hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
8b416c7ae2e62481514ba36d6e81f887758c427f
474
cpp
C++
154/findMin.cpp
Lixu518/leetcode
f8e868ef6963da92237e6dc6888d7dda0b9bdd19
[ "MIT" ]
1
2018-06-24T13:58:07.000Z
2018-06-24T13:58:07.000Z
154/findMin.cpp
Lixu518/leetcode
f8e868ef6963da92237e6dc6888d7dda0b9bdd19
[ "MIT" ]
null
null
null
154/findMin.cpp
Lixu518/leetcode
f8e868ef6963da92237e6dc6888d7dda0b9bdd19
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int findMin(vector<int>&nums){ int left = 0, right = nums.size() - 1; while(left < right){ int mid = (left + right)>>1; if(nums[left] < nums[right]) right = mid; else if(nums[mid] > nums[right]) left = mid + 1; else right--; } return nums[left]; } int main(){ vector<int>nums = {10,10,1,10,10}; cout<<"The min num is: "<<findMin(nums)<<endl; return 0; }
23.7
56
0.561181
Lixu518
8b427a4a94297484826d12e8ac381edcca1697d7
7,362
cpp
C++
libgpopt/src/operators/CPhysicalStreamAgg.cpp
hsyuan/gporca
793b1dd7f55eb0e97f829e9e3b58d2a3133cf7ad
[ "ECL-2.0", "Apache-2.0" ]
466
2016-01-26T18:07:03.000Z
2022-03-30T06:08:55.000Z
libgpopt/src/operators/CPhysicalStreamAgg.cpp
hsyuan/gporca
793b1dd7f55eb0e97f829e9e3b58d2a3133cf7ad
[ "ECL-2.0", "Apache-2.0" ]
463
2016-01-26T19:13:02.000Z
2022-03-24T03:08:13.000Z
libgpopt/src/operators/CPhysicalStreamAgg.cpp
hsyuan/gporca
793b1dd7f55eb0e97f829e9e3b58d2a3133cf7ad
[ "ECL-2.0", "Apache-2.0" ]
203
2016-01-26T13:46:35.000Z
2022-03-22T03:17:06.000Z
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CPhysicalStreamAgg.cpp // // @doc: // Implementation of stream aggregation operator //--------------------------------------------------------------------------- #include "gpopt/operators/CPhysicalStreamAgg.h" #include "gpos/base.h" #include "gpopt/base/CColRefSetIter.h" #include "gpopt/base/CDistributionSpecHashed.h" #include "gpopt/base/CDistributionSpecSingleton.h" #include "gpopt/base/CKeyCollection.h" #include "gpopt/base/COptCtxt.h" #include "gpopt/base/CUtils.h" #include "gpopt/operators/CExpressionHandle.h" using namespace gpopt; //--------------------------------------------------------------------------- // @function: // CPhysicalStreamAgg::CPhysicalStreamAgg // // @doc: // Ctor // //--------------------------------------------------------------------------- CPhysicalStreamAgg::CPhysicalStreamAgg( CMemoryPool *mp, CColRefArray *colref_array, CColRefArray *pdrgpcrMinimal, COperator::EGbAggType egbaggtype, BOOL fGeneratesDuplicates, CColRefArray *pdrgpcrArgDQA, BOOL fMultiStage, BOOL isAggFromSplitDQA, CLogicalGbAgg::EAggStage aggStage, BOOL should_enforce_distribution) : CPhysicalAgg(mp, colref_array, pdrgpcrMinimal, egbaggtype, fGeneratesDuplicates, pdrgpcrArgDQA, fMultiStage, isAggFromSplitDQA, aggStage, should_enforce_distribution), m_pos(NULL) { GPOS_ASSERT(NULL != m_pdrgpcrMinimal); m_pcrsMinimalGrpCols = GPOS_NEW(mp) CColRefSet(mp, m_pdrgpcrMinimal); InitOrderSpec(mp, m_pdrgpcrMinimal); } //--------------------------------------------------------------------------- // @function: // CPhysicalStreamAgg::InitOrderSpec // // @doc: // Initialize the order spec using the given array of columns // //--------------------------------------------------------------------------- void CPhysicalStreamAgg::InitOrderSpec(CMemoryPool *mp, CColRefArray *pdrgpcrOrder) { GPOS_ASSERT(NULL != pdrgpcrOrder); CRefCount::SafeRelease(m_pos); m_pos = GPOS_NEW(mp) COrderSpec(mp); const ULONG size = pdrgpcrOrder->Size(); for (ULONG ul = 0; ul < size; ul++) { CColRef *colref = (*pdrgpcrOrder)[ul]; // TODO: 12/21/2011 - ; this seems broken: a colref must not embed // a pointer to a cached object gpmd::IMDId *mdid = colref->RetrieveType()->GetMdidForCmpType(IMDType::EcmptL); mdid->AddRef(); m_pos->Append(mdid, colref, COrderSpec::EntLast); } } //--------------------------------------------------------------------------- // @function: // CPhysicalStreamAgg::~CPhysicalStreamAgg // // @doc: // Dtor // //--------------------------------------------------------------------------- CPhysicalStreamAgg::~CPhysicalStreamAgg() { m_pcrsMinimalGrpCols->Release(); m_pos->Release(); } //--------------------------------------------------------------------------- // @function: // CPhysicalStreamAgg::PosCovering // // @doc: // Construct order spec on grouping column so that it covers required // order spec, the function returns NULL if no covering order spec // can be created // //--------------------------------------------------------------------------- COrderSpec * CPhysicalStreamAgg::PosCovering(CMemoryPool *mp, COrderSpec *posRequired, CColRefArray *pdrgpcrGrp) const { GPOS_ASSERT(NULL != posRequired); if (0 == posRequired->UlSortColumns()) { // required order must be non-empty return NULL; } // create a set of required sort columns CColRefSet *pcrsReqd = posRequired->PcrsUsed(mp); COrderSpec *pos = NULL; CColRefSet *pcrsGrpCols = GPOS_NEW(mp) CColRefSet(mp, pdrgpcrGrp); if (pcrsGrpCols->ContainsAll(pcrsReqd)) { // required order columns are included in grouping columns, we can // construct a covering order spec pos = GPOS_NEW(mp) COrderSpec(mp); // extract order expressions from required order const ULONG ulReqdSortCols = posRequired->UlSortColumns(); for (ULONG ul = 0; ul < ulReqdSortCols; ul++) { CColRef *colref = const_cast<CColRef *>(posRequired->Pcr(ul)); IMDId *mdid = posRequired->GetMdIdSortOp(ul); COrderSpec::ENullTreatment ent = posRequired->Ent(ul); mdid->AddRef(); pos->Append(mdid, colref, ent); } // augment order with remaining grouping columns const ULONG size = pdrgpcrGrp->Size(); for (ULONG ul = 0; ul < size; ul++) { CColRef *colref = (*pdrgpcrGrp)[ul]; if (!pcrsReqd->FMember(colref)) { IMDId *mdid = colref->RetrieveType()->GetMdidForCmpType(IMDType::EcmptL); mdid->AddRef(); pos->Append(mdid, colref, COrderSpec::EntLast); } } } pcrsGrpCols->Release(); pcrsReqd->Release(); return pos; } //--------------------------------------------------------------------------- // @function: // CPhysicalStreamAgg::PosRequiredStreamAgg // // @doc: // Compute required sort columns of the n-th child // //--------------------------------------------------------------------------- COrderSpec * CPhysicalStreamAgg::PosRequiredStreamAgg(CMemoryPool *mp, CExpressionHandle &exprhdl, COrderSpec *posRequired, ULONG #ifdef GPOS_DEBUG child_index #endif // GPOS_DEBUG , CColRefArray *pdrgpcrGrp) const { GPOS_ASSERT(0 == child_index); COrderSpec *pos = PosCovering(mp, posRequired, pdrgpcrGrp); if (NULL == pos) { // failed to find a covering order spec, use local order spec m_pos->AddRef(); pos = m_pos; } // extract sort columns from order spec CColRefSet *pcrs = pos->PcrsUsed(mp); // get key collection of the relational child CKeyCollection *pkc = exprhdl.DeriveKeyCollection(0); if (NULL != pkc && pkc->FKey(pcrs, false /*fExactMatch*/)) { CColRefSet *pcrsReqd = posRequired->PcrsUsed(m_mp); BOOL fUsesDefinedCols = FUnaryUsesDefinedColumns(pcrsReqd, exprhdl); pcrsReqd->Release(); if (!fUsesDefinedCols) { // we are grouping on child's key, // stream agg does not need to sort child and we can pass through input spec pos->Release(); posRequired->AddRef(); pos = posRequired; } } pcrs->Release(); return pos; } //--------------------------------------------------------------------------- // @function: // CPhysicalStreamAgg::PosDerive // // @doc: // Derive sort order // //--------------------------------------------------------------------------- COrderSpec * CPhysicalStreamAgg::PosDerive(CMemoryPool *, // mp CExpressionHandle &exprhdl) const { return PosDerivePassThruOuter(exprhdl); } //--------------------------------------------------------------------------- // @function: // CPhysicalStreamAgg::EpetOrder // // @doc: // Return the enforcing type for order property based on this operator // //--------------------------------------------------------------------------- CEnfdProp::EPropEnforcingType CPhysicalStreamAgg::EpetOrder(CExpressionHandle &exprhdl, const CEnfdOrder *peo) const { GPOS_ASSERT(NULL != peo); GPOS_ASSERT(!peo->PosRequired()->IsEmpty()); // get the order delivered by the stream agg node COrderSpec *pos = CDrvdPropPlan::Pdpplan(exprhdl.Pdp())->Pos(); if (peo->FCompatible(pos)) { // required order will be established by the stream agg operator return CEnfdProp::EpetUnnecessary; } // required order will be enforced on limit's output return CEnfdProp::EpetRequired; } // EOF
28.099237
79
0.591144
hsyuan
8b4417699e581d52667e23b09518dd06b16010cc
2,727
cpp
C++
libvast/test/system/explorer.cpp
frerich/vast
decac739ea4782ab91a1cee791ecd754b066419f
[ "BSD-3-Clause" ]
null
null
null
libvast/test/system/explorer.cpp
frerich/vast
decac739ea4782ab91a1cee791ecd754b066419f
[ "BSD-3-Clause" ]
null
null
null
libvast/test/system/explorer.cpp
frerich/vast
decac739ea4782ab91a1cee791ecd754b066419f
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #define SUITE explorer #include "vast/test/test.hpp" #include "vast/system/spawn_explorer.hpp" #include "vast/time.hpp" #include <caf/settings.hpp> using namespace std::chrono_literals; TEST(explorer config) { { MESSAGE("Specifying no options at all is not allowed."); caf::settings settings; [[maybe_unused]] auto& explore = settings["explore"].as_dictionary(); CHECK_NOT_EQUAL(vast::system::explorer_validate_args(settings), caf::none); } { MESSAGE("Specifying only time is allowed, as long as it is > 0."); caf::settings settings; auto& explore = settings["explore"].as_dictionary(); explore["before"] = "0s"; explore["after"] = "0s"; CHECK_NOT_EQUAL(vast::system::explorer_validate_args(settings), caf::none); explore["after"] = "10s"; std::cerr << caf::to_string(settings) << std::endl; CHECK_EQUAL(vast::system::explorer_validate_args(settings), caf::none); } { MESSAGE("Specifying only 'by' is allowed."); caf::settings settings; auto& explore = settings["explore"].as_dictionary(); explore["by"] = "0s"; CHECK_EQUAL(vast::system::explorer_validate_args(settings), caf::none); } { MESSAGE("Malformed input is not allowed."); caf::settings settings; auto& explore = settings["after"].as_dictionary(); explore["by"] = "MIP = RE"; CHECK_NOT_EQUAL(vast::system::explorer_validate_args(settings), caf::none); } { MESSAGE("Specifying all options is fine."); caf::settings settings; auto& explore = settings["explore"].as_dictionary(); explore["before"] = vast::duration{10s}; explore["after"] = vast::duration{10s}; explore["by"] = "foo"; CHECK_EQUAL(vast::system::explorer_validate_args(settings), caf::none); } }
38.408451
80
0.548588
frerich
8b45d902b014a3502d3b0d1b9d8c126e12f12b20
10,695
cpp
C++
src/nbl/asset/interchange/CImageLoaderPNG.cpp
devshgraphicsprogramming/Nabla
5588c69ac714734ca50b5d3c1409fed88b258bff
[ "Apache-2.0" ]
null
null
null
src/nbl/asset/interchange/CImageLoaderPNG.cpp
devshgraphicsprogramming/Nabla
5588c69ac714734ca50b5d3c1409fed88b258bff
[ "Apache-2.0" ]
null
null
null
src/nbl/asset/interchange/CImageLoaderPNG.cpp
devshgraphicsprogramming/Nabla
5588c69ac714734ca50b5d3c1409fed88b258bff
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2019 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine" and was originally part of the "Irrlicht Engine" // For conditions of distribution and use, see copyright notice in nabla.h // See the original file in irrlicht source for authors #include "nbl/asset/ICPUImageView.h" #include "nbl/asset/interchange/IImageAssetHandlerBase.h" #include "nbl/system/ISystem.h" using namespace nbl; using namespace system; using namespace core; #ifdef _NBL_COMPILE_WITH_PNG_LOADER_ #include "CImageLoaderPNG.h" #ifdef _NBL_COMPILE_WITH_LIBPNG_ # include "libpng/png.h" #endif // _NBL_COMPILE_WITH_LIBPNG_ #include "nbl/system/IFile.h" namespace nbl { namespace asset { #ifdef _NBL_COMPILE_WITH_LIBPNG_ // PNG function for error handling void updateFilePos(png_structp png_pt, size_t new_file_pos) { auto ptr = (CImageLoaderPng::SContext*)png_get_user_chunk_ptr(png_pt); ptr->file_pos = new_file_pos; png_set_read_user_chunk_fn(png_pt, ptr, nullptr); } static void png_cpexcept_error(png_structp png_ptr, png_const_charp msg) { auto ctx = (CImageLoaderPng::SContext*)png_get_user_chunk_ptr(png_ptr); ctx->logger.log("PNG fatal error %s", system::ILogger::ELL_ERROR, msg); longjmp(png_jmpbuf(png_ptr), 1); } // PNG function for warning handling static void png_cpexcept_warn(png_structp png_ptr, png_const_charp msg) { auto ctx = (CImageLoaderPng::SContext*)png_get_user_chunk_ptr(png_ptr); ctx->logger.log("PNG warning", system::ILogger::ELL_WARNING); // png loader prints stuff that android fails to process } // PNG function for file reading void PNGAPI user_read_data_fcn(png_structp png_pt, png_bytep data, png_size_t length) { png_size_t check; auto* userData = (CImageLoaderPng::SContext*)png_get_user_chunk_ptr(png_pt); size_t file_pos = userData->file_pos; system::IFile* file=(system::IFile*)png_get_io_ptr(png_pt); system::ISystem::future_t<size_t> future; file->read(future, data, file_pos, length); check = future.get(); file_pos += length; updateFilePos(png_pt, file_pos); if (check != length) png_error(png_pt, "Read Error"); } #endif // _NBL_COMPILE_WITH_LIBPNG_ //! returns true if the file maybe is able to be loaded by this class bool CImageLoaderPng::isALoadableFileFormat(system::IFile* _file, const system::logger_opt_ptr logger) const { #ifdef _NBL_COMPILE_WITH_LIBPNG_ if (!_file) return false; png_byte buffer[8]; // Read the first few bytes of the PNG _file system::IFile::success_t success; _file->read(success, buffer, 0, sizeof(buffer)); if (!success) return false; // Check if it really is a PNG _file return !png_sig_cmp(buffer, 0, 8); #else return false; #endif // _NBL_COMPILE_WITH_LIBPNG_ } // load in the image data asset::SAssetBundle CImageLoaderPng::loadAsset(system::IFile* _file, const asset::IAssetLoader::SAssetLoadParams& _params, asset::IAssetLoader::IAssetLoaderOverride* _override, uint32_t _hierarchyLevel) { #ifdef _NBL_COMPILE_WITH_LIBPNG_ if (!_file) return {}; uint32_t imageSize[3] = { 1,1,1 }; uint32_t& Width = imageSize[0]; uint32_t& Height = imageSize[1]; //Used to point to image rows uint8_t** RowPointers = 0; png_byte buffer[8]; // Read the first few bytes of the PNG _file system::IFile::success_t success; _file->read(success, buffer, 0, sizeof(buffer)); if (!success) { _params.logger.log("LOAD PNG: can't read _file\n", system::ILogger::ELL_ERROR, _file->getFileName().string()); return {}; } // Check if it really is a PNG _file if( png_sig_cmp(buffer, 0, 8) ) { _params.logger.log("LOAD PNG: not really a png\n", system::ILogger::ELL_ERROR, _file->getFileName().string().c_str()); return {}; } // Allocate the png read struct png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, (png_error_ptr)png_cpexcept_error, (png_error_ptr)png_cpexcept_warn); if (!png_ptr) { _params.logger.log("LOAD PNG: Internal PNG create read struct failure\n", system::ILogger::ELL_ERROR, _file->getFileName().string().c_str()); return {}; } // Allocate the png info struct png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { _params.logger.log("LOAD PNG: Internal PNG create info struct failure\n", system::ILogger::ELL_ERROR, _file->getFileName().string().c_str()); png_destroy_read_struct(&png_ptr, nullptr, nullptr); return {}; } // for proper error handling if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); if (RowPointers) _NBL_DELETE_ARRAY(RowPointers, Height); return {}; } SContext usrData(_params.logger); png_set_read_user_chunk_fn(png_ptr, &usrData, nullptr); png_set_read_fn(png_ptr, _file, user_read_data_fcn); png_set_sig_bytes(png_ptr, 8); // Tell png that we read the signature png_read_info(png_ptr, info_ptr); // Read the info section of the png _file int32_t BitDepth; int32_t ColorType; { // Use temporary variables to avoid passing casted pointers png_uint_32 w,h; // Extract info png_get_IHDR(png_ptr, info_ptr, &w, &h, &BitDepth, &ColorType, nullptr, nullptr, nullptr); Width=w; Height=h; } if (ColorType == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png_ptr); // Convert low bit colors to 8 bit colors if (BitDepth < 8) { switch (ColorType) { case PNG_COLOR_TYPE_GRAY: case PNG_COLOR_TYPE_GRAY_ALPHA: png_set_expand_gray_1_2_4_to_8(png_ptr); break; default: png_set_packing(png_ptr); } } // Add an alpha channel if transparency information is found in tRNS chunk if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr); // Convert high bit colors to 8 bit colors if (BitDepth == 16) png_set_strip_16(png_ptr); int intent; const double screen_gamma = 2.2; if (png_get_sRGB(png_ptr, info_ptr, &intent)) png_set_gamma(png_ptr, screen_gamma, 0.45455); else { double image_gamma; if (png_get_gAMA(png_ptr, info_ptr, &image_gamma)) png_set_gamma(png_ptr, screen_gamma, image_gamma); else png_set_gamma(png_ptr, screen_gamma, 0.45455); } // Update the changes in between, as we need to get the new color type // for proper processing of the RGBA type png_read_update_info(png_ptr, info_ptr); { // Use temporary variables to avoid passing casted pointers png_uint_32 w,h; // Extract info png_get_IHDR(png_ptr, info_ptr, &w, &h, &BitDepth, &ColorType, nullptr, nullptr, nullptr); Width = w; Height = h; } // Create the image structure to be filled by png data ICPUImage::SCreationParams imgInfo; imgInfo.type = ICPUImage::ET_2D; imgInfo.extent.width = Width; imgInfo.extent.height = Height; imgInfo.extent.depth = 1u; imgInfo.mipLevels = 1u; imgInfo.arrayLayers = 1u; imgInfo.samples = ICPUImage::ESCF_1_BIT; imgInfo.flags = static_cast<IImage::E_CREATE_FLAGS>(0u); core::smart_refctd_ptr<ICPUImage> image = nullptr; bool lumaAlphaType = false; switch (ColorType) { case PNG_COLOR_TYPE_RGB_ALPHA: imgInfo.format = EF_R8G8B8A8_SRGB; break; case PNG_COLOR_TYPE_RGB: imgInfo.format = EF_R8G8B8_SRGB; break; case PNG_COLOR_TYPE_GRAY: imgInfo.format = EF_R8_SRGB; break; case PNG_COLOR_TYPE_GRAY_ALPHA: imgInfo.format = EF_R8G8B8A8_SRGB; lumaAlphaType = true; break; default: { _params.logger.log("Unsupported PNG colorspace (only RGB/RGBA/8-bit grayscale), operation aborted.", system::ILogger::ELL_ERROR); return {}; } } // Create array of pointers to rows in image data RowPointers = _NBL_NEW_ARRAY(png_bytep, Height); if (!RowPointers) { _params.logger.log("LOAD PNG: Internal PNG create row pointers failure\n", system::ILogger::ELL_ERROR, _file->getFileName().string().c_str()); png_destroy_read_struct(&png_ptr, nullptr, nullptr); return {}; } auto dimension = asset::getBlockDimensions(imgInfo.format); assert(dimension.X == 1 && dimension.Y == 1 && dimension.Z == 1); const uint32_t texelFormatBytesize = getTexelOrBlockBytesize(imgInfo.format); auto regions = core::make_refctd_dynamic_array<core::smart_refctd_dynamic_array<ICPUImage::SBufferCopy>>(1u); ICPUImage::SBufferCopy& region = regions->front(); region.imageSubresource.aspectMask = IImage::E_ASPECT_FLAGS::EAF_COLOR_BIT; region.imageSubresource.mipLevel = 0u; region.imageSubresource.baseArrayLayer = 0u; region.imageSubresource.layerCount = 1u; region.bufferOffset = 0u; region.bufferRowLength = asset::IImageAssetHandlerBase::calcPitchInBlocks(Width, texelFormatBytesize); region.bufferImageHeight = 0u; //tightly packed region.imageOffset = { 0u, 0u, 0u }; region.imageExtent = imgInfo.extent; auto texelBuffer = core::make_smart_refctd_ptr<ICPUBuffer>(region.bufferRowLength * region.imageExtent.height * texelFormatBytesize); // Fill array of pointers to rows in image data const uint32_t pitch = region.bufferRowLength*texelFormatBytesize; uint8_t* data = reinterpret_cast<uint8_t*>(texelBuffer->getPointer()); for (uint32_t i=0; i<Height; ++i) { RowPointers[i] = (png_bytep)data; data += pitch; } // for proper error handling if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); _NBL_DELETE_ARRAY(RowPointers, Height); return {}; } // Read data using the library function that handles all transformations including interlacing png_read_image(png_ptr, RowPointers); png_read_end(png_ptr, nullptr); if (lumaAlphaType) { assert(imgInfo.format==asset::EF_R8G8B8A8_SRGB); for (uint32_t i=0u; i<Height; ++i) for (uint32_t j=0u; j<Width;) { uint32_t in = reinterpret_cast<uint16_t*>(RowPointers[i])[j]; j++; auto& out = reinterpret_cast<uint32_t*>(RowPointers[i])[Width-j]; out = in|(in << 16u); // LXLA out &= 0xffff00ffu; out |= (in&0xffu) << 8u; } } _NBL_DELETE_ARRAY(RowPointers, Height); png_destroy_read_struct(&png_ptr,&info_ptr, 0); // Clean up memory #else return {}; #endif // _NBL_COMPILE_WITH_LIBPNG_ image = ICPUImage::create(std::move(imgInfo)); if (!image) { _params.logger.log("LOAD PNG: Internal PNG create image struct failure\n", system::ILogger::ELL_ERROR, _file->getFileName().string().c_str()); png_destroy_read_struct(&png_ptr, nullptr, nullptr); return {}; } image->setBufferAndRegions(std::move(texelBuffer), regions); if (imgInfo.format == asset::EF_R8_SRGB) image = asset::IImageAssetHandlerBase::convertR8ToR8G8B8Image(image, _params.logger); return SAssetBundle(nullptr,{image}); } }// end namespace nbl }//end namespace video #endif
30.29745
202
0.729406
devshgraphicsprogramming
8b46e273ecf38a4758330f62f7b3286c9280ef6f
3,895
hpp
C++
sprout/algorithm/all_of.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
sprout/algorithm/all_of.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
sprout/algorithm/all_of.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2017 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout 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 SPROUT_ALGORITHM_ALL_OF_HPP #define SPROUT_ALGORITHM_ALL_OF_HPP #include <iterator> #include <type_traits> #include <sprout/config.hpp> #include <sprout/iterator/operation.hpp> #include <sprout/iterator/type_traits/category.hpp> #include <sprout/utility/pair/pair.hpp> namespace sprout { namespace detail { template<typename RandomAccessIterator, typename Predicate> inline SPROUT_CONSTEXPR bool all_of_impl_ra( RandomAccessIterator const& first, RandomAccessIterator const& last, Predicate pred, typename std::iterator_traits<RandomAccessIterator>::difference_type pivot ) { return pivot == 0 ? pred(*first) : sprout::detail::all_of_impl_ra( first, sprout::next(first, pivot), pred, pivot / 2 ) && sprout::detail::all_of_impl_ra( sprout::next(first, pivot), last, pred, (sprout::distance(first, last) - pivot) / 2 ) ; } template<typename RandomAccessIterator, typename Predicate> inline SPROUT_CONSTEXPR typename std::enable_if< sprout::is_constant_distance_iterator<RandomAccessIterator>::value, bool >::type all_of( RandomAccessIterator const& first, RandomAccessIterator const& last, Predicate pred, std::random_access_iterator_tag* ) { return first == last ? true : sprout::detail::all_of_impl_ra(first, last, pred, sprout::distance(first, last) / 2) ; } template<typename InputIterator, typename Predicate> inline SPROUT_CONSTEXPR sprout::pair<InputIterator, bool> all_of_impl_1( sprout::pair<InputIterator, bool> const& current, InputIterator const& last, Predicate pred, typename std::iterator_traits<InputIterator>::difference_type n ) { typedef sprout::pair<InputIterator, bool> type; return !current.second || current.first == last ? current : n == 1 ? pred(*current.first) ? type(sprout::next(current.first), true) : type(current.first, false) : sprout::detail::all_of_impl_1( sprout::detail::all_of_impl_1( current, last, pred, n / 2 ), last, pred, n - n / 2 ) ; } template<typename InputIterator, typename Predicate> inline SPROUT_CONSTEXPR sprout::pair<InputIterator, bool> all_of_impl( sprout::pair<InputIterator, bool> const& current, InputIterator const& last, Predicate pred, typename std::iterator_traits<InputIterator>::difference_type n ) { return !current.second || current.first == last ? current : sprout::detail::all_of_impl( sprout::detail::all_of_impl_1( current, last, pred, n ), last, pred, n * 2 ) ; } template<typename InputIterator, typename Predicate> inline SPROUT_CONSTEXPR bool all_of( InputIterator const& first, InputIterator const& last, Predicate pred, std::input_iterator_tag* ) { typedef sprout::pair<InputIterator, bool> type; return sprout::detail::all_of_impl(type(first, true), last, pred, 1).second; } } // namespace detail // 25.2.1 All of // // recursion depth: // O(log N) // template<typename InputIterator, typename Predicate> inline SPROUT_CONSTEXPR bool all_of(InputIterator first, InputIterator last, Predicate pred) { typedef typename std::iterator_traits<InputIterator>::iterator_category* category; return sprout::detail::all_of(first, last, pred, category()); } } // namespace sprout #endif // #ifndef SPROUT_ALGORITHM_ALL_OF_HPP
33.869565
110
0.666239
kariya-mitsuru
8b483c21bfa42855dabbfd39baef5da2cb4a8a15
1,203
hpp
C++
include/boost/url/rfc/userinfo_bnf.hpp
madmongo1/url
e7c9b0c860abd5fba3b7a20c3b29552a326de7b5
[ "BSL-1.0" ]
null
null
null
include/boost/url/rfc/userinfo_bnf.hpp
madmongo1/url
e7c9b0c860abd5fba3b7a20c3b29552a326de7b5
[ "BSL-1.0" ]
null
null
null
include/boost/url/rfc/userinfo_bnf.hpp
madmongo1/url
e7c9b0c860abd5fba3b7a20c3b29552a326de7b5
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail 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) // // Official repository: https://github.com/CPPAlliance/url // #ifndef BOOST_URL_USERINFO_BNF_HPP #define BOOST_URL_USERINFO_BNF_HPP #include <boost/url/detail/config.hpp> #include <boost/url/error.hpp> #include <boost/url/string.hpp> #include <boost/url/rfc/pct_encoded_bnf.hpp> #include <boost/optional.hpp> namespace boost { namespace urls { /** BNF for userinfo @par BNF @code userinfo = username [ ":" [ password ] ] username = *( unreserved / pct-encoded / sub-delims ) password = *( unreserved / pct-encoded / sub-delims / ":" ) @endcode @see https://datatracker.ietf.org/doc/html/rfc3986#section-3.3 */ struct userinfo_bnf { string_view str; pct_encoded_str username; optional<pct_encoded_str> password; BOOST_URL_DECL friend bool parse( char const*& it, char const* const end, error_code& ec, userinfo_bnf& t); }; } // urls } // boost #endif
21.872727
79
0.670823
madmongo1
8b49a84cd4a8878d58fcf0cd8d072da09adcade8
13,202
hpp
C++
include/pfp/dictionary.hpp
maxrossi91/pfp-data-structures
6c5c1b801573d1c5116297e3cca20d1517c41e7b
[ "MIT" ]
6
2020-06-23T11:46:27.000Z
2021-06-01T09:59:01.000Z
include/pfp/dictionary.hpp
maxrossi91/pfp-data-structures
6c5c1b801573d1c5116297e3cca20d1517c41e7b
[ "MIT" ]
null
null
null
include/pfp/dictionary.hpp
maxrossi91/pfp-data-structures
6c5c1b801573d1c5116297e3cca20d1517c41e7b
[ "MIT" ]
null
null
null
/* pfp-dictionary - prefix free parsing dictionary Copyright (C) 2020 Massimiliano Rossi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ . */ /*! \file dictionary.hpp \brief dictionary.hpp define and build the prefix-free dictionary data structure. \author Massimiliano Rossi \date 03/04/2020 */ #ifndef _PFP_DICTIONARY_HH #define _PFP_DICTIONARY_HH #include <queue> #include <common.hpp> #include <sdsl/rmq_support.hpp> #include <sdsl/int_vector.hpp> extern "C" { #include<gsacak.h> } // TODO: Extend it to integer alphabets class dictionary{ public: std::vector<uint8_t> d; std::vector<uint_t> saD; std::vector<uint_t> isaD; std::vector<int_da> daD; std::vector<int_t> lcpD; sdsl::rmq_succinct_sct<> rmq_lcp_D; sdsl::bit_vector b_d; // Starting position of each phrase in D sdsl::bit_vector::rank_1_type rank_b_d; sdsl::bit_vector::select_1_type select_b_d; std::vector<int_t> colex_daD; sdsl::rmq_succinct_sct<> rmq_colex_daD; sdsl::range_maximum_sct<>::type rMq_colex_daD; std::vector<uint_t> colex_id; bool saD_flag = false; bool isaD_flag = false; bool daD_flag = false; bool lcpD_flag = false; bool rmq_lcp_D_flag = false; typedef size_t size_type; // default constructor for load. dictionary() {} dictionary( std::vector<uint8_t>& d_, size_t w, bool saD_flag_ = true, bool isaD_flag_ = true, bool daD_flag_ = true, bool lcpD_flag_ = true, bool rmq_lcp_D_flag_ = true ): d(d_) { build(saD_flag_, isaD_flag_, daD_flag_, lcpD_flag_, rmq_lcp_D_flag_); //assert(d[0] == Dollar); } dictionary(std::string filename, size_t w, bool saD_flag_ = true, bool isaD_flag_ = true, bool daD_flag_ = true, bool lcpD_flag_ = true, bool rmq_lcp_D_flag_ = true) { // Building dictionary from file std::string tmp_filename = filename + std::string(".dict"); read_file(tmp_filename.c_str(), d); assert(d[0] == Dollar); // Prepending w dollars to d // 1. Count how many dollars there are int i = 0; int n_dollars = 0; while(i < d.size() && d[i++] == Dollar) ++n_dollars; std::vector<uint8_t> dollars(w-n_dollars,Dollar); d.insert(d.begin(), dollars.begin(),dollars.end()); build(saD_flag_, isaD_flag_, daD_flag_, lcpD_flag_, rmq_lcp_D_flag_); } inline size_t length_of_phrase(size_t id){ assert(id > 0); return select_b_d(id+1)-select_b_d(id) - 1; // to remove the EndOfWord } inline size_t n_phrases(){ return rank_b_d(d.size()-1); } void build(bool saD_flag_, bool isaD_flag_, bool daD_flag_, bool lcpD_flag_, bool rmq_lcp_D_flag_){ // Building the bitvector with a 1 in each starting position of each phrase in D b_d.resize(d.size()); for(size_t i = 0; i < b_d.size(); ++i) b_d[i] = false; // bug in resize b_d[0] = true; // Mark the first phrase for(int i = 1; i < d.size(); ++i ) b_d[i] = (d[i-1]==EndOfWord); b_d[d.size()-1] = true; // This is necessary to get the length of the last phrase rank_b_d = sdsl::bit_vector::rank_1_type(&b_d); select_b_d = sdsl::bit_vector::select_1_type(&b_d); assert(!rmq_lcp_D_flag_ || (lcpD_flag || lcpD_flag_)); // TODO: check if it has been already computed if(saD_flag_ && daD_flag_ && lcpD_flag_){ saD.resize(d.size()); lcpD.resize(d.size()); daD.resize(d.size()); // suffix array, LCP array, and Document array of the dictionary. verbose("Computing SA, LCP, and DA of dictionary"); _elapsed_time( gsacak(&d[0],&saD[0],&lcpD[0],&daD[0],d.size()) ); }else if(saD_flag_ && lcpD_flag_){ saD.resize(d.size()); lcpD.resize(d.size()); // suffix array and LCP array of the dictionary. verbose("Computing SA, and LCP of dictionary"); _elapsed_time( gsacak(&d[0],&saD[0],&lcpD[0],nullptr,d.size()) ); } else if(saD_flag_ && daD_flag_){ saD.resize(d.size()); daD.resize(d.size()); // suffix array and LCP array of the dictionary. verbose("Computing SA, and DA of dictionary"); _elapsed_time( gsacak(&d[0],&saD[0],nullptr,&daD[0],d.size()) ); } else if(saD_flag_){ saD.resize(d.size()); // suffix array and LCP array of the dictionary. verbose("Computing SA of dictionary"); _elapsed_time( gsacak(&d[0],&saD[0],nullptr,nullptr,d.size()) ); } assert(!isaD_flag_ || (saD_flag || saD_flag_) ); if(isaD_flag_ && !isaD_flag){ // inverse suffix array of the dictionary. verbose("Computing ISA of dictionary"); _elapsed_time( { isaD.resize(d.size()); for(int i = 0; i < saD.size(); ++i){ isaD[saD[i]] = i; } } ); } assert(!rmq_lcp_D_flag_ || (lcpD_flag || lcpD_flag_)); if(rmq_lcp_D_flag_ && ! rmq_lcp_D_flag){ rmq_lcp_D_flag = true; verbose("Computing RMQ over LCP of dictionary"); // Compute the LCP rank of D _elapsed_time( rmq_lcp_D = sdsl::rmq_succinct_sct<>(&lcpD) ); } // if(colex_daD_flag_){ // co-lex document array of the dictionary. verbose("Computing co-lex DA of dictionary"); _elapsed_time( // { // std::vector<uint_t>colex_id(n_phrases()); // std::vector<uint_t>inv_colex_id(n_phrases()); // I am using it as starting positions // for(int i = 0, j = 0; i < d.size(); ++i ) // if(d[i+1]==EndOfWord){ // colex_id[j] = j; // inv_colex_id[j++] = i; // } // colex_document_array_helper(inv_colex_id,colex_id,0,n_phrases()); // // computing inverse colex id // for(int i = 0; i < colex_id.size(); ++i){ // inv_colex_id[colex_id[i]] = i; // } // colex_id.clear(); // colex_daD.resize(d.size()); // for(int i = 0; i < colex_daD.size(); ++i ){ // colex_daD[i] = inv_colex_id[daD[i]]; // } // } { compute_colex_da(); rmq_colex_daD = sdsl::rmq_succinct_sct<>(&colex_daD); rMq_colex_daD = sdsl::range_maximum_sct<>::type(&colex_daD); } ); // } } // I am assuming that the alphabet fits in an unsigned char void colex_document_array_helper(std::vector<uint_t>& sp, std::vector<uint_t>& id, size_t start, size_t end ){ if((end - start < 2) || (start > end)) return; std::vector<uint32_t> count(256,0); for(size_t i = start; i < end; ++i ){ count[ d[ sp[i] ] ] ++; } std::vector<uint32_t> psum(256,0); for(size_t i = 1; i < 256; ++i){ psum[i] = psum[i-1] + count[i-1]; } std::vector<uint_t> tmp(end-start+1,0); std::vector<uint_t> tmp_id(end-start+1,0); for(size_t i = start; i < end; ++i ){ size_t index = psum[ d[sp[i] ] ] ++; tmp[index] = std::min(sp[i]-1, static_cast<uint_t>(d.size()-1)); tmp_id[index] = id[i]; } // Recursion size_t tmp_start = 0; for(size_t i = 0; i < 256; ++i ){ for(size_t j = 0; j < count[i]; ++j){ sp[start + j] = tmp[tmp_start]; id[start + j] = tmp_id[tmp_start ++]; } end = start + count[i]; if(i > EndOfWord) colex_document_array_helper(sp,id,start,end); start = end; } } void compute_colex_da(){ colex_id.resize(n_phrases()); std::vector<uint_t> inv_colex_id(n_phrases()); // I am using it as starting positions for (int i = 0, j = 0; i < d.size(); ++i) if (d[i + 1] == EndOfWord) { colex_id[j] = j; inv_colex_id[j++] = i; } // buckets stores the begin and the end of each bucket. std::queue<std::pair<int,int> > buckets; // the first bucket is the whole array. buckets.push({0,colex_id.size()}); // for each bucket while(!buckets.empty()){ auto bucket = buckets.front(); buckets.pop(); int start = bucket.first; int end = bucket.second; if ((start < end) && (end - start > 1)) { std::vector<uint32_t> count(256, 0); for (size_t i = start; i < end; ++i) { count[d[inv_colex_id[i]]]++; } std::vector<uint32_t> psum(256, 0); for (size_t i = 1; i < 256; ++i) { psum[i] = psum[i - 1] + count[i - 1]; } std::vector<uint_t> tmp(end - start, 0); std::vector<uint_t> tmp_id(end - start, 0); for (size_t i = start; i < end; ++i) { size_t index = psum[d[inv_colex_id[i]]]++; tmp[index] = std::min(inv_colex_id[i] - 1, static_cast<uint_t>(d.size() - 1)); tmp_id[index] = colex_id[i]; } // Recursion size_t tmp_start = 0; for (size_t i = 0; i < 256; ++i) { for (size_t j = 0; j < count[i]; ++j) { inv_colex_id[start + j] = tmp[tmp_start]; colex_id[start + j] = tmp_id[tmp_start++]; } end = start + count[i]; if (i > EndOfWord){ buckets.push({start, end}); } start = end; } } } // computing inverse colex id for (int i = 0; i < colex_id.size(); ++i) { inv_colex_id[colex_id[i]] = i; } colex_id.clear(); colex_daD.resize(d.size()); for (int i = 0; i < colex_daD.size(); ++i) { colex_daD[i] = inv_colex_id[daD[i]]; } return; } // Serialize to a stream. size_type serialize(std::ostream &out, sdsl::structure_tree_node *v = nullptr, std::string name = "") const { sdsl::structure_tree_node *child = sdsl::structure_tree::add_child(v, name, sdsl::util::class_name(*this)); size_type written_bytes = 0; written_bytes += my_serialize(d, out, child, "dictionary"); written_bytes += my_serialize(saD, out, child, "saD"); written_bytes += my_serialize(isaD, out, child, "isaD"); written_bytes += my_serialize(daD, out, child, "daD"); written_bytes += my_serialize(lcpD, out, child, "lcpD"); written_bytes += rmq_lcp_D.serialize(out, child, "rmq_lcp_D"); written_bytes += b_d.serialize(out, child, "b_d"); written_bytes += rank_b_d.serialize(out, child, "rank_b_d"); written_bytes += select_b_d.serialize(out, child, "select_b_d"); written_bytes += my_serialize(colex_daD, out, child, "colex_daD"); written_bytes += rmq_colex_daD.serialize(out, child, "rmq_colex_daD"); written_bytes += rMq_colex_daD.serialize(out, child, "rMq_colex_daD"); written_bytes += my_serialize(colex_id, out, child, "colex_id"); // written_bytes += sdsl::serialize(d, out, child, "dictionary"); // written_bytes += sdsl::serialize(saD, out, child, "saD"); // written_bytes += sdsl::serialize(isaD, out, child, "isaD"); // written_bytes += sdsl::serialize(daD, out, child, "daD"); // written_bytes += sdsl::serialize(lcpD, out, child, "lcpD"); // written_bytes += rmq_lcp_D.serialize(out, child, "rmq_lcp_D"); // written_bytes += b_d.serialize(out, child, "b_d"); // written_bytes += rank_b_d.serialize(out, child, "rank_b_d"); // written_bytes += select_b_d.serialize(out, child, "select_b_d"); // written_bytes += sdsl::serialize(colex_daD, out, child, "colex_daD"); // written_bytes += rmq_colex_daD.serialize(out, child, "rmq_colex_daD"); // written_bytes += rMq_colex_daD.serialize(out, child, "rMq_colex_daD"); // written_bytes += sdsl::serialize(colex_id, out, child, "colex_id"); sdsl::structure_tree::add_size(child, written_bytes); return written_bytes; } //! Load from a stream. void load(std::istream &in) { my_load(d, in); my_load(saD, in); my_load(isaD, in); my_load(daD, in); my_load(lcpD, in); rmq_lcp_D.load(in); b_d.load(in); rank_b_d.load(in, &b_d); select_b_d.load(in, &b_d); my_load(colex_daD, in); rmq_colex_daD.load(in); rMq_colex_daD.load(in); my_load(colex_id, in); // sdsl::load(d, in); // sdsl::load(saD, in); // sdsl::load(isaD, in); // sdsl::load(daD, in); // sdsl::load(lcpD, in); // rmq_lcp_D.load(in); // b_d.load(in); // rank_b_d.load(in, &b_d); // select_b_d.load(in, &b_d); // sdsl::load(colex_daD, in); // rmq_colex_daD.load(in); // rMq_colex_daD.load(in); // sdsl::load(colex_id, in); } }; #endif /* end of include guard: _PFP_DICTIONARY_HH */
31.136792
112
0.591577
maxrossi91
8b4b0eac349275067c8eda66b9c81b17b3a3648d
4,042
cpp
C++
DeepSkyStacker/SaturationTab.cpp
matdrapes/DSS
ab2c184cb9e03f5acc550df52aa3804f76ea59bb
[ "BSD-3-Clause" ]
4
2018-02-26T09:45:52.000Z
2018-03-04T16:23:37.000Z
DeepSkyStacker/SaturationTab.cpp
matdrapes/DSS
ab2c184cb9e03f5acc550df52aa3804f76ea59bb
[ "BSD-3-Clause" ]
null
null
null
DeepSkyStacker/SaturationTab.cpp
matdrapes/DSS
ab2c184cb9e03f5acc550df52aa3804f76ea59bb
[ "BSD-3-Clause" ]
null
null
null
// SaturationTab.cpp : implementation file // #include "stdafx.h" #include "DeepSkyStacker.h" #include "SaturationTab.h" #include "DeepStackerDlg.h" #include "ProcessingDlg.h" ///////////////////////////////////////////////////////////////////////////// // CSaturationTab property page /* ------------------------------------------------------------------- */ IMPLEMENT_DYNCREATE(CSaturationTab, CChildPropertyPage) CSaturationTab::CSaturationTab() : CChildPropertyPage(CSaturationTab::IDD) { //{{AFX_DATA_INIT(CSaturationTab) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_psp.dwFlags |= PSP_PREMATURE; m_bFirstActivation = true; } CSaturationTab::~CSaturationTab() { } /* ------------------------------------------------------------------- */ void CSaturationTab::DoDataExchange(CDataExchange* pDX) { CChildPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CSaturationTab) DDX_Control(pDX, IDC_UNDO, m_Undo); DDX_Control(pDX, IDC_SETTINGS, m_Settings); DDX_Control(pDX, IDC_REDO, m_Redo); DDX_Control(pDX, IDC_SATURATION, m_Saturation); //}}AFX_DATA_MAP DDX_Control(pDX, IDC_ST_SATURATION, m_ST_Saturation); DDX_Control(pDX, IDC_TEXT_SATURATION, m_SaturationTitle); } /* ------------------------------------------------------------------- */ BEGIN_MESSAGE_MAP(CSaturationTab, CChildPropertyPage) //{{AFX_MSG_MAP(CSaturationTab) ON_BN_CLICKED(IDC_PROCESS, OnProcess) ON_BN_CLICKED(IDC_REDO, OnRedo) ON_BN_CLICKED(IDC_RESET, OnReset) ON_BN_CLICKED(IDC_SETTINGS, OnSettings) ON_BN_CLICKED(IDC_UNDO, OnUndo) ON_WM_HSCROLL() //}}AFX_MSG_MAP END_MESSAGE_MAP() /* ------------------------------------------------------------------- */ ///////////////////////////////////////////////////////////////////////////// // CSaturationTab message handlers void CSaturationTab::OnProcess() { GetParentProcessingDlg(this)->OnProcess(); } /* ------------------------------------------------------------------- */ void CSaturationTab::OnRedo() { GetParentProcessingDlg(this)->OnRedo(); } /* ------------------------------------------------------------------- */ void CSaturationTab::OnReset() { GetParentProcessingDlg(this)->OnReset(); } /* ------------------------------------------------------------------- */ void CSaturationTab::OnSettings() { GetParentProcessingDlg(this)->OnSettings(); } /* ------------------------------------------------------------------- */ void CSaturationTab::OnUndo() { GetParentProcessingDlg(this)->OnUndo(); } /* ------------------------------------------------------------------- */ BOOL CSaturationTab::OnSetActive() { if (m_bFirstActivation) { m_Redo.DrawTransparent(true); m_Undo.DrawTransparent(true); m_Redo.SetFlat(true); m_Undo.SetFlat(true); m_Redo.SetIcon(IDI_REDO, (INT)(size_t)BTNST_AUTO_GRAY); m_Undo.SetIcon(IDI_UNDO, (INT)(size_t)BTNST_AUTO_GRAY); m_Redo.SetTooltipText(IDS_REDOLASTSETTINGS); m_Undo.SetTooltipText(IDS_UNDOLASTSETTINGS); m_Settings.DrawTransparent(true); m_Settings.SetFlat(true); m_Settings.SetIcon(IDI_SETTINGS, (INT)(size_t)BTNST_AUTO_GRAY); m_Settings.SetTooltipText(IDS_MANAGESETTINGS); // m_ST_Saturation.SetBorder(true); m_SaturationTitle.SetTextColor(RGB(0, 0, 0)); m_SaturationTitle.SetBkColor(RGB(224, 244, 252), RGB(138, 185, 242), CLabel::Gradient); m_bFirstActivation = false; }; return CChildPropertyPage::OnSetActive(); } /* ------------------------------------------------------------------- */ void CSaturationTab::UpdateTexts() { CString strText; auto lPos = m_Saturation.GetPos(); strText.Format(_T("%ld %%"), lPos-50); m_ST_Saturation.SetText(strText); }; /* ------------------------------------------------------------------- */ void CSaturationTab::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { // GetParentProcessingDlg(this)->OnHScroll(nSBCode, nPos, pScrollBar); UpdateTexts(); CChildPropertyPage::OnHScroll(nSBCode, nPos, pScrollBar); } /* ------------------------------------------------------------------- */
27.127517
89
0.571994
matdrapes
8b4b78755d976a7d149c91e2a8133c54ea47f193
3,228
hpp
C++
include/gltf2/Exceptions.hpp
Lugdunum3D/glTF2-loader
c2c6b32e65094ddde2a551b8a5bf10ef6ffb07a2
[ "MIT" ]
38
2017-04-19T02:15:57.000Z
2022-01-28T09:43:46.000Z
include/gltf2/Exceptions.hpp
Lugdunum3D/glTF2-loader
c2c6b32e65094ddde2a551b8a5bf10ef6ffb07a2
[ "MIT" ]
2
2017-07-17T07:03:31.000Z
2018-05-08T02:14:02.000Z
include/gltf2/Exceptions.hpp
Lugdunum3D/glTF2-loader
c2c6b32e65094ddde2a551b8a5bf10ef6ffb07a2
[ "MIT" ]
6
2017-06-22T13:52:39.000Z
2022-03-28T08:15:31.000Z
#pragma once #include <string> #include <exception> namespace gltf2 { class MisformattedException: public std::exception { public: explicit MisformattedException(const char* key, const char* what) { _what = std::string("Misformated file: '") + key + "' " + what; } explicit MisformattedException(const std::string& key, const std::string& what) { _what = "Misformated file: '" + key + "' " + what; } virtual ~MisformattedException() throw() {} virtual const char* what() const throw() { return _what.c_str(); } protected: std::string _what; }; class MisformattedExceptionNotNumber: public MisformattedException { public: explicit MisformattedExceptionNotNumber(const char* key) : MisformattedException(key, "is not a number") {} explicit MisformattedExceptionNotNumber(const std::string& key) : MisformattedException(key, "is not a number") {} virtual ~MisformattedExceptionNotNumber() throw() {} }; class MisformattedExceptionNotBoolean: public MisformattedException { public: explicit MisformattedExceptionNotBoolean(const char* key) : MisformattedException(key, "is not a boolean") {} explicit MisformattedExceptionNotBoolean(const std::string& key) : MisformattedException(key, "is not a boolean") {} virtual ~MisformattedExceptionNotBoolean() throw() {} }; class MisformattedExceptionNotString: public MisformattedException { public: explicit MisformattedExceptionNotString(const char* key) : MisformattedException(key, "is not a string") {} explicit MisformattedExceptionNotString(const std::string& key) : MisformattedException(key, "is not a string") {} virtual ~MisformattedExceptionNotString() throw() {} }; class MisformattedExceptionNotArray: public MisformattedException { public: explicit MisformattedExceptionNotArray(const char* key) : MisformattedException(key, "is not an array") {} explicit MisformattedExceptionNotArray(const std::string& key) : MisformattedException(key, "is not an array") {} virtual ~MisformattedExceptionNotArray() throw() {} }; class MisformattedExceptionNotGoodSizeArray: public MisformattedException { public: explicit MisformattedExceptionNotGoodSizeArray(const char* key) : MisformattedException(key, "is not the good size") {} explicit MisformattedExceptionNotGoodSizeArray(const std::string& key) : MisformattedException(key, "is not the good size") {} virtual ~MisformattedExceptionNotGoodSizeArray() throw() {} }; class MisformattedExceptionNotObject: public MisformattedException { public: explicit MisformattedExceptionNotObject(const char* key) : MisformattedException(key, "is not an array") {} explicit MisformattedExceptionNotObject(const std::string& key) : MisformattedException(key, "is not an array") {} virtual ~MisformattedExceptionNotObject() throw() {} }; class MisformattedExceptionIsRequired: public MisformattedException { public: explicit MisformattedExceptionIsRequired(const char* key) : MisformattedException(key, "is required") {} explicit MisformattedExceptionIsRequired(const std::string& key) : MisformattedException(key, "is required") {} virtual ~MisformattedExceptionIsRequired() throw() {} }; }
41.922078
130
0.753717
Lugdunum3D
8b4d68a0668483b9de1b305cf742472641a73746
22,686
cc
C++
tensorflow/core/profiler/utils/group_events.cc
Squadrick/tensorflow
735bb0fc23f70a7bbff8de4d3258b48f2853c0c3
[ "Apache-2.0" ]
null
null
null
tensorflow/core/profiler/utils/group_events.cc
Squadrick/tensorflow
735bb0fc23f70a7bbff8de4d3258b48f2853c0c3
[ "Apache-2.0" ]
null
null
null
tensorflow/core/profiler/utils/group_events.cc
Squadrick/tensorflow
735bb0fc23f70a7bbff8de4d3258b48f2853c0c3
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/profiler/utils/group_events.h" #include <algorithm> #include <functional> #include <iterator> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tensorflow/core/lib/gtl/map_util.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/profiler/protobuf/xplane.pb.h" #include "tensorflow/core/profiler/utils/tf_op_utils.h" #include "tensorflow/core/profiler/utils/tf_xplane_visitor.h" #include "tensorflow/core/profiler/utils/xplane_builder.h" #include "tensorflow/core/profiler/utils/xplane_schema.h" #include "tensorflow/core/profiler/utils/xplane_utils.h" #include "tensorflow/core/profiler/utils/xplane_visitor.h" namespace tensorflow { namespace profiler { namespace { static const int64 kFunctionalOpEventTypes[] = { HostEventType::kCallOp, HostEventType::kNumericalGradientOpEvalRight, HostEventType::kNumericalGradientOpEvalLeft, HostEventType::kSymbolicGradientOp, HostEventType::kRemoteCallOp, HostEventType::kIfOp, HostEventType::kCaseOp, // TODO(b/154510598): Fix handling of the loop ops. // HostEventType::kWhileOpEvalCond, // HostEventType::kWhileOpStartBody, // HostEventType::kForOp, // HostEventType::kParallelForOp, // HostEventType::kForeverOp, HostEventType::kPartitionedCallOp, }; // Creates stat metadata for the stats which may be added by grouping. void CreateStatMetadata(XPlane* plane) { XPlaneBuilder builder(plane); builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kGroupId)); builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kStepName)); builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kIsEager)); } // Returns event type if it is a KernelLaunch or KernelExecute event. absl::optional<int64> GetKernelEventType(const XPlaneVisitor& visitor, const XEvent& event) { for (const auto& stat : event.stats()) { if (visitor.GetStatType(stat) == StatType::kCorrelationId) { // TODO(b/149095099): avoid string comparison. return visitor.Name() == kHostThreads ? HostEventType::kKernelLaunch : HostEventType::kKernelExecute; } } return absl::nullopt; } bool IsTfOpEvent(const XPlaneVisitor& visitor, const XEvent& event) { TfOp tf_op = ParseTfOpFullname(visitor.GetEventMetadata(event.metadata_id())->name()); return tf_op.category == Category::kTensorFlow; } int64 GetEventType(const XPlaneVisitor& visitor, const XEvent& event) { if (absl::optional<int64> event_type = visitor.GetEventType(event)) { return *event_type; } else if (absl::optional<int64> kernel_event_type = GetKernelEventType(visitor, event)) { // KernelLaunch and KernelExecute event types are not supported by // XPlaneVisitor and should be checked separately. // TODO(148346217): Make XPlaneVisitor support KernelLaunch and // KernelExecute event types. return *kernel_event_type; } else if (IsTfOpEvent(visitor, event)) { return HostEventType::kTfOpRun; } else { return HostEventType::kUnknownHostEventType; } } void SetGroupId(const XPlaneVisitor& visitor, int64 group_id, XEvent* event) { AddOrUpdateIntStat(*visitor.GetStatMetadataId(StatType::kGroupId), group_id, event); } void SetContextGroup(EventNode* event, ContextGroupMap* context_groups) { auto producer = event->GetProducerContext(); if (producer.has_value()) { ((*context_groups)[producer->type][producer->id]).producer = event; } auto consumer = event->GetConsumerContext(); if (consumer.has_value()) { ((*context_groups)[consumer->type][consumer->id]) .consumers.push_back(event); } } void ConnectContextGroups(const ContextGroupMap& context_groups) { for (auto& type_id_group : context_groups) { for (auto& id_group : type_id_group.second) { const ContextGroup& group = id_group.second; EventNode* parent = group.producer; for (EventNode* child : group.consumers) { parent->AddChild(child); } } } } std::unique_ptr<XEvent> CreateVirtualEvent(const XStat& step_id_stat, const XStat& iter_num_stat) { auto virtual_event = absl::make_unique<XEvent>(); *virtual_event->add_stats() = step_id_stat; *virtual_event->add_stats() = iter_num_stat; return virtual_event; } bool NeedsVirtualEventsForAsyncExecutor( const std::vector<int64 /*EventType*/>& root_event_types) { return std::find(root_event_types.begin(), root_event_types.end(), HostEventType::kAsyncExecutorTraceContext) != root_event_types.end(); } bool HasFunctionRun(EventNode* event_node) { for (EventNode* child : event_node->GetChildren()) { if (child->GetEventVisitor().Type() == HostEventType::kFunctionRun) { return true; } } return false; } void ProcessRootEvent(int64 group_id, EventNode* root_event, EventGroupNameMap* event_group_name_map) { root_event->PropagateGroupId(group_id); std::string group_name = root_event->GetGroupName(); // TODO(jihochoi): change event name instead. root_event->AddStepName(group_name); event_group_name_map->emplace(group_id, std::move(group_name)); } bool IsTfDataEvent(const EventNode& event_node) { return event_node.FindParent(HostEventType::kTfDataCapturedFunctionRun) || event_node.FindParent( HostEventType::kTfDataCapturedFunctionRunAsync) || event_node.FindParent( HostEventType::kTfDataCapturedFunctionRunInstantiated) || event_node.FindParent( HostEventType::kTfDataCapturedFunctionRunWithBorrowedArgs); } } // namespace EventNode::EventNode(const XPlaneVisitor* plane, XLine* raw_line, XEvent* raw_event) : plane_(plane), visitor_(plane, raw_line, raw_event), raw_line_(raw_line), raw_event_(raw_event) { absl::optional<int> producer_type; absl::optional<uint64> producer_id; absl::optional<int> consumer_type; absl::optional<uint64> consumer_id; visitor_.ForEachStat([&](const XStatVisitor& stat) { if (!stat.Type().has_value()) return; switch (*stat.Type()) { case StatType::kProducerType: producer_type = stat.IntValue(); break; case StatType::kProducerId: producer_id = stat.IntValue(); break; case StatType::kConsumerType: consumer_type = stat.IntValue(); break; case StatType::kConsumerId: consumer_id = stat.IntValue(); break; case StatType::kIsRoot: is_root_ = stat.IntValue(); break; case StatType::kIsAsync: is_async_ = stat.IntValue(); break; default: break; } }); if (producer_type.has_value() && producer_id.has_value()) { producer_context_ = {*producer_type, *producer_id}; } if (consumer_type.has_value() && consumer_id.has_value()) { consumer_context_ = {*consumer_type, *consumer_id}; } } EventNode::EventNode(const EventNode& event_node) : EventNode(event_node.plane_, event_node.raw_line_, event_node.raw_event_) {} const XStat* EventNode::GetContextStat(int64 stat_type) const { if (const XStat* stat = visitor_.GetStats(stat_type)) { return stat; } else if (parent_) { return parent_->GetContextStat(stat_type); } return nullptr; } std::string EventNode::GetGroupName() const { std::vector<std::string> name_parts; if (const XStat* graph_type_stat = GetContextStat(StatType::kGraphType)) { XStatVisitor stat(plane_, graph_type_stat); name_parts.push_back(stat.ToString()); } int64 step_num = group_id_.value_or(0); if (const XStat* step_num_stat = GetContextStat(StatType::kStepNum)) { step_num = step_num_stat->int64_value(); } if (const XStat* iter_num_stat = GetContextStat(StatType::kIterNum)) { step_num = iter_num_stat->int64_value(); } name_parts.push_back(absl::StrCat(step_num)); return absl::StrJoin(name_parts, " "); } void EventNode::PropagateGroupId(int64 group_id) { group_id_ = group_id; SetGroupId(*plane_, group_id, raw_event_); for (const auto& child : children_) { // Skip if it already belongs to a group. Some nodes may be added multiple // times as child (e.g., sometimes async ops are executed synchronously and // their nodes are added as child both in ConnectIntraThread and // ConnectInterThread). if (child->GetGroupId()) continue; child->PropagateGroupId(*group_id_); } } void EventNode::AddStepName(absl::string_view step_name) { AddOrUpdateStrStat(*plane_->GetStatMetadataId(StatType::kStepName), step_name, raw_event_); } void EventNode::SetIsEager(bool is_eager) { AddOrUpdateIntStat(*plane_->GetStatMetadataId(StatType::kIsEager), is_eager ? 1 : 0, raw_event_); } bool EventNode::IsEager() { // It is eagerly executed if its trace context includes the EagerKernelExecute // event (which may execute an op eagerly or through the TF executor) but not // the TF executor event. return FindParent(HostEventType::kExecutorStateProcess) == nullptr && FindParent(HostEventType::kEagerKernelExecute) != nullptr; } EventNode* EventNode::FindParent(int64 event_type) const { if (parent_) { if (parent_->GetEventVisitor().Type() == event_type) { return parent_; } return parent_->FindParent(event_type); } return nullptr; } bool EventNode::StartsBefore(const EventNode& other) const { return GetEventVisitor().TimestampPs() <= other.GetEventVisitor().TimestampPs(); } void EventForest::ConnectIntraThread(const XPlaneVisitor& visitor, XPlane* plane, ContextGroupMap* context_groups) { for (auto& line : *plane->mutable_lines()) { std::vector<EventNode*> parent_nodes; for (auto& event : *line.mutable_events()) { auto cur_node = absl::make_unique<EventNode>(&visitor, &line, &event); // Update `context_groups` for `ConnectInterThread`. SetContextGroup(cur_node.get(), context_groups); // Update `root_events_` for `CreateEventGroup`. if (cur_node->IsRoot()) root_events_.push_back(cur_node.get()); // Async events are ignored when processing the nesting relationship. if (cur_node->IsAsync()) continue; while (!parent_nodes.empty()) { EventNode* parent_node = parent_nodes.back(); if (parent_node->GetEventVisitor().GetTimespan().Includes( cur_node->GetEventVisitor().GetTimespan())) { parent_node->AddChild(cur_node.get()); break; } else { parent_nodes.pop_back(); } } parent_nodes.push_back(cur_node.get()); // event_node_map_ keeps cur_node alive. event_node_map_[GetEventType(visitor, event)].push_back( std::move(cur_node)); } } } void EventForest::ConnectInterThread( const std::vector<InterThreadConnectInfo>& connect_info_list) { for (const auto& connect_info : connect_info_list) { absl::flat_hash_map<std::vector<int64>, EventNode*> connect_map; const std::vector<int64>& parent_stat_types = connect_info.parent_stat_types; const std::vector<int64>* child_stat_types = &connect_info.child_stat_types; if (child_stat_types->empty()) { child_stat_types = &parent_stat_types; } if (auto parent_event_node_list = gtl::FindOrNull(event_node_map_, connect_info.parent_event_type)) { for (const auto& parent_event_node : *parent_event_node_list) { std::vector<int64> stats; for (auto stat_type : parent_stat_types) { const XStat* stat = parent_event_node->GetContextStat(stat_type); if (!stat) break; stats.push_back(stat->value_case() == stat->kInt64Value ? stat->int64_value() : stat->uint64_value()); } if (stats.size() == parent_stat_types.size()) { connect_map[stats] = parent_event_node.get(); } } } if (auto child_event_node_list = gtl::FindOrNull(event_node_map_, connect_info.child_event_type)) { for (const auto& child_event_node : *child_event_node_list) { std::vector<int64> stats; for (auto stat_type : *child_stat_types) { const XStat* stat = child_event_node->GetContextStat(stat_type); if (!stat) break; stats.push_back(stat->value_case() == stat->kInt64Value ? stat->int64_value() : stat->uint64_value()); } if (stats.size() == child_stat_types->size()) { if (auto parent_event_node = gtl::FindPtrOrNull(connect_map, stats)) { parent_event_node->AddChild(child_event_node.get()); } } } } } } void EventForest::CreateEventGroup( const std::vector<int64 /*EventType*/>& root_event_types) { for (EventNode* root_event : tf_loop_root_events_) { ProcessRootEvent(next_group_id_++, root_event, &event_group_name_map_); } for (EventNode* root_event : root_events_) { ProcessRootEvent(next_group_id_++, root_event, &event_group_name_map_); } for (int64 root_event_type : root_event_types) { if (auto root_events = gtl::FindOrNull(event_node_map_, root_event_type)) { for (const auto& root_event : *root_events) { // Skip if it already belongs to a group. if (root_event->GetGroupId()) continue; ProcessRootEvent(next_group_id_++, root_event.get(), &event_group_name_map_); } // Only use the first root event type found. if (!root_events->empty()) break; } } } void EventForest::MarkEagerlyExecutedGpuKernels() { auto kernel_execute_event_node_list = gtl::FindOrNull(event_node_map_, HostEventType::kKernelExecute); if (!kernel_execute_event_node_list) return; for (auto& kernel_execute_event_node : *kernel_execute_event_node_list) { kernel_execute_event_node->SetIsEager(kernel_execute_event_node->IsEager()); } } void EventForest::MarkEagerlyExecutedCpuTfOps() { auto tf_op_run_event_node_list = gtl::FindOrNull(event_node_map_, HostEventType::kTfOpRun); if (!tf_op_run_event_node_list) return; for (auto& tf_op_run_event_node : *tf_op_run_event_node_list) { tf_op_run_event_node->SetIsEager(tf_op_run_event_node->IsEager()); } } void EventForest::ProcessTensorFlowLoop() { struct TensorFlowLoopIteration { EventNode* first_event = nullptr; std::vector<EventNode*> events; }; using TensorFlowLoop = std::map<int64 /*iter_num*/, TensorFlowLoopIteration>; absl::flat_hash_map<int64 /*step_id*/, TensorFlowLoop> tf_loops; // Sort the TF executor events by TF function/session (step_id) and iter_num. auto executor_event_list = gtl::FindOrNull(event_node_map_, HostEventType::kExecutorStateProcess); if (!executor_event_list) return; for (auto& executor_event : *executor_event_list) { if (IsTfDataEvent(*executor_event)) continue; const XStat* step_id_stat = executor_event->GetContextStat(StatType::kStepId); const XStat* iter_num_stat = executor_event->GetContextStat(StatType::kIterNum); if (!step_id_stat || !iter_num_stat) continue; int64 step_id = step_id_stat->int64_value(); TensorFlowLoop& tf_loop = tf_loops[step_id]; TensorFlowLoopIteration& iteration = tf_loop[iter_num_stat->int64_value()]; if (!iteration.first_event || executor_event->StartsBefore(*iteration.first_event)) { iteration.first_event = executor_event.get(); } iteration.events.push_back(executor_event.get()); } // Sort the TF loops by start time. std::map<int64 /*start_time*/, int64 /*step_id*/> sorted_tf_loops; for (const auto& step_id_and_tf_loop : tf_loops) { auto& iterations = step_id_and_tf_loop.second; // Filter out TF function/session without loops. if (iterations.size() == 1 && iterations.count(0)) continue; int64 start_time = iterations.cbegin() ->second.first_event->GetEventVisitor() .TimestampPs(); DCHECK_EQ(sorted_tf_loops.count(start_time), 0); sorted_tf_loops[start_time] = step_id_and_tf_loop.first; } // Register the first event of each iteration as a root event. Also, add the // other events of the iteration as child to the root event. bool next_group_id_updated = false; for (const auto& start_time_and_step_id : sorted_tf_loops) { TensorFlowLoop& tf_loop = tf_loops[start_time_and_step_id.second]; for (auto& iter_num_and_iteration : tf_loop) { if (!next_group_id_updated) { // Set next_group_id_ to the first iter_num of the first TF loop. This // is necessary later when selecting the intersection of the steps from // multiple hosts. next_group_id_ = iter_num_and_iteration.first; next_group_id_updated = true; } TensorFlowLoopIteration& iteration = iter_num_and_iteration.second; EventNode* root_event = iteration.first_event; tf_loop_root_events_.push_back(root_event); for (EventNode* event : iteration.events) { if (event == root_event) continue; root_event->AddChild(event); } } } } void EventForest::CreateVirtualEventsForAsyncExecutor() { auto eager_kernel_execute_event_node_list = gtl::FindOrNull(event_node_map_, HostEventType::kEagerKernelExecute); if (!eager_kernel_execute_event_node_list) return; EventNode* virtual_event_node = nullptr; for (auto& eager_kernel_execute_event_node : *eager_kernel_execute_event_node_list) { if (HasFunctionRun(eager_kernel_execute_event_node.get())) { auto new_virtual_event_node = absl::make_unique<EventNode>(*eager_kernel_execute_event_node); virtual_event_node = new_virtual_event_node.get(); // event_node_map_ keeps new_virtual_event_node alive. event_node_map_[HostEventType::kAsyncExecutorTraceContext].push_back( std::move(new_virtual_event_node)); } if (virtual_event_node) { virtual_event_node->AddChild(eager_kernel_execute_event_node.get()); } } } EventForest::EventForest( const std::vector<InterThreadConnectInfo>& connect_info_list, const std::vector<int64>& root_event_types, const std::function<XPlaneVisitor(const XPlane*)> visitor_factory, XSpace* space) { ContextGroupMap context_groups; visitors_.reserve(space->planes_size()); for (auto& plane : *space->mutable_planes()) { CreateStatMetadata(&plane); visitors_.push_back(visitor_factory(&plane)); ConnectIntraThread(visitors_.back(), &plane, &context_groups); } ConnectInterThread(connect_info_list); ConnectContextGroups(context_groups); ProcessTensorFlowLoop(); if (NeedsVirtualEventsForAsyncExecutor(root_event_types)) { CreateVirtualEventsForAsyncExecutor(); } CreateEventGroup(root_event_types); MarkEagerlyExecutedGpuKernels(); MarkEagerlyExecutedCpuTfOps(); } std::vector<InterThreadConnectInfo> CreateInterThreadConnectInfoList() { std::vector<InterThreadConnectInfo> connect_info_list = { {HostEventType::kFunctionRun, HostEventType::kExecutorStateProcess, {StatType::kStepId}}, {HostEventType::kFunctionRun, HostEventType::kExecutorDoneCallback, {StatType::kStepId}}, {HostEventType::kSessionRun, HostEventType::kExecutorStateProcess, {StatType::kStepId}}, {HostEventType::kSessionRun, HostEventType::kExecutorDoneCallback, {StatType::kStepId}}, {HostEventType::kRunGraph, HostEventType::kExecutorStateProcess, {StatType::kStepId}}, {HostEventType::kRunGraph, HostEventType::kExecutorDoneCallback, {StatType::kStepId}}, {HostEventType::kRunGraph, HostEventType::kRunGraphDone, {StatType::kStepId}}, {HostEventType::kExecutorStateProcess, HostEventType::kIteratorGetNextOp, {StatType::kStepId, StatType::kIterNum}}, {HostEventType::kExecutorStateProcess, HostEventType::kIteratorGetNextAsOptionalOp, {StatType::kStepId, StatType::kIterNum}}, {HostEventType::kKernelLaunch, HostEventType::kKernelExecute, {StatType::kCorrelationId}}, {HostEventType::kLocalExecutableExecuteOnLocalDevice, HostEventType::kLocalExecutableExecute, {StatType::kRunId}}}; for (int64 event_type : kFunctionalOpEventTypes) { connect_info_list.push_back({event_type, HostEventType::kExecutorStateProcess, {StatType::kFunctionStepId}, {StatType::kStepId}}); connect_info_list.push_back({event_type, HostEventType::kExecutorDoneCallback, {StatType::kFunctionStepId}, {StatType::kStepId}}); } return connect_info_list; } void GroupTfEvents(XSpace* space, EventGroupNameMap* event_group_name_map) { if (!space) return; std::vector<InterThreadConnectInfo> connect_info_list = CreateInterThreadConnectInfoList(); const std::vector<int64 /*EventType*/> root_event_types( {HostEventType::kTraceContext, HostEventType::kFunctionRun, HostEventType::kSessionRun, HostEventType::kRunGraph}); EventForest event_forest(connect_info_list, root_event_types, CreateTfXPlaneVisitor, space); if (event_group_name_map) { *event_group_name_map = event_forest.GetEventGroupNameMap(); } } } // namespace profiler } // namespace tensorflow
38.320946
80
0.692806
Squadrick
8b4f76a431758b3e139cbfceb5c46cb4f551b561
78,642
cpp
C++
editor/editor_file_system.cpp
Segs/Engine
754aabfc2708a46f764979a604871633152ce479
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
8
2019-09-03T19:58:19.000Z
2021-06-18T07:11:26.000Z
editor/editor_file_system.cpp
Segs/Engine
754aabfc2708a46f764979a604871633152ce479
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
24
2019-09-03T17:35:45.000Z
2020-10-27T14:36:02.000Z
editor/editor_file_system.cpp
nemerle/SegsEngine
b9dd0b5481b92d956befa72c746758d33a1a08c9
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
6
2019-09-27T15:44:35.000Z
2021-01-23T18:52:51.000Z
/*************************************************************************/ /* editor_file_system.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "editor_file_system.h" #include "core/io/resource_importer.h" #include "core/io/resource_loader.h" #include "core/io/resource_saver.h" #include "core/map.h" #include "core/string.h" #include "core/string_formatter.h" #include "core/string_utils.inl" #include "core/method_bind.h" #include "core/os/file_access.h" #include "core/os/mutex.h" #include "core/os/os.h" #include "core/project_settings.h" #include "core/resource/resource_manager.h" #include "core/variant_parser.h" #include "editor_node.h" #include "editor_resource_preview.h" #include "editor_settings.h" #include "EASTL/sort.h" IMPL_GDCLASS(EditorFileSystemDirectory) IMPL_GDCLASS(EditorFileSystem) EditorFileSystem *EditorFileSystem::singleton = nullptr; //the name is the version, to keep compatibility with different versions of Godot #define CACHE_FILE_NAME "filesystem_cache6" void EditorFileSystemDirectory::sort_files() { eastl::sort(files.begin(),files.end()); } int EditorFileSystemDirectory::find_file_index(StringView p_file) const { for (size_t i = 0; i < files.size(); i++) { if (files[i]->file == p_file) return i; } return -1; } int EditorFileSystemDirectory::find_dir_index(StringView p_dir) const { for (size_t i = 0; i < subdirs.size(); i++) { if (subdirs[i]->name == p_dir) return i; } return -1; } int EditorFileSystemDirectory::get_subdir_count() const { return subdirs.size(); } EditorFileSystemDirectory *EditorFileSystemDirectory::get_subdir(int p_idx) { ERR_FAIL_INDEX_V(p_idx, subdirs.size(), nullptr); return subdirs[p_idx]; } int EditorFileSystemDirectory::get_file_count() const { return files.size(); } String EditorFileSystemDirectory::get_file(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, files.size(), String()); return files[p_idx]->file; } String EditorFileSystemDirectory::get_path() const { String p; const EditorFileSystemDirectory *d = this; while (d->parent) { p = PathUtils::plus_file(d->name,p); d = d->parent; } return "res://" + p; } String EditorFileSystemDirectory::get_file_path(int p_idx) const { String file(get_file(p_idx)); const EditorFileSystemDirectory *d = this; while (d->parent) { file = PathUtils::plus_file(d->name,file); d = d->parent; } return "res://" + file; } String EditorFileSystemDirectory::get_named_file_path(StringView named_file) const { String file(named_file); const EditorFileSystemDirectory *d = this; while (d->parent) { file = PathUtils::plus_file(d->name,file); d = d->parent; } return "res://" + file; } const Vector<String> &EditorFileSystemDirectory::get_file_deps(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, files.size(), null_string_pvec); return files[p_idx]->deps; } bool EditorFileSystemDirectory::get_file_import_is_valid(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, files.size(), false); return files[p_idx]->import_valid; } StringName EditorFileSystemDirectory::get_file_script_class_name(int p_idx) const { return files[p_idx]->script_class_name; } StringName EditorFileSystemDirectory::get_file_script_class_extends(int p_idx) const { return files[p_idx]->script_class_extends; } const String & EditorFileSystemDirectory::get_file_script_class_icon_path(int p_idx) const { return files[p_idx]->script_class_icon_path; } StringName EditorFileSystemDirectory::get_file_type(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, files.size(), ""); return files[p_idx]->type; } const String &EditorFileSystemDirectory::get_name() { return name; } EditorFileSystemDirectory *EditorFileSystemDirectory::get_parent() { return parent; } void EditorFileSystemDirectory::_bind_methods() { MethodBinder::bind_method(D_METHOD("get_subdir_count"), &EditorFileSystemDirectory::get_subdir_count); MethodBinder::bind_method(D_METHOD("get_subdir", {"idx"}), &EditorFileSystemDirectory::get_subdir); MethodBinder::bind_method(D_METHOD("get_file_count"), &EditorFileSystemDirectory::get_file_count); MethodBinder::bind_method(D_METHOD("get_file", {"idx"}), &EditorFileSystemDirectory::get_file); MethodBinder::bind_method(D_METHOD("get_file_path", {"idx"}), &EditorFileSystemDirectory::get_file_path); MethodBinder::bind_method(D_METHOD("get_file_type", {"idx"}), &EditorFileSystemDirectory::get_file_type); MethodBinder::bind_method(D_METHOD("get_file_script_class_name", {"idx"}), &EditorFileSystemDirectory::get_file_script_class_name); MethodBinder::bind_method(D_METHOD("get_file_script_class_extends", {"idx"}), &EditorFileSystemDirectory::get_file_script_class_extends); MethodBinder::bind_method(D_METHOD("get_file_import_is_valid", {"idx"}), &EditorFileSystemDirectory::get_file_import_is_valid); MethodBinder::bind_method(D_METHOD("get_name"), &EditorFileSystemDirectory::get_name); MethodBinder::bind_method(D_METHOD("get_path"), &EditorFileSystemDirectory::get_path); MethodBinder::bind_method(D_METHOD("get_parent"), &EditorFileSystemDirectory::get_parent); MethodBinder::bind_method(D_METHOD("find_file_index", {"name"}), &EditorFileSystemDirectory::find_file_index); MethodBinder::bind_method(D_METHOD("find_dir_index", {"name"}), &EditorFileSystemDirectory::find_dir_index); } EditorFileSystemDirectory::EditorFileSystemDirectory() { modified_time = 0; parent = nullptr; verified = false; } EditorFileSystemDirectory::~EditorFileSystemDirectory() { for (FileInfo * f : files) { memdelete(f); } for (EditorFileSystemDirectory * d : subdirs) { memdelete(d); } } void EditorFileSystem::_scan_from_cache() { String fscache = PathUtils::plus_file(EditorSettings::get_singleton()->get_project_settings_dir(), CACHE_FILE_NAME); FileAccess *f = FileAccess::open(fscache, FileAccess::READ); if (!f) return; // read .fscache String cpath; bool first = true; while (!f->eof_reached()) { String l(StringUtils::strip_edges(f->get_line())); if (first) { if (first_scan) { // only use this on first scan, afterwards it gets ignored // this is so on first reimport we synchronize versions, then // we don't care until editor restart. This is for usability mainly so // your workflow is not killed after changing a setting by forceful reimporting // everything there is. filesystem_settings_version_for_import = StringUtils::strip_edges(l); if (filesystem_settings_version_for_import != ResourceFormatImporter::get_singleton()->get_import_settings_hash()) { revalidate_import_files = true; } } first = false; continue; } if (l.empty()) continue; if (StringUtils::begins_with(l, "::")) { Vector<StringView> split = StringUtils::split(l, "::"); ERR_CONTINUE(split.size() != 3); StringView name = split[1]; cpath = name; } else { Vector<StringView> split = StringUtils::split(l, "::"); ERR_CONTINUE(split.size() != 8); String name = PathUtils::plus_file(cpath, split[0]); FileCache fc; fc.type = split[1]; fc.modification_time = StringUtils::to_int64(split[2]); fc.import_modification_time = StringUtils::to_int64(split[3]); fc.import_valid = StringUtils::to_int64(split[4]) != 0; fc.import_group_file = StringUtils::strip_edges(split[5]); fc.script_class_name = StringName(StringUtils::get_slice(split[6], "<>", 0)); fc.script_class_extends = StringName(StringUtils::get_slice(split[6], "<>", 1)); fc.script_class_icon_path = StringUtils::get_slice(split[6], "<>", 2); StringView deps = StringUtils::strip_edges(split[7]); if (deps.length()) { Vector<StringView> dp = StringUtils::split(deps, "<>"); for (int i = 0; i < dp.size(); i++) { StringView path = dp[i]; fc.deps.emplace_back(path); } } file_cache[String(name)] = fc; } } f->close(); memdelete(f); } void EditorFileSystem::_scan_mark_updates() { String update_cache = PathUtils::plus_file(EditorSettings::get_singleton()->get_project_settings_dir(), "filesystem_update4"); if (!FileAccess::exists(update_cache)) return; { FileAccessRef f2 = FileAccess::open(update_cache, FileAccess::READ); String l(StringUtils::strip_edges(f2->get_line())); while (!l.empty()) { file_cache.erase(l); // erase cache for this, so it gets updated l = StringUtils::strip_edges(f2->get_line()); } } DirAccessRef d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); d->remove(update_cache); // bye bye update cache } void EditorFileSystem::_scan_filesystem() { ERR_FAIL_COND(!scanning || new_filesystem); sources_changed.clear(); file_cache.clear(); // read the disk cache _scan_from_cache(); _scan_mark_updates(); EditorProgressBG scan_progress("efs", "ScanFS", 1000); ScanProgress sp; sp.low = 0; sp.hi = 1; sp.progress = &scan_progress; new_filesystem = memnew(EditorFileSystemDirectory); new_filesystem->parent = nullptr; DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES); d->change_dir("res://"); _scan_new_dir(new_filesystem, d, sp); file_cache.clear(); // clear caches, no longer needed memdelete(d); if (!first_scan) { // on the first scan this is done from the main thread after re-importing _save_filesystem_cache(); } scanning = false; } void EditorFileSystem::_save_filesystem_cache() { group_file_cache.clear(); String fscache = PathUtils::plus_file(EditorSettings::get_singleton()->get_project_settings_dir(),CACHE_FILE_NAME); FileAccess *f = FileAccess::open(fscache, FileAccess::WRITE); ERR_FAIL_COND_MSG(!f, "Cannot create file '" + fscache + "'. Check user write permissions."); f->store_line(filesystem_settings_version_for_import); _save_filesystem_cache(filesystem, f); f->close(); memdelete(f); } void EditorFileSystem::_thread_func(void *_userdata) { EditorFileSystem *sd = (EditorFileSystem *)_userdata; sd->_scan_filesystem(); } bool EditorFileSystem::_test_for_reimport(StringView p_path, bool p_only_imported_files) { if (!reimport_on_missing_imported_files && p_only_imported_files) return false; if (!FileAccess::exists(String(p_path) + ".import")) { return true; } if (!ResourceFormatImporter::get_singleton()->are_import_settings_valid(p_path)) { //reimport settings are not valid, reimport return true; } Error err; FileAccess *f = FileAccess::open(String(p_path) + ".import", FileAccess::READ, &err); if (!f) { //no import file, do reimport return true; } VariantParserStream *stream = VariantParser::get_file_stream(f); Variant value; VariantParser::Tag next_tag; int lines = 0; String error_text; Vector<String> to_check; String source_file; String source_md5; Vector<String> dest_files; String dest_md5; while (true) { String assign = Variant().as<String>(); next_tag.fields.clear(); next_tag.name.clear(); err = VariantParser::parse_tag_assign_eof(stream, lines, error_text, next_tag, assign, value, nullptr, true); if (err == ERR_FILE_EOF) { break; } else if (err != OK) { ERR_PRINT("ResourceFormatImporter::load - '" + String(p_path) + ".import:" + ::to_string(lines) + "' error '" + error_text + "'."); VariantParser::release_stream(stream); memdelete(f); return false; //parse error, try reimport manually (Avoid reimport loop on broken file) } if (!assign.empty()) { if (StringUtils::begins_with(assign,"path")) { to_check.push_back(value.as<String>()); } else if (assign == "files") { Array fa = value.as<Array>(); for (int i = 0; i < fa.size(); i++) { to_check.push_back(fa[i].as<String>()); } } else if (!p_only_imported_files) { if (assign == "source_file") { source_file = value.as<String>(); } else if (assign == "dest_files") { dest_files = value.as<Vector<String>>(); } } } else if (next_tag.name != "remap" && next_tag.name != "deps") { break; } } VariantParser::release_stream(stream); memdelete(f); // Read the md5's from a separate file (so the import parameters aren't dependent on the file version String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(p_path); FileAccess *md5s = FileAccess::open(base_path + ".md5", FileAccess::READ, &err); if (!md5s) { // No md5's stored for this resource return true; } VariantParserStream *md5_stream = VariantParser::get_file_stream(md5s); while (true) { String assign = Variant().as<String>(); next_tag.fields.clear(); next_tag.name.clear(); err = VariantParser::parse_tag_assign_eof(md5_stream, lines, error_text, next_tag, assign, value, nullptr, true); if (err == ERR_FILE_EOF) { break; } else if (err != OK) { ERR_PRINT("ResourceFormatImporter::load - '" + String(p_path) + ".import.md5:" + ::to_string(lines) + "' error '" + error_text + "'."); VariantParser::release_stream(md5_stream); memdelete(md5s); return false; // parse error } if (!assign.empty() && !p_only_imported_files) { if (assign == "source_md5") { source_md5 = value.as<String>(); } else if (assign == "dest_md5") { dest_md5 = value.as<String>(); } } } VariantParser::release_stream(md5_stream); memdelete(md5s); //imported files are gone, reimport for (const String &E : to_check) { if (!FileAccess::exists(E)) { return true; } } //check source md5 matching if (!p_only_imported_files) { if (!source_file.empty() && StringView(source_file) != p_path) { return true; //file was moved, reimport } if (source_md5.empty()) { return true; //lacks md5, so just reimport } String md5(FileAccess::get_md5(p_path)); if (md5 != source_md5) { return true; } if (!dest_files.empty() && !dest_md5.empty()) { md5 = FileAccess::get_multiple_md5(dest_files); if (md5 != dest_md5) { return true; } } } return false; //nothing changed } bool EditorFileSystem::_update_scan_actions() { sources_changed.clear(); bool fs_changed = false; Vector<String> reimports; PoolVector<String> reloads; for (ItemAction &ia : scan_actions) { switch (ia.action) { case ItemAction::ACTION_NONE: { } break; case ItemAction::ACTION_DIR_ADD: { int idx = 0; for (int i = 0; i < ia.dir->subdirs.size(); i++) { if (ia.new_dir->name < ia.dir->subdirs[i]->name) break; idx++; } if (idx == ia.dir->subdirs.size()) { ia.dir->subdirs.push_back(ia.new_dir); } else { ia.dir->subdirs.insert(ia.dir->subdirs.begin()+idx, ia.new_dir); } fs_changed = true; } break; case ItemAction::ACTION_DIR_REMOVE: { ERR_CONTINUE(!ia.dir->parent); ia.dir->parent->subdirs.erase_first(ia.dir); memdelete(ia.dir); fs_changed = true; } break; case ItemAction::ACTION_FILE_ADD: { int idx = 0; for (int i = 0; i < ia.dir->files.size(); i++) { if (ia.new_file->file < ia.dir->files[i]->file) break; idx++; } if (idx == ia.dir->files.size()) { ia.dir->files.push_back(ia.new_file); } else { ia.dir->files.insert(ia.dir->files.begin()+idx, ia.new_file); } fs_changed = true; } break; case ItemAction::ACTION_FILE_REMOVE: { int idx = ia.dir->find_file_index(ia.file); ERR_CONTINUE(idx == -1); _delete_internal_files(ia.dir->files[idx]->file); memdelete(ia.dir->files[idx]); ia.dir->files.erase_at(idx); fs_changed = true; } break; case ItemAction::ACTION_FILE_TEST_REIMPORT: { int idx = ia.dir->find_file_index(ia.file); ERR_CONTINUE(idx == -1); String full_path = ia.dir->get_file_path(idx); if (_test_for_reimport(full_path, false)) { //must reimport reimports.push_back(full_path); reimports.push_back(_get_dependencies(full_path)); } else { //must not reimport, all was good //update modified times, to avoid reimport ia.dir->files[idx]->modified_time = FileAccess::get_modified_time(full_path); ia.dir->files[idx]->import_modified_time = FileAccess::get_modified_time(full_path + ".import"); } fs_changed = true; } break; case ItemAction::ACTION_FILE_RELOAD: { int idx = ia.dir->find_file_index(ia.file); ERR_CONTINUE(idx == -1); String full_path = ia.dir->get_file_path(idx); reloads.push_back(full_path); } break; } } if (!reimports.empty()) { reimport_files(reimports); } if (first_scan) { //only on first scan this is valid and updated, then settings changed. revalidate_import_files = false; filesystem_settings_version_for_import = ResourceFormatImporter::get_singleton()->get_import_settings_hash(); _save_filesystem_cache(); } if (!reloads.empty()) { emit_signal("resources_reload", reloads); } scan_actions.clear(); return fs_changed; } void EditorFileSystem::scan() { if (false /*&& bool(Globals::get_singleton()->get("debug/disable_scan"))*/) return; if (scanning || scanning_changes || thread.is_started()) return; _update_extensions(); abort_scan = false; if (!use_threads) { scanning = true; scan_total = 0; _scan_filesystem(); memdelete(filesystem); //file_type_cache.clear(); filesystem = new_filesystem; new_filesystem = nullptr; _update_scan_actions(); scanning = false; emit_signal("filesystem_changed"); emit_signal("sources_changed", !sources_changed.empty()); _queue_update_script_classes(); first_scan = false; } else { ERR_FAIL_COND(thread.is_started()); set_process(true); Thread::Settings s; scanning = true; scan_total = 0; s.priority = Thread::PRIORITY_LOW; thread.start(_thread_func, this, s); //tree->hide(); //progress->show(); } } void EditorFileSystem::ScanProgress::update(int p_current, int p_total) const { float ratio = low + (hi - low) / p_total * p_current; progress->step(ratio * 1000); EditorFileSystem::singleton->scan_total = ratio; } EditorFileSystem::ScanProgress EditorFileSystem::ScanProgress::get_sub(int p_current, int p_total) const { ScanProgress sp = *this; float slice = (sp.hi - sp.low) / p_total; sp.low += slice * p_current; sp.hi = slice; return sp; } void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir, DirAccess *da, const ScanProgress &p_progress) { Vector<String> dirs; Vector<String> files; String cd = da->get_current_dir(); p_dir->modified_time = FileAccess::get_modified_time(cd); da->list_dir_begin(); while (true) { String f = da->get_next(); if (f.empty()) break; if (da->current_is_hidden()) continue; if (da->current_is_dir()) { if (StringUtils::begins_with(f,".")) // Ignore special and . / .. continue; if (FileAccess::exists(PathUtils::plus_file(PathUtils::plus_file(cd,f),"project.godot"))) // skip if another project inside this continue; if (FileAccess::exists(PathUtils::plus_file(PathUtils::plus_file(cd,f),".gdignore"))) // skip if another project inside this continue; dirs.push_back(f); } else { files.push_back(f); } } da->list_dir_end(); eastl::sort(dirs.begin(),dirs.end(),NaturalNoCaseComparator()); eastl::sort(files.begin(),files.end(),NaturalNoCaseComparator()); int total = dirs.size() + files.size(); int idx = -1; for (const String &entry : dirs) { idx++; if (da->change_dir(entry) == OK) { String d = da->get_current_dir(); if (d == cd || !StringUtils::begins_with(d,cd)) { da->change_dir(cd); //avoid recursion } else { EditorFileSystemDirectory *efd = memnew(EditorFileSystemDirectory); efd->parent = p_dir; efd->name = entry; _scan_new_dir(efd, da, p_progress.get_sub(idx, total)); int idx2 = 0; for (int j = 0; j < p_dir->subdirs.size(); j++) { if (efd->name < p_dir->subdirs[j]->name) break; idx2++; } if (idx2 == p_dir->subdirs.size()) { p_dir->subdirs.push_back(efd); } else { p_dir->subdirs.insert(p_dir->subdirs.begin()+idx2, efd); } da->change_dir(".."); } } else { ERR_PRINT("Cannot go into subdir: " + entry); } p_progress.update(idx, total); } ResourceFormatImporter *rfi = ResourceFormatImporter::get_singleton(); for (size_t i=0,fin=files.size(); i<fin; ++i, ++idx) { const String &fname(files[i]); String ext = StringUtils::to_lower(PathUtils::get_extension(fname)); if (!valid_extensions.contains(ext)) { continue; //invalid } EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo); fi->file = fname; String path = PathUtils::plus_file(cd,fi->file); auto fc_iter = file_cache.find(path); FileCache *fc = file_cache.end()==fc_iter ? nullptr : &fc_iter->second; uint64_t mt = FileAccess::get_modified_time(path); if (import_extensions.contains(ext) && ResourceFormatImporter::get_singleton()->any_can_import(path)) { //is imported uint64_t import_mt = 0; if (FileAccess::exists(path + ".import")) { import_mt = FileAccess::get_modified_time(path + ".import"); } if (fc && fc->modification_time == mt && fc->import_modification_time == import_mt && !_test_for_reimport(path, true)) { fi->type = StringName(fc->type); fi->deps = fc->deps; fi->modified_time = fc->modification_time; fi->import_modified_time = fc->import_modification_time; fi->import_valid = fc->import_valid; fi->script_class_name = fc->script_class_name; fi->import_group_file = fc->import_group_file; fi->script_class_extends = fc->script_class_extends; fi->script_class_icon_path = fc->script_class_icon_path; if (revalidate_import_files && !rfi->are_import_settings_valid(path)) { ItemAction ia; ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT; ia.dir = p_dir; ia.file = fname; scan_actions.push_back(ia); } if (fc->type.empty()) { fi->type = StringName(gResourceManager().get_resource_type(path)); fi->import_group_file = gResourceManager().get_import_group_file(path); //there is also the chance that file type changed due to reimport, must probably check this somehow here //(or kind of note it for next time in another file?) //note: I think this should not happen any longer.. } } else { fi->type = StringName(rfi->get_resource_type(path)); fi->import_group_file = rfi->get_import_group_file(path); fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends, &fi->script_class_icon_path); fi->modified_time = 0; fi->import_modified_time = 0; fi->import_valid = gResourceManager().is_import_valid(path); ItemAction ia; ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT; ia.dir = p_dir; ia.file = fname; scan_actions.push_back(ia); } } else { if (fc && fc->modification_time == mt) { //not imported, so just update type if changed fi->type = StringName(fc->type); fi->modified_time = fc->modification_time; fi->deps = fc->deps; fi->import_modified_time = 0; fi->import_valid = true; fi->script_class_name = fc->script_class_name; fi->script_class_extends = fc->script_class_extends; fi->script_class_icon_path = fc->script_class_icon_path; } else { //new or modified time fi->type = StringName(gResourceManager().get_resource_type(path)); fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends, &fi->script_class_icon_path); fi->deps = _get_dependencies(path); fi->modified_time = mt; fi->import_modified_time = 0; fi->import_valid = true; } } p_dir->files.push_back(fi); p_progress.update(idx, total); } } void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir, const ScanProgress &p_progress) { uint64_t current_mtime = FileAccess::get_modified_time(p_dir->get_path()); bool updated_dir = false; String cd = p_dir->get_path(); if (current_mtime != p_dir->modified_time || using_fat32_or_exfat) { updated_dir = true; p_dir->modified_time = current_mtime; //ooooops, dir changed, see what's going on //first mark everything as verified for (auto * fi : p_dir->files) { fi->verified = false; } for (auto * sd : p_dir->subdirs) { sd->verified = false; } //then scan files and directories and check what's different DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); da->change_dir(cd); da->list_dir_begin(); while (true) { String f = da->get_next(); if (f.empty()) break; if (da->current_is_hidden()) continue; if (da->current_is_dir()) { if (StringUtils::begins_with(f,".")) // Ignore special and . / .. continue; int idx = p_dir->find_dir_index(f); if (idx == -1) { if (FileAccess::exists(PathUtils::plus_file(PathUtils::plus_file(cd,f),"project.godot"))) // skip if another project inside this continue; if (FileAccess::exists(PathUtils::plus_file(PathUtils::plus_file(cd,f),".gdignore"))) // skip if another project inside this continue; EditorFileSystemDirectory *efd = memnew(EditorFileSystemDirectory); efd->parent = p_dir; efd->name = f; DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES); d->change_dir(PathUtils::plus_file(cd,f)); _scan_new_dir(efd, d, p_progress.get_sub(1, 1)); memdelete(d); ItemAction ia; ia.action = ItemAction::ACTION_DIR_ADD; ia.dir = p_dir; ia.file = f; ia.new_dir = efd; scan_actions.push_back(ia); } else { p_dir->subdirs[idx]->verified = true; } } else { String ext = StringUtils::to_lower(PathUtils::get_extension(f)); if (!valid_extensions.contains(ext)) continue; //invalid int idx = p_dir->find_file_index(f); if (idx == -1) { //never seen this file, add actition to add it EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo); fi->file = f; String path = PathUtils::plus_file(cd,fi->file); bool importer_can_import = ResourceFormatImporter::get_singleton()->any_can_import(path); fi->modified_time = FileAccess::get_modified_time(path); fi->import_modified_time = 0; fi->type = StringName(gResourceManager().get_resource_type(path)); fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends, &fi->script_class_icon_path); fi->import_valid = gResourceManager().is_import_valid(path); fi->import_group_file = gResourceManager().get_import_group_file(path); { ItemAction ia; ia.action = ItemAction::ACTION_FILE_ADD; ia.dir = p_dir; ia.file = f; ia.new_file = fi; scan_actions.push_back(ia); } if (importer_can_import && import_extensions.contains(ext)) { //if it can be imported, and it was added, it needs to be reimported ItemAction ia; ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT; ia.dir = p_dir; ia.file = f; scan_actions.push_back(ia); } } else { p_dir->files[idx]->verified = true; } } } da->list_dir_end(); memdelete(da); } for (size_t i = 0; i < p_dir->files.size(); i++) { if (updated_dir && !p_dir->files[i]->verified) { //this file was removed, add action to remove it ItemAction ia; ia.action = ItemAction::ACTION_FILE_REMOVE; ia.dir = p_dir; ia.file = p_dir->files[i]->file; scan_actions.push_back(ia); continue; } String path = PathUtils::plus_file(cd,p_dir->files[i]->file); if (import_extensions.contains(StringUtils::to_lower(PathUtils::get_extension(p_dir->files[i]->file)))) { //check here if file must be imported or not bool importer_can_import = ResourceFormatImporter::get_singleton()->any_can_import(path); if(!importer_can_import) { continue; } uint64_t mt = FileAccess::get_modified_time(path); bool reimport = false; if (mt != p_dir->files[i]->modified_time) { reimport = true; //it was modified, must be reimported. } else if (!FileAccess::exists(path + ".import")) { reimport = true; //no .import file, obviously reimport } else { uint64_t import_mt = FileAccess::get_modified_time(path + ".import"); if (import_mt != p_dir->files[i]->import_modified_time) { reimport = true; } else if (_test_for_reimport(path, true)) { reimport = true; } } if (reimport) { ItemAction ia; ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT; ia.dir = p_dir; ia.file = p_dir->files[i]->file; scan_actions.push_back(ia); } } else if (ResourceCache::has(path)) { //test for potential reload uint64_t mt = FileAccess::get_modified_time(path); if (mt != p_dir->files[i]->modified_time) { p_dir->files[i]->modified_time = mt; //save new time, but test for reload ItemAction ia; ia.action = ItemAction::ACTION_FILE_RELOAD; ia.dir = p_dir; ia.file = p_dir->files[i]->file; scan_actions.push_back(ia); } } } for (int i = 0; i < p_dir->subdirs.size(); i++) { if (updated_dir && !p_dir->subdirs[i]->verified) { //this directory was removed, add action to remove it ItemAction ia; ia.action = ItemAction::ACTION_DIR_REMOVE; ia.dir = p_dir->subdirs[i]; scan_actions.push_back(ia); continue; } _scan_fs_changes(p_dir->get_subdir(i), p_progress); } } void EditorFileSystem::_delete_internal_files(StringView p_file) { if (FileAccess::exists(String(p_file) + ".import")) { Vector<String> paths; ResourceFormatImporter::get_singleton()->get_internal_resource_path_list(p_file, &paths); DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); for (const String &E : paths) { da->remove(E); } da->remove(String(p_file) + ".import"); memdelete(da); } } void EditorFileSystem::_thread_func_sources(void *_userdata) { EditorFileSystem *efs = (EditorFileSystem *)_userdata; if (efs->filesystem) { EditorProgressBG pr(StringName("sources"), TTR("ScanSources"), 1000); ScanProgress sp; sp.progress = &pr; sp.hi = 1; sp.low = 0; efs->_scan_fs_changes(efs->filesystem, sp); } efs->scanning_changes_done = true; } void EditorFileSystem::get_changed_sources(List<String> *r_changed) { *r_changed = sources_changed; } void EditorFileSystem::scan_changes() { if (first_scan || // Prevent a premature changes scan from inhibiting the first full scan scanning || scanning_changes || thread.is_started()) { scan_changes_pending = true; set_process(true); return; } _update_extensions(); sources_changed.clear(); scanning_changes = true; scanning_changes_done = false; abort_scan = false; if (!use_threads) { if (filesystem) { EditorProgressBG pr(("sources"), TTR("ScanSources"), 1000); ScanProgress sp; sp.progress = &pr; sp.hi = 1; sp.low = 0; scan_total = 0; _scan_fs_changes(filesystem, sp); if (_update_scan_actions()) emit_signal("filesystem_changed"); } scanning_changes = false; scanning_changes_done = true; emit_signal("sources_changed", !sources_changed.empty()); } else { ERR_FAIL_COND(thread_sources.is_started()); set_process(true); scan_total = 0; Thread::Settings s; s.priority = Thread::PRIORITY_LOW; thread_sources.start(_thread_func_sources, this, s); } } void EditorFileSystem::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: { //this should happen after every editor node entered the tree call_deferred([this]() {scan();}); //call_deferred("scan"); //this should happen after every editor node entered the tree } break; case NOTIFICATION_EXIT_TREE: { Thread &active_thread = thread.is_started() ? thread : thread_sources; if (use_threads && active_thread.is_started()) { //abort thread if in progress abort_scan = true; while (scanning) { OS::get_singleton()->delay_usec(1000); } active_thread.wait_to_finish(); WARN_PRINT("Scan thread aborted..."); set_process(false); } memdelete(filesystem); memdelete(new_filesystem); filesystem = nullptr; new_filesystem = nullptr; } break; case NOTIFICATION_PROCESS: { if (use_threads) { if (scanning_changes) { if (scanning_changes_done) { scanning_changes = false; set_process(false); thread_sources.wait_to_finish(); if (_update_scan_actions()) emit_signal("filesystem_changed"); emit_signal("sources_changed", !sources_changed.empty()); _queue_update_script_classes(); first_scan = false; } } else if (!scanning && thread.is_started()) { set_process(false); if (filesystem) memdelete(filesystem); filesystem = new_filesystem; new_filesystem = nullptr; thread.wait_to_finish(); _update_scan_actions(); emit_signal("filesystem_changed"); emit_signal("sources_changed", !sources_changed.empty()); _queue_update_script_classes(); first_scan = false; } if (!is_processing() && scan_changes_pending) { scan_changes_pending = false; scan_changes(); } } } break; } } bool EditorFileSystem::is_scanning() const { return scanning || scanning_changes; } float EditorFileSystem::get_scanning_progress() const { return scan_total; } EditorFileSystemDirectory *EditorFileSystem::get_filesystem() { return filesystem; } void EditorFileSystem::_save_filesystem_cache(EditorFileSystemDirectory *p_dir, FileAccess *p_file) { if (!p_dir) return; //none p_file->store_line(FormatVE("::%s::%luz",p_dir->get_path().c_str(),p_dir->modified_time)); for (size_t i = 0; i < p_dir->files.size(); i++) { if (!p_dir->files[i]->import_group_file.empty()) { group_file_cache.insert(p_dir->files[i]->import_group_file); } String s = p_dir->files[i]->file + "::" + p_dir->files[i]->type + "::" + ::to_string(p_dir->files[i]->modified_time) + "::" + ::to_string(p_dir->files[i]->import_modified_time) + "::" + ::to_string(p_dir->files[i]->import_valid) + "::" + p_dir->files[i]->import_group_file + "::" + p_dir->files[i]->script_class_name + "<>" + p_dir->files[i]->script_class_extends + "<>" + p_dir->files[i]->script_class_icon_path; s += "::"; for (int j = 0; j < p_dir->files[i]->deps.size(); j++) { if (j > 0) s += "<>"; s += p_dir->files[i]->deps[j]; } p_file->store_line(s); } for (size_t i = 0; i < p_dir->subdirs.size(); i++) { _save_filesystem_cache(p_dir->subdirs[i], p_file); } } bool EditorFileSystem::_find_file(StringView p_file, EditorFileSystemDirectory **r_d, int &r_file_pos) const { //todo make faster if (!filesystem || scanning) return false; String f = ProjectSettings::get_singleton()->localize_path(p_file); if (!StringUtils::begins_with(f,"res://")) return false; f = StringUtils::substr(f,6, f.length()); f = PathUtils::from_native_path(f); Vector<StringView> path = StringUtils::split(f,'/'); if (path.empty()) return false; String file(path[path.size() - 1]); path.resize(path.size() - 1); EditorFileSystemDirectory *fs = filesystem; for (int i = 0; i < path.size(); i++) { if (StringUtils::begins_with(path[i],".")) return false; int idx = -1; for (int j = 0; j < fs->get_subdir_count(); j++) { if (fs->get_subdir(j)->get_name() == path[i]) { idx = j; break; } } if (idx == -1) { //does not exist, create i guess? EditorFileSystemDirectory *efsd = memnew(EditorFileSystemDirectory); efsd->name = path[i]; efsd->parent = fs; int idx2 = 0; for (int j = 0; j < fs->get_subdir_count(); j++) { if (efsd->name < fs->get_subdir(j)->get_name()) break; idx2++; } if (idx2 == fs->get_subdir_count()) fs->subdirs.push_back(efsd); else fs->subdirs.insert(fs->subdirs.begin()+idx2, efsd); fs = efsd; } else { fs = fs->get_subdir(idx); } } int cpos = -1; for (int i = 0; i < fs->files.size(); i++) { if (fs->files[i]->file == file) { cpos = i; break; } } r_file_pos = cpos; *r_d = fs; return cpos != -1; } //TODO: SEGS: this could return either a naked pointer or a string view. String EditorFileSystem::get_file_type(StringView p_file) const { EditorFileSystemDirectory *fs = nullptr; int cpos = -1; if (!_find_file(p_file, &fs, cpos)) { return {}; } return fs->files[cpos]->type.asCString(); } EditorFileSystemDirectory *EditorFileSystem::find_file(StringView p_file, int *r_index) const { if (!filesystem || scanning) return nullptr; EditorFileSystemDirectory *fs = nullptr; int cpos = -1; if (!_find_file(p_file, &fs, cpos)) { return nullptr; } if (r_index) *r_index = cpos; return fs; } EditorFileSystemDirectory *EditorFileSystem::get_filesystem_path(StringView p_path) { if (!filesystem || scanning) return nullptr; String f = ProjectSettings::get_singleton()->localize_path(p_path); if (!StringUtils::begins_with(f,"res://")) return nullptr; f = StringUtils::substr(f,6, f.length()); f = PathUtils::from_native_path(f); if (f.empty()) return filesystem; if (StringUtils::ends_with(f,"/")) f = StringUtils::substr(f,0, f.length() - 1); Vector<StringView> path = StringUtils::split(f,'/'); if (path.empty()) return nullptr; EditorFileSystemDirectory *fs = filesystem; for (size_t i = 0; i < path.size(); i++) { int idx = -1; for (int j = 0; j < fs->get_subdir_count(); j++) { if (fs->get_subdir(j)->get_name() == path[i]) { idx = j; break; } } if (idx == -1) { return nullptr; } else { fs = fs->get_subdir(idx); } } return fs; } void EditorFileSystem::_save_late_updated_files() { //files that already existed, and were modified, need re-scanning for dependencies upon project restart. This is done via saving this special file String fscache = PathUtils::plus_file(EditorSettings::get_singleton()->get_project_settings_dir(),"filesystem_update4"); FileAccessRef f = FileAccess::open(fscache, FileAccess::WRITE); ERR_FAIL_COND_MSG(!f, "Cannot create file '" + fscache + "'. Check user write permissions."); for (const String &E : late_update_files) { f->store_line(E); } } Vector<String> EditorFileSystem::_get_dependencies(StringView p_path) { Vector<String> deps; gResourceManager().get_dependencies(p_path, deps); return deps; } StringName EditorFileSystem::_get_global_script_class( StringView p_type, StringView p_path, StringName *r_extends, String *r_icon_path) const { for (int i = 0; i < ScriptServer::get_language_count(); i++) { if (ScriptServer::get_language(i)->handles_global_class_type(p_type)) { StringName global_name; String extends; String icon_path; global_name = ScriptServer::get_language(i)->get_global_class_name(p_path, &extends, &icon_path); *r_extends = StringName(extends); *r_icon_path = icon_path; return global_name; } } *r_extends= StringName(); r_icon_path->clear(); return StringName(); } void EditorFileSystem::_scan_script_classes(EditorFileSystemDirectory *p_dir) { for (const EditorFileSystemDirectory::FileInfo * fi : p_dir->files) { if (fi->script_class_name.empty()) { continue; } StringName lang; for (int j = 0; j < ScriptServer::get_language_count(); j++) { if (ScriptServer::get_language(j)->handles_global_class_type(fi->type)) { lang = ScriptServer::get_language(j)->get_name(); } } ScriptServer::add_global_class(fi->script_class_name, fi->script_class_extends, lang, p_dir->get_named_file_path(fi->file)); EditorNode::get_editor_data().script_class_set_icon_path(fi->script_class_name, fi->script_class_icon_path); EditorNode::get_editor_data().script_class_set_name(fi->file, fi->script_class_name); } for (int i = 0; i < p_dir->get_subdir_count(); i++) { _scan_script_classes(p_dir->get_subdir(i)); } } void EditorFileSystem::update_script_classes() { if (!update_script_classes_queued) return; update_script_classes_queued = false; ScriptServer::global_classes_clear(); if (get_filesystem()) { _scan_script_classes(get_filesystem()); } ScriptServer::save_global_classes(); EditorNode::get_editor_data().script_class_save_icon_paths(); // Rescan custom loaders and savers. // Doing the following here because the `filesystem_changed` signal fires multiple times and isn't always followed by script classes update. // So I thought it's better to do this when script classes really get updated gResourceManager().remove_custom_loaders(); gResourceManager().add_custom_loaders(); gResourceManager().remove_custom_savers(); gResourceManager().add_custom_savers(); } void EditorFileSystem::_queue_update_script_classes() { if (update_script_classes_queued) { return; } update_script_classes_queued = true; call_deferred([this] {update_script_classes();}); } void EditorFileSystem::update_file(StringView p_file) { EditorFileSystemDirectory *fs = nullptr; int cpos = -1; if (!_find_file(p_file, &fs, cpos)) { if (!fs) return; } if (!FileAccess::exists(p_file)) { //was removed _delete_internal_files(p_file); if (cpos != -1) { // Might've never been part of the editor file system (*.* files deleted in Open dialog). memdelete(fs->files[cpos]); fs->files.erase_at(cpos); } call_deferred([this] { emit_signal("filesystem_changed"); }); //update later _queue_update_script_classes(); return; } String type = gResourceManager().get_resource_type(p_file); if (cpos == -1) { // The file did not exist, it was added. late_added_files.insert(p_file); // Remember that it was added. This mean it will be scanned and imported on editor restart. int idx = 0; String file_name(PathUtils::get_file(p_file)); for (const auto f : fs->files) { if (file_name < f->file) { break; } idx++; } EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo); fi->file = file_name; fi->import_modified_time = 0; fi->import_valid = gResourceManager().is_import_valid(p_file); if (idx == fs->files.size()) { fs->files.push_back(fi); } else { fs->files.insert(fs->files.begin()+idx, fi); } cpos = idx; } else { //the file exists and it was updated, and was not added in this step. //this means we must force upon next restart to scan it again, to get proper type and dependencies late_update_files.insert(p_file); _save_late_updated_files(); //files need to be updated in the re-scan } fs->files[cpos]->type = StringName(type); fs->files[cpos]->script_class_name = _get_global_script_class(type, p_file, &fs->files[cpos]->script_class_extends, &fs->files[cpos]->script_class_icon_path); fs->files[cpos]->import_group_file = gResourceManager().get_import_group_file(p_file); fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file); fs->files[cpos]->deps = _get_dependencies(p_file); fs->files[cpos]->import_valid = gResourceManager().is_import_valid(p_file); // Update preview EditorResourcePreview::get_singleton()->check_for_invalidation(p_file); call_deferred([this] { emit_signal("filesystem_changed"); }); //update later _queue_update_script_classes(); } Error EditorFileSystem::_reimport_group(StringView p_group_file, const Vector<String> &p_files) { String importer_name; Map<String, HashMap<StringName, Variant> > source_file_options; Map<String, String> base_paths; for (int i = 0; i < p_files.size(); i++) { Ref<ConfigFile> config(make_ref_counted<ConfigFile>()); Error err = config->load(p_files[i] + ".import"); ERR_CONTINUE(err != OK); ERR_CONTINUE(!config->has_section_key("remap", "importer")); String file_importer_name = config->get_value("remap", "importer").as<String>(); ERR_CONTINUE(file_importer_name.empty()); if (!importer_name.empty() && importer_name != file_importer_name) { print_line("one importer: " + importer_name + " the other: " + file_importer_name); EditorNode::get_singleton()->show_warning(FormatSN(TTR("There are multiple importers for different types pointing to file %.*s, import aborted").asCString(), p_group_file.length(),p_group_file.data())); ERR_FAIL_V(ERR_FILE_CORRUPT); } source_file_options[p_files[i]] = HashMap<StringName, Variant>(); importer_name = file_importer_name; ResourceImporterInterface *importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name); ERR_FAIL_COND_V(importer==nullptr, ERR_FILE_CORRUPT); Vector<ResourceImporter::ImportOption> options; importer->get_import_options(&options); //set default values for (const ResourceImporter::ImportOption &E : options) { source_file_options[p_files[i]][E.option.name] = E.default_value; } if (config->has_section("params")) { Vector<String> sk = config->get_section_keys("params"); for (const String &param : sk) { Variant value = config->get_value("params", param); //override with whathever is in file source_file_options[p_files[i]][StringName(param)] = value; } } base_paths[p_files[i]] = ResourceFormatImporter::get_singleton()->get_import_base_path(p_files[i]); } ERR_FAIL_COND_V(importer_name.empty(), ERR_UNCONFIGURED); ResourceImporterInterface *importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name); Error err = importer->import_group_file(p_group_file, source_file_options, base_paths); //all went well, overwrite config files with proper remaps and md5s for (eastl::pair<const String, HashMap<StringName, Variant> > &E : source_file_options) { const String &file = E.first; String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(file); FileAccessRef f = FileAccess::open(file + ".import", FileAccess::WRITE); ERR_FAIL_COND_V(!f, ERR_FILE_CANT_OPEN); //write manually, as order matters ([remap] has to go first for performance). f->store_line("[remap]"); f->store_line(""); f->store_line(String("importer=\"") + importer->get_importer_name() + "\""); if (!importer->get_resource_type().empty()) { f->store_line(String("type=\"") + importer->get_resource_type() + "\""); } Vector<String> dest_paths; if (err == OK) { String path = base_path + "." + importer->get_save_extension(); f->store_line("path=\"" + path + "\""); dest_paths.push_back(path); } f->store_line("group_file=" + Variant(p_group_file).get_construct_string()); if (err == OK) { f->store_line("valid=true"); } else { f->store_line("valid=false"); } f->store_line("[deps]\n"); f->store_line(""); f->store_line("source_file=" + Variant(file).get_construct_string()); if (!dest_paths.empty()) { Array dp; for (size_t i = 0; i < dest_paths.size(); i++) { dp.push_back(dest_paths[i]); } f->store_line("dest_files=" + Variant(dp).get_construct_string() + "\n"); } f->store_line("[params]"); f->store_line(""); //store options in provided order, to avoid file changing. Order is also important because first match is accepted first. Vector<ResourceImporter::ImportOption> options; importer->get_import_options(&options); //set default values for (const ResourceImporter::ImportOption &F : options) { StringName base(F.option.name); Variant v = F.default_value; if (source_file_options[file].contains(base)) { v = source_file_options[file][base]; } String value; VariantWriter::write_to_string(v, value); f->store_line(String(base) + "=" + value); } f->close(); // Store the md5's of the various files. These are stored separately so that the .import files can be version controlled. FileAccessRef md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE); ERR_FAIL_COND_V_MSG(!md5s, ERR_FILE_CANT_OPEN, "Cannot open MD5 file '" + base_path + ".md5'."); md5s->store_line("source_md5=\"" + FileAccess::get_md5(file) + "\""); if (!dest_paths.empty()) { md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n"); } md5s->close(); EditorFileSystemDirectory *fs = nullptr; int cpos = -1; bool found = _find_file(file, &fs, cpos); ERR_FAIL_COND_V_MSG(!found, ERR_UNCONFIGURED, "Can't find file '" + file + "'."); //update modified times, to avoid reimport fs->files[cpos]->modified_time = FileAccess::get_modified_time(file); fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(file + ".import"); fs->files[cpos]->deps = _get_dependencies(file); fs->files[cpos]->type = importer->get_resource_type(); fs->files[cpos]->import_valid = err == OK; //if file is currently up, maybe the source it was loaded from changed, so import math must be updated for it //to reload properly if (ResourceCache::has(file)) { Resource *r = ResourceCache::get(file); if (!r->get_import_path().empty()) { String dst_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(file); r->set_import_path(dst_path); r->set_import_last_modified_time(0); } } EditorResourcePreview::get_singleton()->check_for_invalidation(file); } return err; } Error EditorFileSystem::_reimport_file(const String &p_file, Vector<String> &r_missing_deps, bool final_try) { EditorFileSystemDirectory *fs = nullptr; int cpos = -1; bool found = _find_file(p_file, &fs, cpos); ERR_FAIL_COND_V_MSG(!found, ERR_FILE_CANT_OPEN, "Can't find file '" + p_file + "'."); //try to obtain existing params HashMap<StringName, Variant> params; String importer_name; if (FileAccess::exists(p_file + ".import")) { //use existing Ref<ConfigFile> cf(make_ref_counted<ConfigFile>()); Error err = cf->load(p_file + ".import"); if (err == OK) { if (cf->has_section("params")) { Vector<String> sk = cf->get_section_keys("params"); for (const String &E : sk) { params[StringName(E)] = cf->get_value("params", E); } } if (cf->has_section("remap")) { importer_name = cf->get_value("remap", "importer").as<String>(); } } } else { late_added_files.insert(p_file); //imported files do not call update_file(), but just in case.. } ResourceImporterInterface *importer=nullptr; bool load_default = false; //find the importer if (!importer_name.empty()) { importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name); } if (importer==nullptr) { //not found by name, find by extension importer = ResourceFormatImporter::get_singleton()->get_importer_by_extension(PathUtils::get_extension(p_file)); load_default = true; if (importer==nullptr) { ERR_FAIL_V_MSG(ERR_CANT_RESOLVE, "BUG: File queued for import, but can't be imported!"); } } //mix with default params, in case a parameter is missing Vector<ResourceImporter::ImportOption> opts; importer->get_import_options(&opts); for (const ResourceImporter::ImportOption &E : opts) { if (!params.contains(E.option.name)) { //this one is not present params[E.option.name] = E.default_value; } } if (load_default && ProjectSettings::get_singleton()->has_setting(StringName(String("importer_defaults/") + importer->get_importer_name()))) { //use defaults if exist Dictionary d = ProjectSettings::get_singleton()->get(StringName(String("importer_defaults/") + importer->get_importer_name())).as<Dictionary>(); Vector<Variant> v(d.get_key_list()); for (const Variant &E : v) { params[E.as<StringName>()] = d[E]; } } //finally, perform import!! String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(p_file); Vector<String> import_variants; Vector<String> gen_files; Variant metadata; Error err = importer->import(p_file, base_path, params, r_missing_deps,&import_variants, &gen_files, &metadata); if (err != OK) { ERR_PRINT("Error importing '" + p_file + "'."); if(err==ERR_FILE_MISSING_DEPENDENCIES && !final_try) { return ERR_FILE_MISSING_DEPENDENCIES; } } //as import is complete, save the .import file FileAccess *f = FileAccess::open(p_file + ".import", FileAccess::WRITE); ERR_FAIL_COND_V_MSG(!f,ERR_FILE_CANT_WRITE, "Cannot open file from path '" + p_file + ".import'."); //write manually, as order matters ([remap] has to go first for performance). f->store_line("[remap]"); f->store_line(""); f->store_line(String("importer=\"") + importer->get_importer_name() + "\""); if (!importer->get_resource_type().empty()) { f->store_line(String("type=\"") + importer->get_resource_type() + "\""); } Vector<String> dest_paths; if (err == OK) { if (importer->get_save_extension().empty()) { //no path } else if (!import_variants.empty()) { //import with variants for (const String &E : import_variants) { String path = StringUtils::c_escape(base_path) + "." + E + "." + importer->get_save_extension(); f->store_line("path." + E + "=\"" + path + "\""); dest_paths.push_back(path); } } else { String path = base_path + "." + importer->get_save_extension(); f->store_line("path=\"" + path + "\""); dest_paths.push_back(path); } } else { f->store_line("valid=false"); } if (metadata != Variant()) { f->store_line("metadata=" + metadata.get_construct_string()); } f->store_line(""); f->store_line("[deps]\n"); if (!gen_files.empty()) { Array genf; for (const String &E : gen_files) { genf.push_back(E); dest_paths.push_back(E); } String value; VariantWriter::write_to_string(genf, value); f->store_line("files=" + value); f->store_line(""); } f->store_line("source_file=" + Variant(p_file).get_construct_string()); if (!dest_paths.empty()) { Array dp; for (size_t i = 0; i < dest_paths.size(); i++) { dp.push_back(dest_paths[i]); } f->store_line("dest_files=" + Variant(dp).get_construct_string() + "\n"); } f->store_line("[params]"); f->store_line(""); //store options in provided order, to avoid file changing. Order is also important because first match is accepted first. for (const ResourceImporter::ImportOption &E : opts) { StringName base(E.option.name); String value; VariantWriter::write_to_string(params[base], value); f->store_line(String(base) + "=" + value); } f->close(); memdelete(f); // Store the md5's of the various files. These are stored separately so that the .import files can be version controlled. FileAccess *md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE); ERR_FAIL_COND_V(!md5s,ERR_FILE_CANT_WRITE); md5s->store_line("source_md5=\"" + FileAccess::get_md5(p_file) + "\""); if (!dest_paths.empty()) { md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n"); } md5s->close(); memdelete(md5s); //update modified times, to avoid reimport fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file); fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(p_file + ".import"); fs->files[cpos]->deps = _get_dependencies(p_file); fs->files[cpos]->type = importer->get_resource_type(); fs->files[cpos]->import_valid = gResourceManager().is_import_valid(p_file); //if file is currently up, maybe the source it was loaded from changed, so import math must be updated for it //to reload properly if (ResourceCache::has(p_file)) { Resource *r = ResourceCache::get(p_file); if (!r->get_import_path().empty()) { String dst_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_file); r->set_import_path(dst_path); r->set_import_last_modified_time(0); } } EditorResourcePreview::get_singleton()->check_for_invalidation(p_file); return OK; } void EditorFileSystem::_find_group_files(EditorFileSystemDirectory *efd, Map<String, Vector<String> > &group_files, Set<String> &groups_to_reimport) { for (EditorFileSystemDirectory::FileInfo * fi : efd->files) { if (groups_to_reimport.contains(fi->import_group_file)) { group_files[fi->import_group_file].push_back(efd->get_named_file_path(fi->file)); } } for (int i = 0; i < efd->get_subdir_count(); i++) { _find_group_files(efd->get_subdir(i), group_files, groups_to_reimport); } } // Find the order the give set of files need to be imported in, taking into account dependencies between resources. void EditorFileSystem::ordered_reimport(EditorProgress &pr, Vector<ImportFile> &files) { eastl::sort(files.begin(),files.end()); //TODO: use slab allocator here, and just 'forget' all deallocations. HashMap<String, HashSet<String>> missing_deps; HashSet<String> correct_imports; correct_imports.reserve(files.size()); int idx=0; // At the beginning we don't know cross-resource dependencies, so we go linearly for (const auto & fi : files) { pr.step(StringName(PathUtils::get_file(fi.path)), idx); Vector<String> deps; auto err = _reimport_file(fi.path, deps); if (err == OK) { idx++; // count success as progress correct_imports.insert(fi.path); } else if(ERR_FILE_MISSING_DEPENDENCIES==err) { // This path is missing those dependencies: missing_deps[fi.path].insert(eastl::make_move_iterator(deps.begin()), eastl::make_move_iterator(deps.end())); } } if(missing_deps.empty()) return; OS::get_singleton()->print("Missing deps:"); Vector<String> ordered_imports; //NOTE: this should probably use graph theoretic algorithms -> detect cycles + topological sort // 1. Remove dependent files that were loaded after files that needed them. for(auto iter=missing_deps.begin(); iter!= missing_deps.end(); ) { for(auto iter2=iter->second.begin(); iter2!= iter->second.end();) { OS::get_singleton()->print(FormatVE(" %s\n", iter2->c_str())); if(correct_imports.contains(*iter2)) { // got it ! iter2 = iter->second.erase(iter2); } else ++iter2; } if(iter->second.empty()) { ordered_imports.push_back(iter->first); iter = missing_deps.erase(iter); } else ++iter; } // Loop until we have all ordered, or can't add new part to ordered_imports size_t start_of_chunk=0; size_t end_of_chunk= ordered_imports.size(); while(!missing_deps.empty()) { for (auto iter = missing_deps.begin(); iter != missing_deps.end(); ) { Span<const String> last_chunk(ordered_imports.data() + start_of_chunk, end_of_chunk - start_of_chunk); // Remove what's already on the list from deps. for (auto iter2 = iter->second.begin(); iter2 != iter->second.end();) { if (last_chunk.end()!=eastl::find(last_chunk.begin(), last_chunk.end(),*iter2)) { // got it ! iter2 = iter->second.erase(iter2); } else ++iter2; } if (iter->second.empty()) { ordered_imports.push_back(iter->first); iter = missing_deps.erase(iter); } else ++iter; } if(end_of_chunk==ordered_imports.size()) break; // can't reduce anymore ? start_of_chunk = end_of_chunk; end_of_chunk = ordered_imports.size(); } for (const auto & fi : ordered_imports) { pr.step(StringName(PathUtils::get_file(fi)), idx); Vector<String> deps; auto err = _reimport_file(fi, deps,true); // marked as final try, since we want those files to be marked as failed in this case. if (err == OK) { idx++; // count success as progress } } // mark the last missing deps by calling _reimport_file with final_try set for(const auto &f : missing_deps) { Vector<String> deps; _reimport_file(f.first,deps,true); } } void EditorFileSystem::reimport_files(const Vector<String> &p_files) { { //check that .import folder exists DirAccess *da = DirAccess::open("res://"); if (da->change_dir(".import") != OK) { Error err = da->make_dir(".import"); if (err) { memdelete(da); ERR_FAIL_MSG("Failed to create 'res://.import' folder."); } } memdelete(da); } importing = true; EditorProgress pr(("reimport"), TTR("(Re)Importing Assets"), p_files.size()); Vector<ImportFile> files; Set<String> groups_to_reimport; for (const auto &p_file : p_files) { String group_file = ResourceFormatImporter::get_singleton()->get_import_group_file(p_file); if (group_file_cache.contains(p_file)) { //maybe the file itself is a group! groups_to_reimport.insert(p_file); //groups do not belong to grups group_file.clear(); } else if (!group_file.empty()) { //it's a group file, add group to import and skip this file groups_to_reimport.insert(group_file); } else { //it's a regular file ImportFile ifile; ifile.path = p_file; ifile.order = ResourceFormatImporter::get_singleton()->get_import_order(p_file); files.push_back(ifile); } //group may have changed, so also update group reference EditorFileSystemDirectory *fs = nullptr; int cpos = -1; if (_find_file(p_file, &fs, cpos)) { fs->files[cpos]->import_group_file = group_file; } } ordered_reimport(pr, files); //reimport groups if (!groups_to_reimport.empty()) { Map<String, Vector<String> > group_files; _find_group_files(filesystem, group_files, groups_to_reimport); for (eastl::pair<const String,Vector<String> > &E : group_files) { Error err = _reimport_group(E.first, E.second); if (err == OK) { Vector<String> missing_deps; _reimport_file(E.first, missing_deps,true); } } } _save_filesystem_cache(); importing = false; if (!is_scanning()) { emit_signal("filesystem_changed"); } emit_signal("resources_reimported", Variant::from(p_files)); } Error EditorFileSystem::_resource_import(StringView p_path) { Vector<String> files { String(p_path) }; singleton->update_file(p_path); singleton->reimport_files(files); return OK; } bool EditorFileSystem::is_group_file(StringView p_path) const { return group_file_cache.contains_as(p_path); } void EditorFileSystem::_move_group_files(EditorFileSystemDirectory *efd, StringView p_group_file, StringView p_new_location) { for (EditorFileSystemDirectory::FileInfo * fi : efd->files) { if (fi->import_group_file == p_group_file) { fi->import_group_file = p_new_location; Ref<ConfigFile> config(make_ref_counted<ConfigFile>()); String path = efd->get_named_file_path(fi->file) + ".import"; Error err = config->load(path); if (err != OK) { continue; } if (config->has_section_key("remap", "group_file")) { config->set_value("remap", "group_file", p_new_location); } Vector<String> sk = config->get_section_keys("params"); for (const String & param : sk) { //not very clean, but should work String value = config->get_value("params", param).as<String>(); if (value == p_group_file) { config->set_value("params", param, p_new_location); } } config->save(path); } } for (int i = 0; i < efd->get_subdir_count(); i++) { _move_group_files(efd->get_subdir(i), p_group_file, p_new_location); } } void EditorFileSystem::move_group_file(StringView p_path, StringView p_new_path) { if (get_filesystem()) { _move_group_files(get_filesystem(), p_path, p_new_path); auto iter=group_file_cache.find_as(p_path); if (iter!=group_file_cache.end()) { group_file_cache.erase(iter); group_file_cache.insert(p_new_path); } } } void EditorFileSystem::_bind_methods() { MethodBinder::bind_method(D_METHOD("get_filesystem"), &EditorFileSystem::get_filesystem); MethodBinder::bind_method(D_METHOD("is_scanning"), &EditorFileSystem::is_scanning); MethodBinder::bind_method(D_METHOD("get_scanning_progress"), &EditorFileSystem::get_scanning_progress); MethodBinder::bind_method(D_METHOD("scan"), &EditorFileSystem::scan); MethodBinder::bind_method(D_METHOD("scan_changes"), &EditorFileSystem::scan_changes); MethodBinder::bind_method(D_METHOD("update_file", {"path"}), &EditorFileSystem::update_file); MethodBinder::bind_method(D_METHOD("get_filesystem_path", {"path"}), &EditorFileSystem::get_filesystem_path); MethodBinder::bind_method(D_METHOD("get_file_type", {"path"}), &EditorFileSystem::get_file_type); MethodBinder::bind_method(D_METHOD("update_script_classes"), &EditorFileSystem::update_script_classes); ADD_SIGNAL(MethodInfo("filesystem_changed")); ADD_SIGNAL(MethodInfo("sources_changed", PropertyInfo(VariantType::BOOL, "exist"))); ADD_SIGNAL(MethodInfo("resources_reimported", PropertyInfo(VariantType::POOL_STRING_ARRAY, "resources"))); ADD_SIGNAL(MethodInfo("resources_reload", PropertyInfo(VariantType::POOL_STRING_ARRAY, "resources"))); } void EditorFileSystem::_update_extensions() { valid_extensions.clear(); import_extensions.clear(); Vector<String> tmp_extensions; gResourceManager().get_recognized_extensions_for_type("", tmp_extensions); for (String &E : tmp_extensions) { valid_extensions.emplace(eastl::move(E)); } tmp_extensions.clear(); ResourceFormatImporter::get_singleton()->get_recognized_extensions(tmp_extensions); for (String &E : tmp_extensions) { import_extensions.emplace(eastl::move(E)); } } EditorFileSystem::EditorFileSystem() { __thread__safe__.reset(new Mutex); g_import_func = _resource_import; reimport_on_missing_imported_files = T_GLOBAL_DEF("editor/reimport_missing_imported_files", true); singleton = this; filesystem = memnew(EditorFileSystemDirectory); //like, empty filesystem->parent = nullptr; scanning = false; importing = false; use_threads = true; new_filesystem = nullptr; abort_scan = false; scanning_changes = false; scanning_changes_done = false; DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->change_dir("res://.import") != OK) { da->make_dir("res://.import"); } // This should probably also work on Unix and use the string it returns for FAT32 or exFAT String fstype = da->get_filesystem_type(); using_fat32_or_exfat = fstype == "FAT32" || fstype == "exFAT"; memdelete(da); scan_total = 0; update_script_classes_queued = false; first_scan = true; scan_changes_pending = false; revalidate_import_files = false; } EditorFileSystem::~EditorFileSystem() { }
34.859043
214
0.592152
Segs
332f04b476425becdfd4d2dd9605d44ef22c47e5
3,274
cpp
C++
src/Cpu_stub.cpp
oujx28/Ulordrig
cab7fa4e01c1cb93211a81a6fad20c604e960328
[ "MIT" ]
44
2018-04-04T09:48:50.000Z
2021-01-15T10:45:22.000Z
src/Cpu_stub.cpp
oujx28/Ulordrig
cab7fa4e01c1cb93211a81a6fad20c604e960328
[ "MIT" ]
28
2018-05-04T13:44:52.000Z
2020-03-27T03:38:03.000Z
src/Cpu_stub.cpp
oujx28/Ulordrig
cab7fa4e01c1cb93211a81a6fad20c604e960328
[ "MIT" ]
9
2018-04-19T03:47:46.000Z
2019-04-14T11:02:51.000Z
/* UlordRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2016-2017 XMRig <support@xmrig.com> * Copyright 2018 UlordRig <https://github.com/UlordChain/ulordrig> * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifdef _MSC_VER # include <intrin.h> #else # include <cpuid.h> #endif #ifndef bit_AES # define bit_AES (1 << 25) #endif #ifndef bit_BMI2 # define bit_BMI2 (1 << 8) #endif #include <string.h> #include "Cpu.h" #define VENDOR_ID (0) #define PROCESSOR_INFO (1) #define CACHE_TLB_DESCRIPTOR (2) #define EXTENDED_FEATURES (7) #define PROCESSOR_BRAND_STRING_1 (0x80000002) #define PROCESSOR_BRAND_STRING_2 (0x80000003) #define PROCESSOR_BRAND_STRING_3 (0x80000004) #define EAX_Reg (0) #define EBX_Reg (1) #define ECX_Reg (2) #define EDX_Reg (3) #ifdef _MSC_VER static inline void cpuid(int level, int output[4]) { __cpuid(output, level); } #else static inline void cpuid(int level, int output[4]) { int a, b, c, d; __cpuid_count(level, 0, a, b, c, d); output[0] = a; output[1] = b; output[2] = c; output[3] = d; } #endif static inline void cpu_brand_string(char* s) { int cpu_info[4] = { 0 }; cpuid(VENDOR_ID, cpu_info); if (cpu_info[EAX_Reg] >= 4) { for (int i = 0; i < 4; i++) { cpuid(0x80000002 + i, cpu_info); memcpy(s, cpu_info, sizeof(cpu_info)); s += 16; } } } static inline bool has_aes_ni() { int cpu_info[4] = { 0 }; cpuid(PROCESSOR_INFO, cpu_info); return (cpu_info[ECX_Reg] & bit_AES) != 0; } static inline bool has_bmi2() { int cpu_info[4] = { 0 }; cpuid(EXTENDED_FEATURES, cpu_info); return (cpu_info[EBX_Reg] & bit_BMI2) != 0; } char Cpu::m_brand[64] = { 0 }; int Cpu::m_flags = 0; int Cpu::m_l2_cache = 0; int Cpu::m_l3_cache = 0; int Cpu::m_sockets = 1; int Cpu::m_totalCores = 0; int Cpu::m_totalThreads = 0; int Cpu::optimalThreadsCount(int algo, bool doubleHash, int maxCpuUsage) { int count = m_totalThreads / 2; return count < 1 ? 1 : count; } void Cpu::initCommon() { cpu_brand_string(m_brand); # if defined(__x86_64__) || defined(_M_AMD64) m_flags |= X86_64; # endif if (has_aes_ni()) { m_flags |= AES; } if (has_bmi2()) { m_flags |= BMI2; } }
23.385714
75
0.638974
oujx28
3330fde17bf0ebe928b49a1ec0be3c761b017232
45,707
cc
C++
test/extensions/clusters/redis/redis_cluster_test.cc
mengmichael1/envoy
cafccb2f92f90952619465c4f3a4f69ce43e2d55
[ "Apache-2.0" ]
1
2021-01-05T05:56:04.000Z
2021-01-05T05:56:04.000Z
test/extensions/clusters/redis/redis_cluster_test.cc
mengmichael1/envoy
cafccb2f92f90952619465c4f3a4f69ce43e2d55
[ "Apache-2.0" ]
1
2021-01-26T05:15:20.000Z
2021-01-26T05:15:20.000Z
test/extensions/clusters/redis/redis_cluster_test.cc
mengmichael1/envoy
cafccb2f92f90952619465c4f3a4f69ce43e2d55
[ "Apache-2.0" ]
null
null
null
#include <bitset> #include <chrono> #include <memory> #include <vector> #include "envoy/config/cluster/redis/redis_cluster.pb.h" #include "envoy/config/cluster/redis/redis_cluster.pb.validate.h" #include "envoy/config/cluster/v3/cluster.pb.h" #include "envoy/extensions/filters/network/redis_proxy/v3/redis_proxy.pb.h" #include "envoy/extensions/filters/network/redis_proxy/v3/redis_proxy.pb.validate.h" #include "envoy/stats/scope.h" #include "common/network/utility.h" #include "common/singleton/manager_impl.h" #include "common/upstream/logical_dns_cluster.h" #include "source/extensions/clusters/redis/redis_cluster.h" #include "test/common/upstream/utility.h" #include "test/extensions/clusters/redis/mocks.h" #include "test/extensions/filters/network/common/redis/mocks.h" #include "test/mocks/common.h" #include "test/mocks/local_info/mocks.h" #include "test/mocks/protobuf/mocks.h" #include "test/mocks/server/admin.h" #include "test/mocks/server/instance.h" #include "test/mocks/ssl/mocks.h" #include "test/mocks/upstream/cluster_manager.h" #include "test/mocks/upstream/cluster_priority_set.h" #include "test/mocks/upstream/health_check_event_logger.h" #include "test/mocks/upstream/health_checker.h" using testing::_; using testing::ContainerEq; using testing::Eq; using testing::NiceMock; using testing::Ref; using testing::Return; namespace Envoy { namespace Extensions { namespace Clusters { namespace Redis { namespace { const std::string BasicConfig = R"EOF( name: name connect_timeout: 0.25s dns_lookup_family: V4_ONLY load_assignment: endpoints: - lb_endpoints: - endpoint: address: socket_address: address: foo.bar.com port_value: 22120 cluster_type: name: envoy.clusters.redis typed_config: "@type": type.googleapis.com/google.protobuf.Struct value: cluster_refresh_rate: 4s cluster_refresh_timeout: 0.25s )EOF"; } static const int ResponseFlagSize = 11; static const int ResponseReplicaFlagSize = 4; class RedisClusterTest : public testing::Test, public Extensions::NetworkFilters::Common::Redis::Client::ClientFactory { public: // ClientFactory Extensions::NetworkFilters::Common::Redis::Client::ClientPtr create(Upstream::HostConstSharedPtr host, Event::Dispatcher&, const Extensions::NetworkFilters::Common::Redis::Client::Config&, const Extensions::NetworkFilters::Common::Redis::RedisCommandStatsSharedPtr&, Stats::Scope&, const std::string&, const std::string&) override { EXPECT_EQ(22120, host->address()->ip()->port()); return Extensions::NetworkFilters::Common::Redis::Client::ClientPtr{ create_(host->address()->asString())}; } MOCK_METHOD(Extensions::NetworkFilters::Common::Redis::Client::Client*, create_, (std::string)); protected: RedisClusterTest() : api_(Api::createApiForTest(stats_store_, random_)) {} std::list<std::string> hostListToAddresses(const Upstream::HostVector& hosts) { std::list<std::string> addresses; for (const Upstream::HostSharedPtr& host : hosts) { addresses.push_back(host->address()->asString()); } return addresses; } void setupFromV3Yaml(const std::string& yaml, bool avoid_boosting = true) { expectRedisSessionCreated(); NiceMock<Upstream::MockClusterManager> cm; envoy::config::cluster::v3::Cluster cluster_config = Upstream::parseClusterFromV3Yaml(yaml, avoid_boosting); Envoy::Stats::ScopePtr scope = stats_store_.createScope(fmt::format( "cluster.{}.", cluster_config.alt_stat_name().empty() ? cluster_config.name() : cluster_config.alt_stat_name())); Envoy::Server::Configuration::TransportSocketFactoryContextImpl factory_context( admin_, ssl_context_manager_, *scope, cm, local_info_, dispatcher_, stats_store_, singleton_manager_, tls_, validation_visitor_, *api_); envoy::config::cluster::redis::RedisClusterConfig config; Config::Utility::translateOpaqueConfig(cluster_config.cluster_type().typed_config(), ProtobufWkt::Struct::default_instance(), ProtobufMessage::getStrictValidationVisitor(), config); cluster_callback_ = std::make_shared<NiceMock<MockClusterSlotUpdateCallBack>>(); cluster_ = std::make_shared<RedisCluster>( cluster_config, TestUtility::downcastAndValidate<const envoy::config::cluster::redis::RedisClusterConfig&>( config), *this, cm, runtime_, *api_, dns_resolver_, factory_context, std::move(scope), false, cluster_callback_); // This allows us to create expectation on cluster slot response without waiting for // makeRequest. pool_callbacks_ = &cluster_->redis_discovery_session_; cluster_->prioritySet().addPriorityUpdateCb( [&](uint32_t, const Upstream::HostVector&, const Upstream::HostVector&) -> void { membership_updated_.ready(); }); } void setupFactoryFromV3Yaml(const std::string& yaml) { NiceMock<Upstream::MockClusterManager> cm; envoy::config::cluster::v3::Cluster cluster_config = Upstream::parseClusterFromV3Yaml(yaml); Envoy::Stats::ScopePtr scope = stats_store_.createScope(fmt::format( "cluster.{}.", cluster_config.alt_stat_name().empty() ? cluster_config.name() : cluster_config.alt_stat_name())); Envoy::Server::Configuration::TransportSocketFactoryContextImpl factory_context( admin_, ssl_context_manager_, *scope, cm, local_info_, dispatcher_, stats_store_, singleton_manager_, tls_, validation_visitor_, *api_); envoy::config::cluster::redis::RedisClusterConfig config; Config::Utility::translateOpaqueConfig(cluster_config.cluster_type().typed_config(), ProtobufWkt::Struct::default_instance(), validation_visitor_, config); NiceMock<AccessLog::MockAccessLogManager> log_manager; NiceMock<Upstream::Outlier::EventLoggerSharedPtr> outlier_event_logger; NiceMock<Envoy::Api::MockApi> api; Upstream::ClusterFactoryContextImpl cluster_factory_context( cm, stats_store_, tls_, std::move(dns_resolver_), ssl_context_manager_, runtime_, dispatcher_, log_manager, local_info_, admin_, singleton_manager_, std::move(outlier_event_logger), false, validation_visitor_, api); RedisClusterFactory factory = RedisClusterFactory(); factory.createClusterWithConfig(cluster_config, config, cluster_factory_context, factory_context, std::move(scope)); } void expectResolveDiscovery(Network::DnsLookupFamily dns_lookup_family, const std::string& expected_address, const std::list<std::string>& resolved_addresses, Network::DnsResolver::ResolutionStatus status = Network::DnsResolver::ResolutionStatus::Success) { EXPECT_CALL(*dns_resolver_, resolve(expected_address, dns_lookup_family, _)) .WillOnce(Invoke([status, resolved_addresses]( const std::string&, Network::DnsLookupFamily, Network::DnsResolver::ResolveCb cb) -> Network::ActiveDnsQuery* { cb(status, TestUtility::makeDnsResponse(resolved_addresses)); return nullptr; })); } void expectRedisSessionCreated() { resolve_timer_ = new Event::MockTimer(&dispatcher_); EXPECT_CALL(*resolve_timer_, disableTimer()); ON_CALL(random_, random()).WillByDefault(Return(0)); } void expectRedisResolve(bool create_client = false) { if (create_client) { client_ = new Extensions::NetworkFilters::Common::Redis::Client::MockClient(); EXPECT_CALL(*this, create_(_)).WillOnce(Return(client_)); EXPECT_CALL(*client_, addConnectionCallbacks(_)); EXPECT_CALL(*client_, close()); } EXPECT_CALL(*client_, makeRequest_(Ref(RedisCluster::ClusterSlotsRequest::instance_), _)) .WillOnce(Return(&pool_request_)); } void expectClusterSlotResponse(NetworkFilters::Common::Redis::RespValuePtr&& response) { EXPECT_CALL(*resolve_timer_, enableTimer(_, _)); pool_callbacks_->onResponse(std::move(response)); } void expectClusterSlotFailure() { EXPECT_CALL(*resolve_timer_, enableTimer(_, _)); pool_callbacks_->onFailure(); } NetworkFilters::Common::Redis::RespValuePtr singleSlotPrimaryReplica(const std::string& primary, const std::string& replica, int64_t port) const { std::vector<NetworkFilters::Common::Redis::RespValue> primary_1(2); primary_1[0].type(NetworkFilters::Common::Redis::RespType::BulkString); primary_1[0].asString() = primary; primary_1[1].type(NetworkFilters::Common::Redis::RespType::Integer); primary_1[1].asInteger() = port; std::vector<NetworkFilters::Common::Redis::RespValue> replica_1(2); replica_1[0].type(NetworkFilters::Common::Redis::RespType::BulkString); replica_1[0].asString() = replica; replica_1[1].type(NetworkFilters::Common::Redis::RespType::Integer); replica_1[1].asInteger() = port; std::vector<NetworkFilters::Common::Redis::RespValue> slot_1(ResponseReplicaFlagSize); slot_1[0].type(NetworkFilters::Common::Redis::RespType::Integer); slot_1[0].asInteger() = 0; slot_1[1].type(NetworkFilters::Common::Redis::RespType::Integer); slot_1[1].asInteger() = 16383; slot_1[2].type(NetworkFilters::Common::Redis::RespType::Array); slot_1[2].asArray().swap(primary_1); slot_1[3].type(NetworkFilters::Common::Redis::RespType::Array); slot_1[3].asArray().swap(replica_1); std::vector<NetworkFilters::Common::Redis::RespValue> slots(1); slots[0].type(NetworkFilters::Common::Redis::RespType::Array); slots[0].asArray().swap(slot_1); NetworkFilters::Common::Redis::RespValuePtr response( new NetworkFilters::Common::Redis::RespValue()); response->type(NetworkFilters::Common::Redis::RespType::Array); response->asArray().swap(slots); return response; } NetworkFilters::Common::Redis::RespValuePtr twoSlotsPrimaries() const { std::vector<NetworkFilters::Common::Redis::RespValue> primary_1(2); primary_1[0].type(NetworkFilters::Common::Redis::RespType::BulkString); primary_1[0].asString() = "127.0.0.1"; primary_1[1].type(NetworkFilters::Common::Redis::RespType::Integer); primary_1[1].asInteger() = 22120; std::vector<NetworkFilters::Common::Redis::RespValue> primary_2(2); primary_2[0].type(NetworkFilters::Common::Redis::RespType::BulkString); primary_2[0].asString() = "127.0.0.2"; primary_2[1].type(NetworkFilters::Common::Redis::RespType::Integer); primary_2[1].asInteger() = 22120; std::vector<NetworkFilters::Common::Redis::RespValue> slot_1(3); slot_1[0].type(NetworkFilters::Common::Redis::RespType::Integer); slot_1[0].asInteger() = 0; slot_1[1].type(NetworkFilters::Common::Redis::RespType::Integer); slot_1[1].asInteger() = 9999; slot_1[2].type(NetworkFilters::Common::Redis::RespType::Array); slot_1[2].asArray().swap(primary_1); std::vector<NetworkFilters::Common::Redis::RespValue> slot_2(3); slot_2[0].type(NetworkFilters::Common::Redis::RespType::Integer); slot_2[0].asInteger() = 10000; slot_2[1].type(NetworkFilters::Common::Redis::RespType::Integer); slot_2[1].asInteger() = 16383; slot_2[2].type(NetworkFilters::Common::Redis::RespType::Array); slot_2[2].asArray().swap(primary_2); std::vector<NetworkFilters::Common::Redis::RespValue> slots(2); slots[0].type(NetworkFilters::Common::Redis::RespType::Array); slots[0].asArray().swap(slot_1); slots[1].type(NetworkFilters::Common::Redis::RespType::Array); slots[1].asArray().swap(slot_2); NetworkFilters::Common::Redis::RespValuePtr response( new NetworkFilters::Common::Redis::RespValue()); response->type(NetworkFilters::Common::Redis::RespType::Array); response->asArray().swap(slots); return response; } NetworkFilters::Common::Redis::RespValuePtr twoSlotsPrimariesWithReplica() const { std::vector<NetworkFilters::Common::Redis::RespValue> primary_1(2); primary_1[0].type(NetworkFilters::Common::Redis::RespType::BulkString); primary_1[0].asString() = "127.0.0.1"; primary_1[1].type(NetworkFilters::Common::Redis::RespType::Integer); primary_1[1].asInteger() = 22120; std::vector<NetworkFilters::Common::Redis::RespValue> primary_2(2); primary_2[0].type(NetworkFilters::Common::Redis::RespType::BulkString); primary_2[0].asString() = "127.0.0.2"; primary_2[1].type(NetworkFilters::Common::Redis::RespType::Integer); primary_2[1].asInteger() = 22120; std::vector<NetworkFilters::Common::Redis::RespValue> replica_1(2); replica_1[0].type(NetworkFilters::Common::Redis::RespType::BulkString); replica_1[0].asString() = "127.0.0.3"; replica_1[1].type(NetworkFilters::Common::Redis::RespType::Integer); replica_1[1].asInteger() = 22120; std::vector<NetworkFilters::Common::Redis::RespValue> replica_2(2); replica_2[0].type(NetworkFilters::Common::Redis::RespType::BulkString); replica_2[0].asString() = "127.0.0.4"; replica_2[1].type(NetworkFilters::Common::Redis::RespType::Integer); replica_2[1].asInteger() = 22120; std::vector<NetworkFilters::Common::Redis::RespValue> slot_1(ResponseReplicaFlagSize); slot_1[0].type(NetworkFilters::Common::Redis::RespType::Integer); slot_1[0].asInteger() = 0; slot_1[1].type(NetworkFilters::Common::Redis::RespType::Integer); slot_1[1].asInteger() = 9999; slot_1[2].type(NetworkFilters::Common::Redis::RespType::Array); slot_1[2].asArray().swap(primary_1); slot_1[3].type(NetworkFilters::Common::Redis::RespType::Array); slot_1[3].asArray().swap(replica_1); std::vector<NetworkFilters::Common::Redis::RespValue> slot_2(ResponseReplicaFlagSize); slot_2[0].type(NetworkFilters::Common::Redis::RespType::Integer); slot_2[0].asInteger() = 10000; slot_2[1].type(NetworkFilters::Common::Redis::RespType::Integer); slot_2[1].asInteger() = 16383; slot_2[2].type(NetworkFilters::Common::Redis::RespType::Array); slot_2[2].asArray().swap(primary_2); slot_2[3].type(NetworkFilters::Common::Redis::RespType::Array); slot_2[3].asArray().swap(replica_2); std::vector<NetworkFilters::Common::Redis::RespValue> slots(2); slots[0].type(NetworkFilters::Common::Redis::RespType::Array); slots[0].asArray().swap(slot_1); slots[1].type(NetworkFilters::Common::Redis::RespType::Array); slots[1].asArray().swap(slot_2); NetworkFilters::Common::Redis::RespValuePtr response( new NetworkFilters::Common::Redis::RespValue()); response->type(NetworkFilters::Common::Redis::RespType::Array); response->asArray().swap(slots); return response; } NetworkFilters::Common::Redis::RespValue createStringField(bool is_correct_type, const std::string& correct_value) const { NetworkFilters::Common::Redis::RespValue respValue; if (is_correct_type) { respValue.type(NetworkFilters::Common::Redis::RespType::BulkString); respValue.asString() = correct_value; } else { respValue.type(NetworkFilters::Common::Redis::RespType::Integer); respValue.asInteger() = ResponseFlagSize; } return respValue; } NetworkFilters::Common::Redis::RespValue createIntegerField(bool is_correct_type, int64_t correct_value) const { NetworkFilters::Common::Redis::RespValue respValue; if (is_correct_type) { respValue.type(NetworkFilters::Common::Redis::RespType::Integer); respValue.asInteger() = correct_value; } else { respValue.type(NetworkFilters::Common::Redis::RespType::BulkString); respValue.asString() = "bad_value"; } return respValue; } NetworkFilters::Common::Redis::RespValue createArrayField(bool is_correct_type, std::vector<NetworkFilters::Common::Redis::RespValue>& correct_value) const { NetworkFilters::Common::Redis::RespValue respValue; if (is_correct_type) { respValue.type(NetworkFilters::Common::Redis::RespType::Array); respValue.asArray().swap(correct_value); } else { respValue.type(NetworkFilters::Common::Redis::RespType::BulkString); respValue.asString() = "bad value"; } return respValue; } // Create a redis cluster slot response. If a bit is set in the bitset, then that part of // of the response is correct, otherwise it's incorrect. NetworkFilters::Common::Redis::RespValuePtr createResponse(std::bitset<ResponseFlagSize> flags, std::bitset<ResponseReplicaFlagSize> replica_flags) const { int64_t idx(0); int64_t slots_type = idx++; int64_t slots_size = idx++; int64_t slot1_type = idx++; int64_t slot1_size = idx++; int64_t slot1_range_start_type = idx++; int64_t slot1_range_end_type = idx++; int64_t primary_type = idx++; int64_t primary_size = idx++; int64_t primary_ip_type = idx++; int64_t primary_ip_value = idx++; int64_t primary_port_type = idx++; idx = 0; int64_t replica_size = idx++; int64_t replica_ip_type = idx++; int64_t replica_ip_value = idx++; int64_t replica_port_type = idx++; std::vector<NetworkFilters::Common::Redis::RespValue> primary_1_array; if (flags.test(primary_size)) { // Ip field. if (flags.test(primary_ip_value)) { primary_1_array.push_back(createStringField(flags.test(primary_ip_type), "127.0.0.1")); } else { primary_1_array.push_back(createStringField(flags.test(primary_ip_type), "bad ip foo")); } // Port field. primary_1_array.push_back(createIntegerField(flags.test(primary_port_type), 22120)); } std::vector<NetworkFilters::Common::Redis::RespValue> replica_1_array; if (replica_flags.any()) { // Ip field. if (replica_flags.test(replica_ip_value)) { replica_1_array.push_back( createStringField(replica_flags.test(replica_ip_type), "127.0.0.2")); } else { replica_1_array.push_back( createStringField(replica_flags.test(replica_ip_type), "bad ip bar")); } // Port field. replica_1_array.push_back(createIntegerField(replica_flags.test(replica_port_type), 22120)); } std::vector<NetworkFilters::Common::Redis::RespValue> slot_1_array; if (flags.test(slot1_size)) { slot_1_array.push_back(createIntegerField(flags.test(slot1_range_start_type), 0)); slot_1_array.push_back(createIntegerField(flags.test(slot1_range_end_type), 16383)); slot_1_array.push_back(createArrayField(flags.test(primary_type), primary_1_array)); if (replica_flags.any()) { slot_1_array.push_back(createArrayField(replica_flags.test(replica_size), replica_1_array)); } } std::vector<NetworkFilters::Common::Redis::RespValue> slots_array; if (flags.test(slots_size)) { slots_array.push_back(createArrayField(flags.test(slot1_type), slot_1_array)); } NetworkFilters::Common::Redis::RespValuePtr response{ new NetworkFilters::Common::Redis::RespValue()}; if (flags.test(slots_type)) { response->type(NetworkFilters::Common::Redis::RespType::Array); response->asArray().swap(slots_array); } else { response->type(NetworkFilters::Common::Redis::RespType::BulkString); response->asString() = "Pong"; } return response; } void expectHealthyHosts(const std::list<std::string, std::allocator<std::string>>& healthy_hosts) { EXPECT_THAT(healthy_hosts, ContainerEq(hostListToAddresses( cluster_->prioritySet().hostSetsPerPriority()[0]->hosts()))); EXPECT_THAT(healthy_hosts, ContainerEq(hostListToAddresses( cluster_->prioritySet().hostSetsPerPriority()[0]->healthyHosts()))); EXPECT_EQ(1UL, cluster_->prioritySet().hostSetsPerPriority()[0]->hostsPerLocality().get().size()); EXPECT_EQ( 1UL, cluster_->prioritySet().hostSetsPerPriority()[0]->healthyHostsPerLocality().get().size()); } void testBasicSetup(const std::string& config, const std::string& expected_discovery_address) { setupFromV3Yaml(config); const std::list<std::string> resolved_addresses{"127.0.0.1", "127.0.0.2"}; expectResolveDiscovery(Network::DnsLookupFamily::V4Only, expected_discovery_address, resolved_addresses); expectRedisResolve(true); EXPECT_CALL(membership_updated_, ready()); EXPECT_CALL(initialized_, ready()); cluster_->initialize([&]() -> void { initialized_.ready(); }); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)); expectClusterSlotResponse(singleSlotPrimaryReplica("127.0.0.1", "127.0.0.2", 22120)); expectHealthyHosts(std::list<std::string>({"127.0.0.1:22120", "127.0.0.2:22120"})); // Promote replica to primary expectRedisResolve(); EXPECT_CALL(membership_updated_, ready()); resolve_timer_->invokeCallback(); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)); expectClusterSlotResponse(twoSlotsPrimaries()); expectHealthyHosts(std::list<std::string>({"127.0.0.1:22120", "127.0.0.2:22120"})); // No change. expectRedisResolve(); resolve_timer_->invokeCallback(); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)).WillOnce(Return(false)); expectClusterSlotResponse(twoSlotsPrimaries()); expectHealthyHosts(std::list<std::string>({"127.0.0.1:22120", "127.0.0.2:22120"})); // Add replicas to primaries expectRedisResolve(); EXPECT_CALL(membership_updated_, ready()); resolve_timer_->invokeCallback(); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)); expectClusterSlotResponse(twoSlotsPrimariesWithReplica()); expectHealthyHosts(std::list<std::string>( {"127.0.0.1:22120", "127.0.0.3:22120", "127.0.0.2:22120", "127.0.0.4:22120"})); // No change. expectRedisResolve(); resolve_timer_->invokeCallback(); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)).WillOnce(Return(false)); expectClusterSlotResponse(twoSlotsPrimariesWithReplica()); expectHealthyHosts(std::list<std::string>( {"127.0.0.1:22120", "127.0.0.3:22120", "127.0.0.2:22120", "127.0.0.4:22120"})); // Remove 2nd shard. expectRedisResolve(); EXPECT_CALL(membership_updated_, ready()); resolve_timer_->invokeCallback(); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)); expectClusterSlotResponse(singleSlotPrimaryReplica("127.0.0.1", "127.0.0.2", 22120)); expectHealthyHosts(std::list<std::string>({"127.0.0.1:22120", "127.0.0.2:22120"})); } void exerciseStubs() { EXPECT_CALL(dispatcher_, createTimer_(_)); RedisCluster::RedisDiscoverySession discovery_session(*cluster_, *this); EXPECT_FALSE(discovery_session.enableHashtagging()); EXPECT_EQ(discovery_session.bufferFlushTimeoutInMs(), std::chrono::milliseconds(0)); EXPECT_EQ(discovery_session.maxUpstreamUnknownConnections(), 0); NetworkFilters::Common::Redis::RespValuePtr dummy_value{ new NetworkFilters::Common::Redis::RespValue()}; dummy_value->type(NetworkFilters::Common::Redis::RespType::Error); dummy_value->asString() = "dummy text"; EXPECT_TRUE(discovery_session.onRedirection(std::move(dummy_value), "dummy ip", false)); RedisCluster::RedisDiscoveryClient discovery_client(discovery_session); EXPECT_NO_THROW(discovery_client.onAboveWriteBufferHighWatermark()); EXPECT_NO_THROW(discovery_client.onBelowWriteBufferLowWatermark()); } void testDnsResolve(const char* const address, const int port) { RedisCluster::DnsDiscoveryResolveTarget resolver_target(*cluster_, address, port); EXPECT_CALL(*dns_resolver_, resolve(address, Network::DnsLookupFamily::V4Only, _)) .WillOnce(Invoke([&](const std::string&, Network::DnsLookupFamily, Network::DnsResolver::ResolveCb) -> Network::ActiveDnsQuery* { return &active_dns_query_; })); ; resolver_target.startResolveDns(); EXPECT_CALL(active_dns_query_, cancel()); } Stats::TestUtil::TestStore stats_store_; Ssl::MockContextManager ssl_context_manager_; std::shared_ptr<NiceMock<Network::MockDnsResolver>> dns_resolver_{ new NiceMock<Network::MockDnsResolver>}; NiceMock<Random::MockRandomGenerator> random_; NiceMock<ThreadLocal::MockInstance> tls_; Event::MockTimer* resolve_timer_; ReadyWatcher membership_updated_; ReadyWatcher initialized_; NiceMock<Runtime::MockLoader> runtime_; NiceMock<Event::MockDispatcher> dispatcher_; NiceMock<LocalInfo::MockLocalInfo> local_info_; NiceMock<Server::MockAdmin> admin_; Singleton::ManagerImpl singleton_manager_{Thread::threadFactoryForTest()}; NiceMock<ProtobufMessage::MockValidationVisitor> validation_visitor_; Api::ApiPtr api_; std::shared_ptr<Upstream::MockClusterMockPrioritySet> hosts_; Upstream::MockHealthCheckEventLogger* event_logger_{}; Event::MockTimer* interval_timer_{}; Extensions::NetworkFilters::Common::Redis::Client::MockClient* client_{}; Extensions::NetworkFilters::Common::Redis::Client::MockPoolRequest pool_request_; Extensions::NetworkFilters::Common::Redis::Client::ClientCallbacks* pool_callbacks_{}; std::shared_ptr<RedisCluster> cluster_; std::shared_ptr<NiceMock<MockClusterSlotUpdateCallBack>> cluster_callback_; Network::MockActiveDnsQuery active_dns_query_; }; using RedisDnsConfigTuple = std::tuple<std::string, Network::DnsLookupFamily, std::list<std::string>, std::list<std::string>>; std::vector<RedisDnsConfigTuple> generateRedisDnsParams() { std::vector<RedisDnsConfigTuple> dns_config; { std::string family_yaml(""); Network::DnsLookupFamily family(Network::DnsLookupFamily::Auto); std::list<std::string> dns_response{"127.0.0.1", "127.0.0.2"}; std::list<std::string> resolved_host{"127.0.0.1:22120", "127.0.0.2:22120"}; dns_config.push_back(std::make_tuple(family_yaml, family, dns_response, resolved_host)); } { std::string family_yaml(R"EOF(dns_lookup_family: V4_ONLY)EOF"); Network::DnsLookupFamily family(Network::DnsLookupFamily::V4Only); std::list<std::string> dns_response{"127.0.0.1", "127.0.0.2"}; std::list<std::string> resolved_host{"127.0.0.1:22120", "127.0.0.2:22120"}; dns_config.push_back(std::make_tuple(family_yaml, family, dns_response, resolved_host)); } { std::string family_yaml(R"EOF(dns_lookup_family: V6_ONLY)EOF"); Network::DnsLookupFamily family(Network::DnsLookupFamily::V6Only); std::list<std::string> dns_response{"::1", "2001:0db8:85a3:0000:0000:8a2e:0370:7334"}; std::list<std::string> resolved_host{"[::1]:22120", "[2001:db8:85a3::8a2e:370:7334]:22120"}; dns_config.push_back(std::make_tuple(family_yaml, family, dns_response, resolved_host)); } { std::string family_yaml(R"EOF(dns_lookup_family: AUTO)EOF"); Network::DnsLookupFamily family(Network::DnsLookupFamily::Auto); std::list<std::string> dns_response{"::1", "2001:0db8:85a3:0000:0000:8a2e:0370:7334"}; std::list<std::string> resolved_host{"[::1]:22120", "[2001:db8:85a3::8a2e:370:7334]:22120"}; dns_config.push_back(std::make_tuple(family_yaml, family, dns_response, resolved_host)); } return dns_config; } class RedisDnsParamTest : public RedisClusterTest, public testing::WithParamInterface<RedisDnsConfigTuple> {}; INSTANTIATE_TEST_SUITE_P(DnsParam, RedisDnsParamTest, testing::ValuesIn(generateRedisDnsParams())); // Validate that if the DNS and CLUSTER SLOT resolve immediately, we have the expected // host state and initialization callback invocation. TEST_P(RedisDnsParamTest, ImmediateResolveDns) { const std::string config = R"EOF( name: name connect_timeout: 0.25s )EOF" + std::get<0>(GetParam()) + R"EOF( load_assignment: endpoints: - lb_endpoints: - endpoint: address: socket_address: address: foo.bar.com port_value: 22120 cluster_type: name: envoy.clusters.redis typed_config: "@type": type.googleapis.com/google.protobuf.Struct value: cluster_refresh_rate: 4s cluster_refresh_timeout: 0.25s )EOF"; setupFromV3Yaml(config); expectRedisResolve(true); EXPECT_CALL(*dns_resolver_, resolve("foo.bar.com", std::get<1>(GetParam()), _)) .WillOnce(Invoke([&](const std::string&, Network::DnsLookupFamily, Network::DnsResolver::ResolveCb cb) -> Network::ActiveDnsQuery* { std::list<std::string> address_pair = std::get<2>(GetParam()); cb(Network::DnsResolver::ResolutionStatus::Success, TestUtility::makeDnsResponse(address_pair)); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)); expectClusterSlotResponse( singleSlotPrimaryReplica(address_pair.front(), address_pair.back(), 22120)); return nullptr; })); EXPECT_CALL(membership_updated_, ready()); EXPECT_CALL(initialized_, ready()); cluster_->initialize([&]() -> void { initialized_.ready(); }); expectHealthyHosts(std::get<3>(GetParam())); } TEST_F(RedisClusterTest, EmptyDnsResponse) { Event::MockTimer* dns_timer = new NiceMock<Event::MockTimer>(&dispatcher_); setupFromV3Yaml(BasicConfig); const std::list<std::string> resolved_addresses{}; EXPECT_CALL(*dns_timer, enableTimer(_, _)); expectResolveDiscovery(Network::DnsLookupFamily::V4Only, "foo.bar.com", resolved_addresses); EXPECT_CALL(initialized_, ready()); cluster_->initialize([&]() -> void { initialized_.ready(); }); EXPECT_EQ(0UL, cluster_->prioritySet().hostSetsPerPriority()[0]->hosts().size()); EXPECT_EQ(0UL, cluster_->prioritySet().hostSetsPerPriority()[0]->healthyHosts().size()); EXPECT_EQ(1U, cluster_->info()->stats().update_empty_.value()); // Does not recreate the timer on subsequent DNS resolve calls. EXPECT_CALL(*dns_timer, enableTimer(_, _)); expectResolveDiscovery(Network::DnsLookupFamily::V4Only, "foo.bar.com", resolved_addresses); dns_timer->invokeCallback(); EXPECT_EQ(0UL, cluster_->prioritySet().hostSetsPerPriority()[0]->hosts().size()); EXPECT_EQ(0UL, cluster_->prioritySet().hostSetsPerPriority()[0]->healthyHosts().size()); EXPECT_EQ(2U, cluster_->info()->stats().update_empty_.value()); } TEST_F(RedisClusterTest, FailedDnsResponse) { Event::MockTimer* dns_timer = new NiceMock<Event::MockTimer>(&dispatcher_); setupFromV3Yaml(BasicConfig); const std::list<std::string> resolved_addresses{}; EXPECT_CALL(*dns_timer, enableTimer(_, _)); expectResolveDiscovery(Network::DnsLookupFamily::V4Only, "foo.bar.com", resolved_addresses, Network::DnsResolver::ResolutionStatus::Failure); EXPECT_CALL(initialized_, ready()); cluster_->initialize([&]() -> void { initialized_.ready(); }); EXPECT_EQ(0UL, cluster_->prioritySet().hostSetsPerPriority()[0]->hosts().size()); EXPECT_EQ(0UL, cluster_->prioritySet().hostSetsPerPriority()[0]->healthyHosts().size()); EXPECT_EQ(0U, cluster_->info()->stats().update_empty_.value()); // Does not recreate the timer on subsequent DNS resolve calls. EXPECT_CALL(*dns_timer, enableTimer(_, _)); expectResolveDiscovery(Network::DnsLookupFamily::V4Only, "foo.bar.com", resolved_addresses); dns_timer->invokeCallback(); EXPECT_EQ(0UL, cluster_->prioritySet().hostSetsPerPriority()[0]->hosts().size()); EXPECT_EQ(0UL, cluster_->prioritySet().hostSetsPerPriority()[0]->healthyHosts().size()); EXPECT_EQ(1U, cluster_->info()->stats().update_empty_.value()); } TEST_F(RedisClusterTest, Basic) { // Using load assignment. const std::string basic_yaml_load_assignment = R"EOF( name: name connect_timeout: 0.25s dns_lookup_family: V4_ONLY load_assignment: cluster_name: name endpoints: - lb_endpoints: - endpoint: address: socket_address: address: foo.bar.com port_value: 22120 health_check_config: port_value: 8000 cluster_type: name: envoy.clusters.redis typed_config: "@type": type.googleapis.com/google.protobuf.Struct value: cluster_refresh_rate: 4s cluster_refresh_timeout: 0.25s )EOF"; testBasicSetup(BasicConfig, "foo.bar.com"); testBasicSetup(basic_yaml_load_assignment, "foo.bar.com"); // Exercise stubbed out interfaces for coverage. exerciseStubs(); } TEST_F(RedisClusterTest, RedisResolveFailure) { setupFromV3Yaml(BasicConfig); const std::list<std::string> resolved_addresses{"127.0.0.1", "127.0.0.2"}; expectResolveDiscovery(Network::DnsLookupFamily::V4Only, "foo.bar.com", resolved_addresses); expectRedisResolve(true); cluster_->initialize([&]() -> void { initialized_.ready(); }); // Initialization will wait til the redis cluster succeed. expectClusterSlotFailure(); EXPECT_EQ(1U, cluster_->info()->stats().update_attempt_.value()); EXPECT_EQ(1U, cluster_->info()->stats().update_failure_.value()); expectRedisResolve(true); resolve_timer_->invokeCallback(); EXPECT_CALL(membership_updated_, ready()); EXPECT_CALL(initialized_, ready()); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)); expectClusterSlotResponse(singleSlotPrimaryReplica("127.0.0.1", "127.0.0.2", 22120)); expectHealthyHosts(std::list<std::string>({"127.0.0.1:22120", "127.0.0.2:22120"})); // Expect no change if resolve failed. expectRedisResolve(); resolve_timer_->invokeCallback(); expectClusterSlotFailure(); expectHealthyHosts(std::list<std::string>({"127.0.0.1:22120", "127.0.0.2:22120"})); EXPECT_EQ(3U, cluster_->info()->stats().update_attempt_.value()); EXPECT_EQ(2U, cluster_->info()->stats().update_failure_.value()); } TEST_F(RedisClusterTest, FactoryInitNotRedisClusterTypeFailure) { const std::string basic_yaml_hosts = R"EOF( name: name connect_timeout: 0.25s dns_lookup_family: V4_ONLY load_assignment: endpoints: - lb_endpoints: - endpoint: address: socket_address: address: foo.bar.com port_value: 22120 cluster_type: name: envoy.clusters.memcached typed_config: "@type": type.googleapis.com/google.protobuf.Struct value: cluster_refresh_rate: 4s cluster_refresh_timeout: 0.25s )EOF"; EXPECT_THROW_WITH_MESSAGE(setupFactoryFromV3Yaml(basic_yaml_hosts), EnvoyException, "Redis cluster can only created with redis cluster type."); } TEST_F(RedisClusterTest, FactoryInitRedisClusterTypeSuccess) { setupFactoryFromV3Yaml(BasicConfig); } TEST_F(RedisClusterTest, RedisErrorResponse) { setupFromV3Yaml(BasicConfig); const std::list<std::string> resolved_addresses{"127.0.0.1", "127.0.0.2"}; expectResolveDiscovery(Network::DnsLookupFamily::V4Only, "foo.bar.com", resolved_addresses); expectRedisResolve(true); cluster_->initialize([&]() -> void { initialized_.ready(); }); // Initialization will wait til the redis cluster succeed. std::vector<NetworkFilters::Common::Redis::RespValue> hello_world(2); hello_world[0].type(NetworkFilters::Common::Redis::RespType::BulkString); hello_world[0].asString() = "hello"; hello_world[1].type(NetworkFilters::Common::Redis::RespType::BulkString); hello_world[1].asString() = "world"; NetworkFilters::Common::Redis::RespValuePtr hello_world_response( new NetworkFilters::Common::Redis::RespValue()); hello_world_response->type(NetworkFilters::Common::Redis::RespType::Array); hello_world_response->asArray().swap(hello_world); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)).Times(0); expectClusterSlotResponse(std::move(hello_world_response)); EXPECT_EQ(1U, cluster_->info()->stats().update_attempt_.value()); EXPECT_EQ(1U, cluster_->info()->stats().update_failure_.value()); expectRedisResolve(); resolve_timer_->invokeCallback(); EXPECT_CALL(membership_updated_, ready()); EXPECT_CALL(initialized_, ready()); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)); std::bitset<ResponseFlagSize> single_slot_primary(0xfff); std::bitset<ResponseReplicaFlagSize> no_replica(0); expectClusterSlotResponse(createResponse(single_slot_primary, no_replica)); expectHealthyHosts(std::list<std::string>({"127.0.0.1:22120"})); // Expect no change if resolve failed. uint64_t update_attempt = 2; uint64_t update_failure = 1; // Test every combination the cluster slots response. for (uint64_t i = 0; i < (1 << ResponseFlagSize); i++) { std::bitset<ResponseFlagSize> flags(i); expectRedisResolve(); resolve_timer_->invokeCallback(); if (flags.all()) { EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)).WillOnce(Return(false)); } expectClusterSlotResponse(createResponse(flags, no_replica)); expectHealthyHosts(std::list<std::string>({"127.0.0.1:22120"})); EXPECT_EQ(++update_attempt, cluster_->info()->stats().update_attempt_.value()); if (!flags.all()) { EXPECT_EQ(++update_failure, cluster_->info()->stats().update_failure_.value()); } } } TEST_F(RedisClusterTest, RedisReplicaErrorResponse) { setupFromV3Yaml(BasicConfig); const std::list<std::string> resolved_addresses{"127.0.0.1", "127.0.0.2"}; expectResolveDiscovery(Network::DnsLookupFamily::V4Only, "foo.bar.com", resolved_addresses); expectRedisResolve(true); cluster_->initialize([&]() -> void { initialized_.ready(); }); EXPECT_CALL(membership_updated_, ready()); EXPECT_CALL(initialized_, ready()); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)); std::bitset<ResponseFlagSize> single_slot_primary(0xfff); std::bitset<ResponseReplicaFlagSize> no_replica(0); expectClusterSlotResponse(createResponse(single_slot_primary, no_replica)); expectHealthyHosts(std::list<std::string>({"127.0.0.1:22120"})); // Expect no change if resolve failed. uint64_t update_attempt = 1; uint64_t update_failure = 0; // Test every combination the replica error response. for (uint64_t i = 1; i < (1 << ResponseReplicaFlagSize); i++) { std::bitset<ResponseReplicaFlagSize> replica_flags(i); expectRedisResolve(); resolve_timer_->invokeCallback(); if (replica_flags.all()) { EXPECT_CALL(membership_updated_, ready()); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)).WillOnce(Return(false)); } expectHealthyHosts(std::list<std::string>({"127.0.0.1:22120"})); expectClusterSlotResponse(createResponse(single_slot_primary, replica_flags)); EXPECT_EQ(++update_attempt, cluster_->info()->stats().update_attempt_.value()); if (!(replica_flags.all() || replica_flags.none())) { EXPECT_EQ(++update_failure, cluster_->info()->stats().update_failure_.value()); } } } TEST_F(RedisClusterTest, DnsDiscoveryResolverBasic) { setupFromV3Yaml(BasicConfig); testDnsResolve("foo.bar.com", 22120); } TEST_F(RedisClusterTest, MultipleDnsDiscovery) { const std::string config = R"EOF( name: name connect_timeout: 0.25s dns_lookup_family: V4_ONLY load_assignment: endpoints: - lb_endpoints: - endpoint: address: socket_address: address: foo.bar.com port_value: 22120 - endpoint: address: socket_address: address: foo1.bar.com port_value: 22120 cluster_type: name: envoy.clusters.redis typed_config: "@type": type.googleapis.com/google.protobuf.Struct value: cluster_refresh_rate: 4s cluster_refresh_timeout: 0.25s )EOF"; setupFromV3Yaml(config); // Only single in-flight "cluster slots" call. expectRedisResolve(true); ReadyWatcher dns_resolve_1; ReadyWatcher dns_resolve_2; EXPECT_CALL(*dns_resolver_, resolve("foo.bar.com", _, _)) .WillOnce(Invoke([&](const std::string&, Network::DnsLookupFamily, Network::DnsResolver::ResolveCb cb) -> Network::ActiveDnsQuery* { cb(Network::DnsResolver::ResolutionStatus::Success, TestUtility::makeDnsResponse(std::list<std::string>({"127.0.0.1", "127.0.0.2"}))); return nullptr; })); EXPECT_CALL(*dns_resolver_, resolve("foo1.bar.com", _, _)) .WillOnce(Invoke([&](const std::string&, Network::DnsLookupFamily, Network::DnsResolver::ResolveCb cb) -> Network::ActiveDnsQuery* { cb(Network::DnsResolver::ResolutionStatus::Success, TestUtility::makeDnsResponse(std::list<std::string>({"127.0.0.3", "127.0.0.4"}))); return nullptr; })); cluster_->initialize([&]() -> void { initialized_.ready(); }); // Pending RedisResolve will call cancel in the destructor. EXPECT_CALL(pool_request_, cancel()); } TEST_F(RedisClusterTest, HostRemovalAfterHcFail) { setupFromV3Yaml(BasicConfig); auto health_checker = std::make_shared<Upstream::MockHealthChecker>(); EXPECT_CALL(*health_checker, start()); EXPECT_CALL(*health_checker, addHostCheckCompleteCb(_)).Times(2); cluster_->setHealthChecker(health_checker); const std::list<std::string> resolved_addresses{"127.0.0.1", "127.0.0.2"}; expectResolveDiscovery(Network::DnsLookupFamily::V4Only, "foo.bar.com", resolved_addresses); expectRedisResolve(true); EXPECT_CALL(membership_updated_, ready()); EXPECT_CALL(initialized_, ready()); cluster_->initialize([&]() -> void { initialized_.ready(); }); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)); expectClusterSlotResponse(twoSlotsPrimariesWithReplica()); // Verify that all hosts are initially marked with FAILED_ACTIVE_HC, then // clear the flag to simulate that these hosts have been successfully health // checked. { EXPECT_CALL(membership_updated_, ready()); const auto& hosts = cluster_->prioritySet().hostSetsPerPriority()[0]->hosts(); EXPECT_EQ(4UL, hosts.size()); for (size_t i = 0; i < 4; ++i) { EXPECT_TRUE(hosts[i]->healthFlagGet(Upstream::Host::HealthFlag::FAILED_ACTIVE_HC)); hosts[i]->healthFlagClear(Upstream::Host::HealthFlag::FAILED_ACTIVE_HC); hosts[i]->healthFlagClear(Upstream::Host::HealthFlag::PENDING_ACTIVE_HC); health_checker->runCallbacks(hosts[i], Upstream::HealthTransition::Changed); } expectHealthyHosts(std::list<std::string>( {"127.0.0.1:22120", "127.0.0.3:22120", "127.0.0.2:22120", "127.0.0.4:22120"})); } // Fail a HC for one of the hosts { EXPECT_CALL(membership_updated_, ready()); EXPECT_CALL(*cluster_callback_, onHostHealthUpdate()); const auto& hosts = cluster_->prioritySet().hostSetsPerPriority()[0]->hosts(); hosts[2]->healthFlagSet(Upstream::Host::HealthFlag::FAILED_ACTIVE_HC); health_checker->runCallbacks(hosts[2], Upstream::HealthTransition::Changed); EXPECT_THAT(cluster_->prioritySet().hostSetsPerPriority()[0]->hosts().size(), 4U); EXPECT_THAT(cluster_->prioritySet().hostSetsPerPriority()[0]->healthyHosts().size(), 3U); } // Remove 2nd shard. { expectRedisResolve(); EXPECT_CALL(membership_updated_, ready()); resolve_timer_->invokeCallback(); EXPECT_CALL(*cluster_callback_, onClusterSlotUpdate(_, _)); expectClusterSlotResponse(singleSlotPrimaryReplica("127.0.0.1", "127.0.0.3", 22120)); const auto& hosts = cluster_->prioritySet().hostSetsPerPriority()[0]->hosts(); // We expect the host that failed health checks to be instantly removed, // but the other should remain until its health check fails too. EXPECT_THAT(cluster_->prioritySet().hostSetsPerPriority()[0]->hosts().size(), 3U); expectHealthyHosts( std::list<std::string>({"127.0.0.1:22120", "127.0.0.3:22120", "127.0.0.4:22120"})); EXPECT_TRUE(hosts[2]->healthFlagGet(Upstream::Host::HealthFlag::PENDING_DYNAMIC_REMOVAL)); } /* // TODO(#14630) This part of the test doesn't pass, as removal of PENDING_DYNAMIC_REMOVAL hosts // does not seem to be implemented for redis clusters at present. // Fail the HC for the remaining removed host { EXPECT_CALL(membership_updated_, ready()); EXPECT_CALL(*cluster_callback_, onHostHealthUpdate()); const auto& hosts = cluster_->prioritySet().hostSetsPerPriority()[0]->hosts(); EXPECT_TRUE(hosts[2]->healthFlagGet(Upstream::Host::HealthFlag::PENDING_DYNAMIC_REMOVAL)); hosts[2]->healthFlagSet(Upstream::Host::HealthFlag::FAILED_ACTIVE_HC); health_checker->runCallbacks(hosts[2], Upstream::HealthTransition::Changed); // The pending removal host should also have been removed now EXPECT_THAT(cluster_->prioritySet().hostSetsPerPriority()[0]->hosts().size(), 2U); expectHealthyHosts(std::list<std::string>( {"127.0.0.1:22120", "127.0.0.3:22120"})); } */ } } // namespace Redis } // namespace Clusters } // namespace Extensions } // namespace Envoy
43.324171
100
0.69683
mengmichael1
3331139de82861cc8f6e5e025b2084bd2fd47043
5,030
hpp
C++
solvers/elliptic/elliptic.hpp
MalachiTimothyPhillips/libparanumal
f3fd4505df56207b05aa86164124ab6bad83f92a
[ "MIT" ]
null
null
null
solvers/elliptic/elliptic.hpp
MalachiTimothyPhillips/libparanumal
f3fd4505df56207b05aa86164124ab6bad83f92a
[ "MIT" ]
null
null
null
solvers/elliptic/elliptic.hpp
MalachiTimothyPhillips/libparanumal
f3fd4505df56207b05aa86164124ab6bad83f92a
[ "MIT" ]
null
null
null
/* The MIT License (MIT) Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ELLIPTIC_HPP #define ELLIPTIC_HPP 1 #include "core.hpp" #include "mesh.hpp" #include "solver.hpp" #include "linAlg.hpp" #include "precon.hpp" #include "linearSolver.hpp" #include "parAlmond.hpp" #define DELLIPTIC LIBP_DIR"/solvers/elliptic/" class ellipticSettings_t: public settings_t { public: ellipticSettings_t(MPI_Comm& _comm); void report(); void parseFromFile(occaSettings_t& occaSettings, meshSettings_t& meshSettings, const string filename); }; void ellipticAddRunSettings(settings_t& settings); void ellipticAddSettings(settings_t& settings, const string prefix=""); class elliptic_t: public solver_t { public: int Nfields; dfloat lambda; dfloat tau; int disc_ipdg, disc_c0; halo_t* traceHalo; precon_t* precon; dfloat *grad; occa::memory o_grad; dfloat *weight, *weightG; occa::memory o_weight, o_weightG; //C0-FEM mask data ogs_t *ogsMasked; int *mapB; // boundary flag of face nodes dlong Nmasked; dlong *maskIds; hlong *maskedGlobalIds; hlong *maskedGlobalNumbering; int *maskedGlobalOwners; occa::memory o_maskIds; occa::memory o_mapB; int *BCType; int *EToB; occa::memory o_EToB; int allNeumann; dfloat allNeumannPenalty; dfloat allNeumannScale; occa::kernel maskKernel; occa::kernel partialAxKernel; occa::kernel partialGradientKernel; occa::kernel partialIpdgKernel; elliptic_t() = delete; elliptic_t(mesh_t& _mesh, linAlg_t& _linAlg, settings_t& _settings, dfloat _lambda): solver_t(_mesh, _linAlg, _settings), lambda(_lambda) {} ~elliptic_t(); //setup static elliptic_t& Setup(mesh_t& mesh, linAlg_t& linAlg, ellipticSettings_t& settings, dfloat lambda, const int NBCTypes, const int *BCType); void BoundarySetup(); void Run(); int Solve(linearSolver_t& linearSolver, occa::memory &o_x, occa::memory &o_r, const dfloat tol, const int MAXIT, const int verbose); void PlotFields(dfloat* Q, char *fileName); void Operator(occa::memory& o_q, occa::memory& o_Aq); void BuildOperatorMatrixIpdg(parAlmond::parCOO& A); void BuildOperatorMatrixContinuous(parAlmond::parCOO& A); void BuildOperatorMatrixContinuousTri2D(parAlmond::parCOO& A); void BuildOperatorMatrixContinuousTri3D(parAlmond::parCOO& A); void BuildOperatorMatrixContinuousQuad2D(parAlmond::parCOO& A); void BuildOperatorMatrixContinuousQuad3D(parAlmond::parCOO& A); void BuildOperatorMatrixContinuousTet3D(parAlmond::parCOO& A); void BuildOperatorMatrixContinuousHex3D(parAlmond::parCOO& A); void BuildOperatorMatrixIpdgTri2D(parAlmond::parCOO& A); void BuildOperatorMatrixIpdgTri3D(parAlmond::parCOO& A); void BuildOperatorMatrixIpdgQuad2D(parAlmond::parCOO& A); void BuildOperatorMatrixIpdgQuad3D(parAlmond::parCOO& A); void BuildOperatorMatrixIpdgTet3D(parAlmond::parCOO& A); void BuildOperatorMatrixIpdgHex3D(parAlmond::parCOO& A); void BuildOperatorDiagonal(dfloat *diagA); void BuildOperatorDiagonalContinuousTri2D(dfloat *diagA); void BuildOperatorDiagonalContinuousTri3D(dfloat *diagA); void BuildOperatorDiagonalContinuousQuad2D(dfloat *diagA); void BuildOperatorDiagonalContinuousQuad3D(dfloat *diagA); void BuildOperatorDiagonalContinuousTet3D(dfloat *diagA); void BuildOperatorDiagonalContinuousHex3D(dfloat *diagA); void BuildOperatorDiagonalIpdgTri2D(dfloat *diagA); void BuildOperatorDiagonalIpdgTri3D(dfloat *diagA); void BuildOperatorDiagonalIpdgQuad2D(dfloat *diagA); void BuildOperatorDiagonalIpdgQuad3D(dfloat *diagA); void BuildOperatorDiagonalIpdgTet3D(dfloat *diagA); void BuildOperatorDiagonalIpdgHex3D(dfloat *diagA); elliptic_t& SetupNewDegree(mesh_t& meshF); elliptic_t* SetupRingPatch(mesh_t& meshPatch); void ZeroMean(occa::memory &o_q); }; #endif
30.858896
79
0.757058
MalachiTimothyPhillips
3332526f3d566e703fa2abc40ae7419c1f800ddc
8,266
hpp
C++
libraries/chain/include/graphene/chain/config.hpp
InsurChain/insur-core
c1743f1ced41b82cd7632016639230dfd1669704
[ "MIT" ]
8
2018-03-30T02:05:03.000Z
2021-01-07T10:55:16.000Z
libraries/chain/include/graphene/chain/config.hpp
InsurChain/insur-core
c1743f1ced41b82cd7632016639230dfd1669704
[ "MIT" ]
1
2021-05-10T02:48:10.000Z
2021-05-10T02:48:10.000Z
libraries/chain/include/graphene/chain/config.hpp
InsurChain/insur-core
c1743f1ced41b82cd7632016639230dfd1669704
[ "MIT" ]
3
2018-03-30T03:45:57.000Z
2019-05-23T17:05:08.000Z
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * 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. */ #pragma once #define GRAPHENE_SYMBOL "GXC" #define GRAPHENE_ADDRESS_PREFIX "GXC" #define GRAPHENE_SYMBOL_GXS "GXS" #define GRAPHENE_MIN_ACCOUNT_NAME_LENGTH 1 #define GRAPHENE_MAX_ACCOUNT_NAME_LENGTH 63 #define GRAPHENE_MIN_ASSET_SYMBOL_LENGTH 3 #define GRAPHENE_MAX_ASSET_SYMBOL_LENGTH 16 #define GRAPHENE_MAX_SHARE_SUPPLY int64_t(100000000000000000ll) #define GRAPHENE_MAX_SIG_CHECK_DEPTH 2 /** * Don't allow the committee_members to publish a limit that would * make the network unable to operate. */ #define GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT 1024 #define GRAPHENE_MIN_BLOCK_INTERVAL 1 /* seconds */ #define GRAPHENE_MAX_BLOCK_INTERVAL 30 /* seconds */ #define GRAPHENE_DEFAULT_BLOCK_INTERVAL 5 /* seconds */ #define GRAPHENE_DEFAULT_MAX_TRANSACTION_SIZE 2048 #define GRAPHENE_DEFAULT_MAX_BLOCK_SIZE (2*1000*1000) /* < 2 MiB (less than MAX_MESSAGE_SIZE in graphene/net/config.hpp) */ #define GRAPHENE_DEFAULT_MAX_TIME_UNTIL_EXPIRATION (60*60*24) // seconds, aka: 1 day #define GRAPHENE_DEFAULT_MAINTENANCE_INTERVAL (60*60*24) // seconds, aka: 1 day #define GRAPHENE_DEFAULT_MAINTENANCE_SKIP_SLOTS 3 // number of slots to skip for maintenance interval #define GRAPHENE_MIN_UNDO_HISTORY 10 #define GRAPHENE_MAX_UNDO_HISTORY 10000 #define GRAPHENE_MIN_BLOCK_SIZE_LIMIT (GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT*5) // 5 transactions per block #define GRAPHENE_BLOCKCHAIN_PRECISION uint64_t( 100000 ) #define GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS 5 /** percentage fields are fixed point with a denominator of 10,000 */ #define GRAPHENE_100_PERCENT 10000 #define GRAPHENE_1_PERCENT (GRAPHENE_100_PERCENT/100) /** NOTE: making this a power of 2 (say 2^15) would greatly accelerate fee calcs */ #define GRAPHENE_MAX_MARKET_FEE_PERCENT GRAPHENE_100_PERCENT #define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_DELAY (60*60*24) ///< 1 day #define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_OFFSET 0 ///< 1% #define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_MAX_VOLUME (20* GRAPHENE_1_PERCENT) ///< 20% #define GRAPHENE_DEFAULT_PRICE_FEED_LIFETIME (60*60*24) ///< 1 day #define GRAPHENE_DEFAULT_MAX_AUTHORITY_MEMBERSHIP 10 #define GRAPHENE_DEFAULT_MAX_ASSET_WHITELIST_AUTHORITIES 10 #define GRAPHENE_DEFAULT_MAX_ASSET_FEED_PUBLISHERS 10 #define GRAPHENE_DEFAULT_COMMISSION_PERCENT 1000 /** * These ratios are fixed point numbers with a denominator of GRAPHENE_COLLATERAL_RATIO_DENOM, the * minimum maitenance collateral is therefore 1.001x and the default * maintenance ratio is 1.75x */ ///@{ #define GRAPHENE_COLLATERAL_RATIO_DENOM 1000 #define GRAPHENE_MIN_COLLATERAL_RATIO 1001 ///< lower than this could result in divide by 0 #define GRAPHENE_MAX_COLLATERAL_RATIO 32000 ///< higher than this is unnecessary and may exceed int16 storage #define GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO 1750 ///< Call when collateral only pays off 175% the debt #define GRAPHENE_DEFAULT_MAX_SHORT_SQUEEZE_RATIO 1500 ///< Stop calling when collateral only pays off 150% of the debt ///@} #define GRAPHENE_DEFAULT_MARGIN_PERIOD_SEC (30*60*60*24) #define GRAPHENE_DEFAULT_MIN_WITNESS_COUNT (11) #define GRAPHENE_DEFAULT_MIN_COMMITTEE_MEMBER_COUNT (11) #define GRAPHENE_DEFAULT_MAX_WITNESSES (1001) // SHOULD BE ODD #define GRAPHENE_DEFAULT_MAX_COMMITTEE (1001) // SHOULD BE ODD #define GRAPHENE_DEFAULT_MAX_PROPOSAL_LIFETIME_SEC (60*60*24*7*4) // Four weeks #define GRAPHENE_DEFAULT_COMMITTEE_PROPOSAL_REVIEW_PERIOD_SEC (60*60*24*7*2) // Two weeks #define GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE (20*GRAPHENE_1_PERCENT) #define GRAPHENE_DEFAULT_LIFETIME_REFERRER_PERCENT_OF_FEE (30*GRAPHENE_1_PERCENT) #define GRAPHENE_DEFAULT_CASHBACK_VESTING_PERIOD_SEC (60*60*24*365) ///< 1 year #define GRAPHENE_DEFAULT_CASHBACK_VESTING_THRESHOLD (GRAPHENE_BLOCKCHAIN_PRECISION*int64_t(100)) #define GRAPHENE_DEFAULT_BURN_PERCENT_OF_FEE (20*GRAPHENE_1_PERCENT) #define GRAPHENE_DEFAULT_MAX_ASSERT_OPCODE 1 #define GRAPHENE_DEFAULT_FEE_LIQUIDATION_THRESHOLD GRAPHENE_BLOCKCHAIN_PRECISION * 100; #define GRAPHENE_DEFAULT_ACCOUNTS_PER_FEE_SCALE 1000 #define GRAPHENE_DEFAULT_ACCOUNT_FEE_SCALE_BITSHIFTS 4 #define GRAPHENE_DEFAULT_MAX_BUYBACK_MARKETS 4 #define GRAPHENE_MAX_WORKER_NAME_LENGTH 63 #define GRAPHENE_MAX_URL_LENGTH 127 /** * every second, the fraction of burned core asset which cycles is * GRAPHENE_CORE_ASSET_CYCLE_RATE / (1 << GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS) */ #define GRAPHENE_CORE_ASSET_CYCLE_RATE 17 #define GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS 32 #define GRAPHENE_DEFAULT_WITNESS_PAY_PER_BLOCK (GRAPHENE_BLOCKCHAIN_PRECISION * int64_t( 10) ) #define GRAPHENE_DEFAULT_WITNESS_PAY_VESTING_SECONDS (60*60*24) #define GRAPHENE_DEFAULT_WORKER_BUDGET_PER_DAY (GRAPHENE_BLOCKCHAIN_PRECISION * int64_t(500) * 1000 ) #define GRAPHENE_DEFAULT_MINIMUM_FEEDS 7 #define GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT 4 #define GRAPHENE_RECENTLY_MISSED_COUNT_DECREMENT 3 #define GRAPHENE_CURRENT_DB_VERSION "GXCHAINDB1.3" #define GRAPHENE_IRREVERSIBLE_THRESHOLD (70 * GRAPHENE_1_PERCENT) #define GRAPHENE_MIN_WITNESS_COUNT 21 /** * Reserved Account IDs with special meaning */ ///@{ /// Represents the current committee members, two-week review period #define GRAPHENE_COMMITTEE_ACCOUNT (graphene::chain::account_id_type(0)) /// Represents the current witnesses #define GRAPHENE_WITNESS_ACCOUNT (graphene::chain::account_id_type(1)) /// Represents the current committee members #define GRAPHENE_RELAXED_COMMITTEE_ACCOUNT (graphene::chain::account_id_type(2)) /// Represents the canonical account with NO authority (nobody can access funds in null account) #define GRAPHENE_NULL_ACCOUNT (graphene::chain::account_id_type(3)) /// Represents the canonical account with WILDCARD authority (anybody can access funds in temp account) #define GRAPHENE_TEMP_ACCOUNT (graphene::chain::account_id_type(4)) /// Represents the canonical account for specifying you will vote directly (as opposed to a proxy) #define GRAPHENE_PROXY_TO_SELF_ACCOUNT (graphene::chain::account_id_type(5)) /// Sentinel value used in the scheduler. #define GRAPHENE_NULL_WITNESS (graphene::chain::witness_id_type(0)) ///@} #define GRAPHENE_DATA_TRANSACTION_COMMISSION_ACCOUNT "commission-account" #define GRAPHENE_GXS_ASSET (asset_id_type(1)) #define GRAPHENE_FBA_STEALTH_DESIGNATED_ASSET (asset_id_type(743)) #define GRAPHENE_MAX_NESTED_OBJECTS (200)
52.316456
127
0.74256
InsurChain
33325315971482f45af6013fca9c643bc35df8b2
2,300
cpp
C++
CLRS/BinaryTree/FindLeavesofBinaryTree.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
CLRS/BinaryTree/FindLeavesofBinaryTree.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
CLRS/BinaryTree/FindLeavesofBinaryTree.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
/* Given the root of a binary tree, collect a tree's nodes as if you were doing this: Collect all the leaf nodes. Remove all the leaf nodes. Repeat until the tree is empty. Example 1: Input: root = [1,2,3,4,5] Output: [[4,5,3],[2],[1]] Explanation: [[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned. Example 2: Input: root = [1] Output: [[1]] Constraints: The number of nodes in the tree is in the range [1, 100]. */ // Basically, this requries printing out the nodes in height order, i.e., print height zero (leaves) first.. // So we can construct node to height mapping using dfs and then group all nodes belong to the same height /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<vector<int>> findLeaves(TreeNode* root) { unordered_map<TreeNode*, int> node2height; int height = dfs(root,node2height); vector<vector<int>> res(height+1); for ( auto n : node2height ) { res[n.second].push_back(n.first->val); } return res; } int dfs(TreeNode* node, unordered_map<TreeNode*,int> &node2height) { if ( !node ) return -1; int height = 1 + max(dfs(node->left,node2height),dfs(node->right,node2height)); node2height[node] = height; return height; } }; // we can avoid using the map space by updating the res as it recurses class Solution { public: vector<vector<int>> findLeaves(TreeNode* root) { vector<vector<int>> res; dfs(root,res); return res; } int dfs(TreeNode* node, vector<vector<int>> &res) { if ( !node ) return -1; int h = 1 + max(dfs(node->left,res),dfs(node->right,res)); if ( res.size() < h + 1 ) res.resize(h+1); res[h].push_back(node->val); return h; } };
25.842697
157
0.596087
ComputerProgrammerStorager
3332b46a90a8fc09175490fffedfe4c6501d26c6
1,780
cpp
C++
C++/course-schedule.cpp
black-shadows/LeetCode-Solutions
b1692583f7b710943ffb19b392b8bf64845b5d7a
[ "Fair", "Unlicense" ]
1
2020-04-16T08:38:14.000Z
2020-04-16T08:38:14.000Z
course-schedule.cpp
Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise
f1111b4edd401a3fc47111993bd7250cf4dc76da
[ "MIT" ]
null
null
null
course-schedule.cpp
Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise
f1111b4edd401a3fc47111993bd7250cf4dc76da
[ "MIT" ]
1
2021-12-25T14:48:56.000Z
2021-12-25T14:48:56.000Z
// Time: O(|V| + |E|) // Space: O(|E|) // Topological sort solution. class Solution { public: bool canFinish(int numCourses, vector<vector<int>>& prerequisites) { // Store courses with in-degree zero. queue<int> zeroInDegree; // in-degree, out-degree unordered_map<int, unordered_set<int>> inDegree; unordered_map<int, unordered_set<int>> outDegree; for (int i = 0; i < prerequisites.size(); ++i) { inDegree[prerequisites[i][0]].insert(prerequisites[i][1]); outDegree[prerequisites[i][1]].insert(prerequisites[i][0]); } // Put all the courses with in-degree zero into queue. for(int i = 0; i < numCourses; ++i) { if(inDegree.find(i) == inDegree.end()) { zeroInDegree.push(i); } } // V+E while(!zeroInDegree.empty()) { // Take the course which prerequisites are all taken. int prerequisite = zeroInDegree.front(); zeroInDegree.pop(); for (const auto & course: outDegree[prerequisite]) { // Update info of all the courses with the taken prerequisite. inDegree[course].erase(prerequisite); // If all the prerequisites are taken, add the course to the queue. if (inDegree[course].empty()) { zeroInDegree.push(course); } } // Mark the course as taken. outDegree.erase(prerequisite); } // All of the courses have been taken. if (!outDegree.empty()) { return false; } return true; } };
34.901961
84
0.512921
black-shadows
33349d9f0702121de810cca7b2449ace0e01ffe9
41,624
cpp
C++
Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
19,438
2019-05-20T15:11:11.000Z
2022-03-31T23:31:32.000Z
Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
7,882
2019-05-20T01:03:52.000Z
2022-03-31T23:26:31.000Z
Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
2,721
2019-05-23T00:44:57.000Z
2022-03-31T22:49:34.000Z
/* * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/Debug.h> #include <AK/Function.h> #include <LibJS/AST.h> #include <LibJS/Bytecode/BasicBlock.h> #include <LibJS/Bytecode/Generator.h> #include <LibJS/Bytecode/Interpreter.h> #include <LibJS/Interpreter.h> #include <LibJS/Runtime/AbstractOperations.h> #include <LibJS/Runtime/Array.h> #include <LibJS/Runtime/AsyncFunctionDriverWrapper.h> #include <LibJS/Runtime/ECMAScriptFunctionObject.h> #include <LibJS/Runtime/Error.h> #include <LibJS/Runtime/ExecutionContext.h> #include <LibJS/Runtime/FunctionEnvironment.h> #include <LibJS/Runtime/GeneratorObject.h> #include <LibJS/Runtime/GeneratorObjectPrototype.h> #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/NativeFunction.h> #include <LibJS/Runtime/PromiseConstructor.h> #include <LibJS/Runtime/PromiseReaction.h> #include <LibJS/Runtime/Value.h> namespace JS { ECMAScriptFunctionObject* ECMAScriptFunctionObject::create(GlobalObject& global_object, FlyString name, Statement const& ecmascript_code, Vector<FunctionNode::Parameter> parameters, i32 m_function_length, Environment* parent_scope, PrivateEnvironment* private_scope, FunctionKind kind, bool is_strict, bool might_need_arguments_object, bool contains_direct_call_to_eval, bool is_arrow_function) { Object* prototype = nullptr; switch (kind) { case FunctionKind::Regular: prototype = global_object.function_prototype(); break; case FunctionKind::Generator: prototype = global_object.generator_function_prototype(); break; case FunctionKind::Async: prototype = global_object.async_function_prototype(); break; case FunctionKind::AsyncGenerator: prototype = global_object.async_generator_function_prototype(); break; } return global_object.heap().allocate<ECMAScriptFunctionObject>(global_object, move(name), ecmascript_code, move(parameters), m_function_length, parent_scope, private_scope, *prototype, kind, is_strict, might_need_arguments_object, contains_direct_call_to_eval, is_arrow_function); } ECMAScriptFunctionObject::ECMAScriptFunctionObject(FlyString name, Statement const& ecmascript_code, Vector<FunctionNode::Parameter> formal_parameters, i32 function_length, Environment* parent_scope, PrivateEnvironment* private_scope, Object& prototype, FunctionKind kind, bool strict, bool might_need_arguments_object, bool contains_direct_call_to_eval, bool is_arrow_function) : FunctionObject(prototype) , m_environment(parent_scope) , m_private_environment(private_scope) , m_formal_parameters(move(formal_parameters)) , m_ecmascript_code(ecmascript_code) , m_realm(global_object().associated_realm()) , m_strict(strict) , m_name(move(name)) , m_function_length(function_length) , m_kind(kind) , m_might_need_arguments_object(might_need_arguments_object) , m_contains_direct_call_to_eval(contains_direct_call_to_eval) , m_is_arrow_function(is_arrow_function) { // NOTE: This logic is from OrdinaryFunctionCreate, https://tc39.es/ecma262/#sec-ordinaryfunctioncreate if (m_is_arrow_function) m_this_mode = ThisMode::Lexical; else if (m_strict) m_this_mode = ThisMode::Strict; else m_this_mode = ThisMode::Global; // 15.1.3 Static Semantics: IsSimpleParameterList, https://tc39.es/ecma262/#sec-static-semantics-issimpleparameterlist m_has_simple_parameter_list = all_of(m_formal_parameters, [&](auto& parameter) { if (parameter.is_rest) return false; if (parameter.default_value) return false; if (!parameter.binding.template has<FlyString>()) return false; return true; }); } void ECMAScriptFunctionObject::initialize(GlobalObject& global_object) { auto& vm = this->vm(); Base::initialize(global_object); // Note: The ordering of these properties must be: length, name, prototype which is the order // they are defined in the spec: https://tc39.es/ecma262/#sec-function-instances . // This is observable through something like: https://tc39.es/ecma262/#sec-ordinaryownpropertykeys // which must give the properties in chronological order which in this case is the order they // are defined in the spec. MUST(define_property_or_throw(vm.names.length, { .value = Value(m_function_length), .writable = false, .enumerable = false, .configurable = true })); MUST(define_property_or_throw(vm.names.name, { .value = js_string(vm, m_name.is_null() ? "" : m_name), .writable = false, .enumerable = false, .configurable = true })); if (!m_is_arrow_function) { Object* prototype = nullptr; switch (m_kind) { case FunctionKind::Regular: prototype = vm.heap().allocate<Object>(global_object, *global_object.new_ordinary_function_prototype_object_shape()); MUST(prototype->define_property_or_throw(vm.names.constructor, { .value = this, .writable = true, .enumerable = false, .configurable = true })); break; case FunctionKind::Generator: // prototype is "g1.prototype" in figure-2 (https://tc39.es/ecma262/img/figure-2.png) prototype = global_object.generator_object_prototype(); break; case FunctionKind::Async: break; case FunctionKind::AsyncGenerator: // FIXME: Add the AsyncGeneratorObject and set it as prototype. break; } define_direct_property(vm.names.prototype, prototype, Attribute::Writable); } } ECMAScriptFunctionObject::~ECMAScriptFunctionObject() { } // 10.2.1 [[Call]] ( thisArgument, argumentsList ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-call-thisargument-argumentslist ThrowCompletionOr<Value> ECMAScriptFunctionObject::internal_call(Value this_argument, MarkedValueList arguments_list) { auto& vm = this->vm(); // 1. Let callerContext be the running execution context. // NOTE: No-op, kept by the VM in its execution context stack. ExecutionContext callee_context(heap()); // Non-standard callee_context.arguments.extend(move(arguments_list)); if (auto* interpreter = vm.interpreter_if_exists()) callee_context.current_node = interpreter->current_node(); // 2. Let calleeContext be PrepareForOrdinaryCall(F, undefined). // NOTE: We throw if the end of the native stack is reached, so unlike in the spec this _does_ need an exception check. TRY(prepare_for_ordinary_call(callee_context, nullptr)); // 3. Assert: calleeContext is now the running execution context. VERIFY(&vm.running_execution_context() == &callee_context); // 4. If F.[[IsClassConstructor]] is true, then if (m_is_class_constructor) { // a. Let error be a newly created TypeError object. // b. NOTE: error is created in calleeContext with F's associated Realm Record. auto throw_completion = vm.throw_completion<TypeError>(global_object(), ErrorType::ClassConstructorWithoutNew, m_name); // c. Remove calleeContext from the execution context stack and restore callerContext as the running execution context. vm.pop_execution_context(); // d. Return ThrowCompletion(error). return throw_completion; } // 5. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument). ordinary_call_bind_this(callee_context, this_argument); // 6. Let result be OrdinaryCallEvaluateBody(F, argumentsList). auto result = ordinary_call_evaluate_body(); // 7. Remove calleeContext from the execution context stack and restore callerContext as the running execution context. vm.pop_execution_context(); // 8. If result.[[Type]] is return, return NormalCompletion(result.[[Value]]). if (result.type() == Completion::Type::Return) return result.value(); // 9. ReturnIfAbrupt(result). if (result.is_abrupt()) { // NOTE: I'm not sure if EvaluateBody can return a completion other than Normal, Return, or Throw. // We're far from using completions in the AST anyway; in the meantime assume Throw. VERIFY(result.is_error()); return result; } // 10. Return NormalCompletion(undefined). return js_undefined(); } // 10.2.2 [[Construct]] ( argumentsList, newTarget ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-construct-argumentslist-newtarget ThrowCompletionOr<Object*> ECMAScriptFunctionObject::internal_construct(MarkedValueList arguments_list, FunctionObject& new_target) { auto& vm = this->vm(); auto& global_object = this->global_object(); // 1. Let callerContext be the running execution context. // NOTE: No-op, kept by the VM in its execution context stack. // 2. Let kind be F.[[ConstructorKind]]. auto kind = m_constructor_kind; Object* this_argument = nullptr; // 3. If kind is base, then if (kind == ConstructorKind::Base) { // a. Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%"). this_argument = TRY(ordinary_create_from_constructor<Object>(global_object, new_target, &GlobalObject::object_prototype)); } ExecutionContext callee_context(heap()); // Non-standard callee_context.arguments.extend(move(arguments_list)); if (auto* interpreter = vm.interpreter_if_exists()) callee_context.current_node = interpreter->current_node(); // 4. Let calleeContext be PrepareForOrdinaryCall(F, newTarget). // NOTE: We throw if the end of the native stack is reached, so unlike in the spec this _does_ need an exception check. TRY(prepare_for_ordinary_call(callee_context, &new_target)); // 5. Assert: calleeContext is now the running execution context. VERIFY(&vm.running_execution_context() == &callee_context); // 6. If kind is base, then if (kind == ConstructorKind::Base) { // a. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument). ordinary_call_bind_this(callee_context, this_argument); // b. Let initializeResult be InitializeInstanceElements(thisArgument, F). auto initialize_result = vm.initialize_instance_elements(*this_argument, *this); // c. If initializeResult is an abrupt completion, then if (initialize_result.is_throw_completion()) { // i. Remove calleeContext from the execution context stack and restore callerContext as the running execution context. vm.pop_execution_context(); // ii. Return Completion(initializeResult). return initialize_result.throw_completion(); } } // 7. Let constructorEnv be the LexicalEnvironment of calleeContext. auto* constructor_env = callee_context.lexical_environment; // 8. Let result be OrdinaryCallEvaluateBody(F, argumentsList). auto result = ordinary_call_evaluate_body(); // 9. Remove calleeContext from the execution context stack and restore callerContext as the running execution context. vm.pop_execution_context(); // 10. If result.[[Type]] is return, then if (result.type() == Completion::Type::Return) { // FIXME: This is leftover from untangling the call/construct mess - doesn't belong here in any way, but removing it breaks derived classes. // Likely fixed by making ClassDefinitionEvaluation fully spec compliant. if (kind == ConstructorKind::Derived && result.value().is_object()) { auto prototype = TRY(new_target.get(vm.names.prototype)); if (prototype.is_object()) TRY(result.value().as_object().internal_set_prototype_of(&prototype.as_object())); } // EOF (End of FIXME) // a. If Type(result.[[Value]]) is Object, return NormalCompletion(result.[[Value]]). if (result.value().is_object()) return &result.value().as_object(); // b. If kind is base, return NormalCompletion(thisArgument). if (kind == ConstructorKind::Base) return this_argument; // c. If result.[[Value]] is not undefined, throw a TypeError exception. if (!result.value().is_undefined()) return vm.throw_completion<TypeError>(global_object, ErrorType::DerivedConstructorReturningInvalidValue); } // 11. Else, ReturnIfAbrupt(result). else { // NOTE: I'm not sure if EvaluateBody can return a completion other than Normal, Return, or Throw. // We're far from using completions in the AST anyway; in the meantime assume Throw. VERIFY(result.is_error()); return result; } // 12. Return ? constructorEnv.GetThisBinding(). auto this_binding = TRY(constructor_env->get_this_binding(global_object)); return &this_binding.as_object(); } void ECMAScriptFunctionObject::visit_edges(Visitor& visitor) { Base::visit_edges(visitor); visitor.visit(m_environment); visitor.visit(m_private_environment); visitor.visit(m_realm); visitor.visit(m_home_object); for (auto& field : m_fields) { if (auto* property_name_ptr = field.name.get_pointer<PropertyKey>(); property_name_ptr && property_name_ptr->is_symbol()) visitor.visit(property_name_ptr->as_symbol()); visitor.visit(field.initializer); } } // 10.2.11 FunctionDeclarationInstantiation ( func, argumentsList ), https://tc39.es/ecma262/#sec-functiondeclarationinstantiation ThrowCompletionOr<void> ECMAScriptFunctionObject::function_declaration_instantiation(Interpreter* interpreter) { auto& vm = this->vm(); auto& callee_context = vm.running_execution_context(); // Needed to extract declarations and functions ScopeNode const* scope_body = nullptr; if (is<ScopeNode>(*m_ecmascript_code)) scope_body = static_cast<ScopeNode const*>(m_ecmascript_code.ptr()); bool has_parameter_expressions = false; // FIXME: Maybe compute has duplicates at parse time? (We need to anyway since it's an error in some cases) bool has_duplicates = false; HashTable<FlyString> parameter_names; for (auto& parameter : m_formal_parameters) { if (parameter.default_value) has_parameter_expressions = true; parameter.binding.visit( [&](FlyString const& name) { if (parameter_names.set(name) != AK::HashSetResult::InsertedNewEntry) has_duplicates = true; }, [&](NonnullRefPtr<BindingPattern> const& pattern) { if (pattern->contains_expression()) has_parameter_expressions = true; pattern->for_each_bound_name([&](auto& name) { if (parameter_names.set(name) != AK::HashSetResult::InsertedNewEntry) has_duplicates = true; }); }); } auto arguments_object_needed = m_might_need_arguments_object; if (this_mode() == ThisMode::Lexical) arguments_object_needed = false; if (parameter_names.contains(vm.names.arguments.as_string())) arguments_object_needed = false; HashTable<FlyString> function_names; Vector<FunctionDeclaration const&> functions_to_initialize; if (scope_body) { scope_body->for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) { if (function_names.set(function.name()) == AK::HashSetResult::InsertedNewEntry) functions_to_initialize.append(function); }); auto const& arguments_name = vm.names.arguments.as_string(); if (!has_parameter_expressions && function_names.contains(arguments_name)) arguments_object_needed = false; if (!has_parameter_expressions && arguments_object_needed) { scope_body->for_each_lexically_declared_name([&](auto const& name) { if (name == arguments_name) { arguments_object_needed = false; return IterationDecision::Break; } return IterationDecision::Continue; }); } } else { arguments_object_needed = false; } Environment* environment; if (is_strict_mode() || !has_parameter_expressions) { environment = callee_context.lexical_environment; } else { environment = new_declarative_environment(*callee_context.lexical_environment); VERIFY(callee_context.variable_environment == callee_context.lexical_environment); callee_context.lexical_environment = environment; } for (auto const& parameter_name : parameter_names) { if (MUST(environment->has_binding(parameter_name))) continue; MUST(environment->create_mutable_binding(global_object(), parameter_name, false)); if (has_duplicates) MUST(environment->initialize_binding(global_object(), parameter_name, js_undefined())); } if (arguments_object_needed) { Object* arguments_object; if (is_strict_mode() || !has_simple_parameter_list()) arguments_object = create_unmapped_arguments_object(global_object(), vm.running_execution_context().arguments); else arguments_object = create_mapped_arguments_object(global_object(), *this, formal_parameters(), vm.running_execution_context().arguments, *environment); if (is_strict_mode()) MUST(environment->create_immutable_binding(global_object(), vm.names.arguments.as_string(), false)); else MUST(environment->create_mutable_binding(global_object(), vm.names.arguments.as_string(), false)); MUST(environment->initialize_binding(global_object(), vm.names.arguments.as_string(), arguments_object)); parameter_names.set(vm.names.arguments.as_string()); } // We now treat parameterBindings as parameterNames. // The spec makes an iterator here to do IteratorBindingInitialization but we just do it manually auto& execution_context_arguments = vm.running_execution_context().arguments; for (size_t i = 0; i < m_formal_parameters.size(); ++i) { auto& parameter = m_formal_parameters[i]; TRY(parameter.binding.visit( [&](auto const& param) -> ThrowCompletionOr<void> { Value argument_value; if (parameter.is_rest) { auto* array = MUST(Array::create(global_object(), 0)); for (size_t rest_index = i; rest_index < execution_context_arguments.size(); ++rest_index) array->indexed_properties().append(execution_context_arguments[rest_index]); argument_value = array; } else if (i < execution_context_arguments.size() && !execution_context_arguments[i].is_undefined()) { argument_value = execution_context_arguments[i]; } else if (parameter.default_value) { // FIXME: Support default arguments in the bytecode world! if (interpreter) argument_value = parameter.default_value->execute(*interpreter, global_object()); if (auto* exception = vm.exception()) return throw_completion(exception->value()); } else { argument_value = js_undefined(); } Environment* used_environment = has_duplicates ? nullptr : environment; if constexpr (IsSame<FlyString const&, decltype(param)>) { Reference reference = vm.resolve_binding(param, used_environment); if (auto* exception = vm.exception()) return throw_completion(exception->value()); // Here the difference from hasDuplicates is important if (has_duplicates) return reference.put_value(global_object(), argument_value); else return reference.initialize_referenced_binding(global_object(), argument_value); } else if (IsSame<NonnullRefPtr<BindingPattern> const&, decltype(param)>) { // Here the difference from hasDuplicates is important return vm.binding_initialization(param, argument_value, used_environment, global_object()); } })); } Environment* var_environment; HashTable<FlyString> instantiated_var_names; if (scope_body) instantiated_var_names.ensure_capacity(scope_body->var_declaration_count()); if (!has_parameter_expressions) { if (scope_body) { scope_body->for_each_var_declared_name([&](auto const& name) { if (!parameter_names.contains(name) && instantiated_var_names.set(name) == AK::HashSetResult::InsertedNewEntry) { MUST(environment->create_mutable_binding(global_object(), name, false)); MUST(environment->initialize_binding(global_object(), name, js_undefined())); } }); } var_environment = environment; } else { var_environment = new_declarative_environment(*environment); callee_context.variable_environment = var_environment; if (scope_body) { scope_body->for_each_var_declared_name([&](auto const& name) { if (instantiated_var_names.set(name) != AK::HashSetResult::InsertedNewEntry) return IterationDecision::Continue; MUST(var_environment->create_mutable_binding(global_object(), name, false)); Value initial_value; if (!parameter_names.contains(name) || function_names.contains(name)) initial_value = js_undefined(); else initial_value = MUST(environment->get_binding_value(global_object(), name, false)); MUST(var_environment->initialize_binding(global_object(), name, initial_value)); return IterationDecision::Continue; }); } } // B.3.2.1 Changes to FunctionDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation if (!m_strict && scope_body) { scope_body->for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) { auto& function_name = function_declaration.name(); if (parameter_names.contains(function_name)) return IterationDecision::Continue; // The spec says 'initializedBindings' here but that does not exist and it then adds it to 'instantiatedVarNames' so it probably means 'instantiatedVarNames'. if (!instantiated_var_names.contains(function_name) && function_name != vm.names.arguments.as_string()) { MUST(var_environment->create_mutable_binding(global_object(), function_name, false)); MUST(var_environment->initialize_binding(global_object(), function_name, js_undefined())); instantiated_var_names.set(function_name); } function_declaration.set_should_do_additional_annexB_steps(); return IterationDecision::Continue; }); } Environment* lex_environment; // 30. If strict is false, then if (!is_strict_mode()) { // Optimization: We avoid creating empty top-level declarative environments in non-strict mode, if both of these conditions are true: // 1. there is no direct call to eval() within this function // 2. there are no lexical declarations that would go into the environment bool can_elide_declarative_environment = !m_contains_direct_call_to_eval && (!scope_body || !scope_body->has_lexical_declarations()); if (can_elide_declarative_environment) { lex_environment = var_environment; } else { // a. Let lexEnv be NewDeclarativeEnvironment(varEnv). // b. NOTE: Non-strict functions use a separate Environment Record for top-level lexical declarations so that a direct eval // can determine whether any var scoped declarations introduced by the eval code conflict with pre-existing top-level // lexically scoped declarations. This is not needed for strict functions because a strict direct eval always places // all declarations into a new Environment Record. lex_environment = new_declarative_environment(*var_environment); } } else { // 31. Else, let lexEnv be varEnv. lex_environment = var_environment; } // 32. Set the LexicalEnvironment of calleeContext to lexEnv. callee_context.lexical_environment = lex_environment; if (!scope_body) return {}; scope_body->for_each_lexically_scoped_declaration([&](Declaration const& declaration) { declaration.for_each_bound_name([&](auto const& name) { if (declaration.is_constant_declaration()) MUST(lex_environment->create_immutable_binding(global_object(), name, true)); else MUST(lex_environment->create_mutable_binding(global_object(), name, false)); return IterationDecision::Continue; }); }); VERIFY(!vm.exception()); auto* private_environment = callee_context.private_environment; for (auto& declaration : functions_to_initialize) { auto* function = ECMAScriptFunctionObject::create(global_object(), declaration.name(), declaration.body(), declaration.parameters(), declaration.function_length(), lex_environment, private_environment, declaration.kind(), declaration.is_strict_mode(), declaration.might_need_arguments_object(), declaration.contains_direct_call_to_eval()); MUST(var_environment->set_mutable_binding(global_object(), declaration.name(), function, false)); } return {}; } // 10.2.1.1 PrepareForOrdinaryCall ( F, newTarget ), https://tc39.es/ecma262/#sec-prepareforordinarycall ThrowCompletionOr<void> ECMAScriptFunctionObject::prepare_for_ordinary_call(ExecutionContext& callee_context, Object* new_target) { auto& vm = this->vm(); // Non-standard callee_context.is_strict_mode = m_strict; // 1. Let callerContext be the running execution context. // 2. Let calleeContext be a new ECMAScript code execution context. // NOTE: In the specification, PrepareForOrdinaryCall "returns" a new callee execution context. // To avoid heap allocations, we put our ExecutionContext objects on the C++ stack instead. // Whoever calls us should put an ExecutionContext on their stack and pass that as the `callee_context`. // 3. Set the Function of calleeContext to F. callee_context.function = this; callee_context.function_name = m_name; // 4. Let calleeRealm be F.[[Realm]]. auto* callee_realm = m_realm; // NOTE: This non-standard fallback is needed until we can guarantee that literally // every function has a realm - especially in LibWeb that's sometimes not the case // when a function is created while no JS is running, as we currently need to rely on // that (:acid2:, I know - see set_event_handler_attribute() for an example). // If there's no 'current realm' either, we can't continue and crash. if (!callee_realm) callee_realm = vm.current_realm(); VERIFY(callee_realm); // 5. Set the Realm of calleeContext to calleeRealm. callee_context.realm = callee_realm; // 6. Set the ScriptOrModule of calleeContext to F.[[ScriptOrModule]]. // FIXME: Our execution context struct currently does not track this item. // 7. Let localEnv be NewFunctionEnvironment(F, newTarget). auto* local_environment = new_function_environment(*this, new_target); // 8. Set the LexicalEnvironment of calleeContext to localEnv. callee_context.lexical_environment = local_environment; // 9. Set the VariableEnvironment of calleeContext to localEnv. callee_context.variable_environment = local_environment; // 10. Set the PrivateEnvironment of calleeContext to F.[[PrivateEnvironment]]. callee_context.private_environment = m_private_environment; // 11. If callerContext is not already suspended, suspend callerContext. // FIXME: We don't have this concept yet. // 12. Push calleeContext onto the execution context stack; calleeContext is now the running execution context. TRY(vm.push_execution_context(callee_context, global_object())); // 13. NOTE: Any exception objects produced after this point are associated with calleeRealm. // 14. Return calleeContext. (See NOTE above about how contexts are allocated on the C++ stack.) return {}; } // 10.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument ), https://tc39.es/ecma262/#sec-ordinarycallbindthis void ECMAScriptFunctionObject::ordinary_call_bind_this(ExecutionContext& callee_context, Value this_argument) { auto& vm = this->vm(); // 1. Let thisMode be F.[[ThisMode]]. auto this_mode = m_this_mode; // If thisMode is lexical, return NormalCompletion(undefined). if (this_mode == ThisMode::Lexical) return; // 3. Let calleeRealm be F.[[Realm]]. auto* callee_realm = m_realm; // NOTE: This non-standard fallback is needed until we can guarantee that literally // every function has a realm - especially in LibWeb that's sometimes not the case // when a function is created while no JS is running, as we currently need to rely on // that (:acid2:, I know - see set_event_handler_attribute() for an example). // If there's no 'current realm' either, we can't continue and crash. if (!callee_realm) callee_realm = vm.current_realm(); VERIFY(callee_realm); // 4. Let localEnv be the LexicalEnvironment of calleeContext. auto* local_env = callee_context.lexical_environment; Value this_value; // 5. If thisMode is strict, let thisValue be thisArgument. if (this_mode == ThisMode::Strict) { this_value = this_argument; } // 6. Else, else { // a. If thisArgument is undefined or null, then if (this_argument.is_nullish()) { // i. Let globalEnv be calleeRealm.[[GlobalEnv]]. // ii. Assert: globalEnv is a global Environment Record. auto& global_env = callee_realm->global_environment(); // iii. Let thisValue be globalEnv.[[GlobalThisValue]]. this_value = &global_env.global_this_value(); } // b. Else, else { // i. Let thisValue be ! ToObject(thisArgument). this_value = MUST(this_argument.to_object(global_object())); // ii. NOTE: ToObject produces wrapper objects using calleeRealm. // FIXME: It currently doesn't, as we pass the function's global object. } } // 7. Assert: localEnv is a function Environment Record. // 8. Assert: The next step never returns an abrupt completion because localEnv.[[ThisBindingStatus]] is not initialized. // 9. Return localEnv.BindThisValue(thisValue). MUST(verify_cast<FunctionEnvironment>(local_env)->bind_this_value(global_object(), this_value)); } // 27.7.5.1 AsyncFunctionStart ( promiseCapability, asyncFunctionBody ), https://tc39.es/ecma262/#sec-async-functions-abstract-operations-async-function-start void ECMAScriptFunctionObject::async_function_start(PromiseCapability const& promise_capability) { auto& vm = this->vm(); // 1. Let runningContext be the running execution context. auto& running_context = vm.running_execution_context(); // 2. Let asyncContext be a copy of runningContext. auto async_context = running_context.copy(); // 3. NOTE: Copying the execution state is required for AsyncBlockStart to resume its execution. It is ill-defined to resume a currently executing context. // 4. Perform ! AsyncBlockStart(promiseCapability, asyncFunctionBody, asyncContext). async_block_start(promise_capability, async_context); } // 27.7.5.2 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext ), https://tc39.es/ecma262/#sec-asyncblockstart void ECMAScriptFunctionObject::async_block_start(PromiseCapability const& promise_capability, ExecutionContext& async_context) { auto& vm = this->vm(); // 1. Assert: promiseCapability is a PromiseCapability Record. // 2. Let runningContext be the running execution context. auto& running_context = vm.running_execution_context(); // 3. Set the code evaluation state of asyncContext such that when evaluation is resumed for that execution context the following steps will be performed: auto* execution_steps = NativeFunction::create(global_object(), "", [async_body = m_ecmascript_code, &promise_capability](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> { // a. Let result be the result of evaluating asyncBody. auto result = async_body->execute(vm.interpreter(), global_object); // b. Assert: If we return here, the async function either threw an exception or performed an implicit or explicit return; all awaiting is done. // c. Remove asyncContext from the execution context stack and restore the execution context that is at the top of the execution context stack as the running execution context. vm.pop_execution_context(); // NOTE: Running the AST node should eventually return a completion. // Until it does, we assume "return" and include the undefined fallback from the call site. // d. If result.[[Type]] is normal, then if (false) { // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « undefined »). MUST(call(global_object, promise_capability.resolve, js_undefined(), js_undefined())); } // e. Else if result.[[Type]] is return, then else if (!vm.exception()) { // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « result.[[Value]] »). MUST(call(global_object, promise_capability.resolve, js_undefined(), result.value_or(js_undefined()))); } // f. Else, else { // i. Assert: result.[[Type]] is throw. // ii. Perform ! Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »). auto reason = vm.exception()->value(); vm.clear_exception(); vm.stop_unwind(); MUST(call(global_object, promise_capability.reject, js_undefined(), reason)); } // g. Return. return js_undefined(); }); // 4. Push asyncContext onto the execution context stack; asyncContext is now the running execution context. auto push_result = vm.push_execution_context(async_context, global_object()); if (push_result.is_error()) return; // 5. Resume the suspended evaluation of asyncContext. Let result be the value returned by the resumed computation. auto result = vm.call(*execution_steps, async_context.this_value.is_empty() ? js_undefined() : async_context.this_value); // 6. Assert: When we return here, asyncContext has already been removed from the execution context stack and runningContext is the currently running execution context. VERIFY(&vm.running_execution_context() == &running_context); // 7. Assert: result is a normal completion with a value of undefined. The possible sources of completion values are Await or, if the async function doesn't await anything, step 3.g above. VERIFY(result.has_value() && result.value().is_undefined()); // 8. Return. } // 10.2.1.4 OrdinaryCallEvaluateBody ( F, argumentsList ), https://tc39.es/ecma262/#sec-ordinarycallevaluatebody Completion ECMAScriptFunctionObject::ordinary_call_evaluate_body() { auto& vm = this->vm(); auto* bytecode_interpreter = Bytecode::Interpreter::current(); if (m_kind == FunctionKind::AsyncGenerator) return vm.throw_completion<InternalError>(global_object(), ErrorType::NotImplemented, "Async Generator function execution"); if (bytecode_interpreter) { // FIXME: pass something to evaluate default arguments with TRY(function_declaration_instantiation(nullptr)); if (!m_bytecode_executable.has_value()) { m_bytecode_executable = Bytecode::Generator::generate(m_ecmascript_code, m_kind); m_bytecode_executable->name = m_name; auto& passes = JS::Bytecode::Interpreter::optimization_pipeline(); passes.perform(*m_bytecode_executable); if constexpr (JS_BYTECODE_DEBUG) { dbgln("Optimisation passes took {}us", passes.elapsed()); dbgln("Compiled Bytecode::Block for function '{}':", m_name); } if (JS::Bytecode::g_dump_bytecode) m_bytecode_executable->dump(); } auto result_and_frame = bytecode_interpreter->run_and_return_frame(*m_bytecode_executable, nullptr); if (auto* exception = vm.exception()) return throw_completion(exception->value()); VERIFY(result_and_frame.frame != nullptr); if (result_and_frame.value.is_error()) { vm.throw_exception(bytecode_interpreter->global_object(), result_and_frame.value.release_error().value()); return throw_completion(vm.exception()->value()); } auto result = result_and_frame.value.release_value(); // NOTE: Running the bytecode should eventually return a completion. // Until it does, we assume "return" and include the undefined fallback from the call site. if (m_kind == FunctionKind::Regular) return { Completion::Type::Return, result.value_or(js_undefined()), {} }; auto generator_object = TRY(GeneratorObject::create(global_object(), result, this, vm.running_execution_context().copy(), move(*result_and_frame.frame))); // NOTE: Async functions are entirely transformed to generator functions, and wrapped in a custom driver that returns a promise // See AwaitExpression::generate_bytecode() for the transformation. if (m_kind == FunctionKind::Async) return { Completion::Type::Return, TRY(AsyncFunctionDriverWrapper::create(global_object(), generator_object)), {} }; VERIFY(m_kind == FunctionKind::Generator); return { Completion::Type::Return, generator_object, {} }; } else { if (m_kind == FunctionKind::Generator) return vm.throw_completion<InternalError>(global_object(), ErrorType::NotImplemented, "Generator function execution in AST interpreter"); OwnPtr<Interpreter> local_interpreter; Interpreter* ast_interpreter = vm.interpreter_if_exists(); if (!ast_interpreter) { local_interpreter = Interpreter::create_with_existing_realm(*realm()); ast_interpreter = local_interpreter.ptr(); } VM::InterpreterExecutionScope scope(*ast_interpreter); if (m_kind == FunctionKind::Regular) { TRY(function_declaration_instantiation(ast_interpreter)); auto result = m_ecmascript_code->execute(*ast_interpreter, global_object()); if (auto* exception = vm.exception()) return throw_completion(exception->value()); // NOTE: Running the AST node should eventually return a completion. // Until it does, we assume "return" and include the undefined fallback from the call site. return { Completion::Type::Return, result.value_or(js_undefined()), {} }; } else if (m_kind == FunctionKind::Async) { // 1. Let promiseCapability be ! NewPromiseCapability(%Promise%). auto promise_capability = MUST(new_promise_capability(global_object(), global_object().promise_constructor())); // 2. Let declResult be FunctionDeclarationInstantiation(functionObject, argumentsList). auto declaration_result = function_declaration_instantiation(ast_interpreter); // 3. If declResult is not an abrupt completion, then if (!declaration_result.is_throw_completion() || !declaration_result.throw_completion().is_abrupt()) { // a. Perform ! AsyncFunctionStart(promiseCapability, FunctionBody). async_function_start(promise_capability); } // 4. Else, else { // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « declResult.[[Value]] »). MUST(call(global_object(), promise_capability.reject, js_undefined(), declaration_result.throw_completion().value())); } // 5. Return Completion { [[Type]]: return, [[Value]]: promiseCapability.[[Promise]], [[Target]]: empty }. return Completion { Completion::Type::Return, promise_capability.promise, {} }; } } VERIFY_NOT_REACHED(); } void ECMAScriptFunctionObject::set_name(const FlyString& name) { VERIFY(!name.is_null()); auto& vm = this->vm(); m_name = name; auto success = MUST(define_property_or_throw(vm.names.name, { .value = js_string(vm, m_name), .writable = false, .enumerable = false, .configurable = true })); VERIFY(success); } void ECMAScriptFunctionObject::add_field(ClassElement::ClassElementName property_key, ECMAScriptFunctionObject* initializer) { m_fields.empend(property_key, initializer); } }
48.120231
394
0.686359
r00ster91
3336a95d4e3b353008216a696220379a64c5294a
1,566
cpp
C++
src/kits/mail/NodeMessage.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
3
2018-05-21T15:32:32.000Z
2019-03-21T13:34:55.000Z
src/kits/mail/NodeMessage.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/kits/mail/NodeMessage.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
null
null
null
#include <NodeMessage.h> #include <kits/StorageKit.h> #include <fs_attr.h> #include <stdlib.h> /* These functions gives a nice BMessage interface to node attributes, by letting you transfer attributes to and from BMessages. It makes it so you can use all the convenient Find...() and Add...() functions provided by BMessage for attributes too. You use it as follows: BMessage m; BNode n(path); if (reading) { n>>m; printf("woohoo=%s\n",m.FindString("woohoo")) } else { m.AddString("woohoo","it's howdy doody time"); n<<m; } If there is more than one data item with a given name, the first item is the one writen to the node. */ _EXPORT BNode& operator<<(BNode& n, const BMessage& m) { #if defined(HAIKU_TARGET_PLATFORM_DANO) const #endif char *name; type_code type; ssize_t bytes; const void *data; for (int32 i = 0; m.GetInfo(B_ANY_TYPE, i, &name, &type) == 0; i++) { m.FindData (name,type,0,&data,&bytes); n.WriteAttr(name,type,0, data, bytes); } return n; } _EXPORT BNode& operator>>(BNode& n, BMessage& m) { char name[B_ATTR_NAME_LENGTH]; attr_info info; char *buf = NULL; n.RewindAttrs(); while (n.GetNextAttrName(name) == B_OK) { if (n.GetAttrInfo(name,&info) != B_OK) continue; // resize the buffer if (char *newBuffer = (char*)realloc(buf, info.size)) buf = newBuffer; else continue; info.size=n.ReadAttr(name,info.type,0,buf,info.size); if (info.size >= 0) m.AddData(name,info.type,buf,info.size); } n.RewindAttrs(); free(buf); return n; }
23.373134
72
0.66092
stasinek
33373e6855e083d26b7765a96b276a1166653ebb
6,325
cpp
C++
src/Evolution/Systems/RelativisticEuler/Valencia/PrimitiveFromConservative.cpp
trami18/spectre
6b1f6497bf2e26d1474bfadf143b3321942c40b4
[ "MIT" ]
2
2021-04-11T04:07:42.000Z
2021-04-11T05:07:54.000Z
src/Evolution/Systems/RelativisticEuler/Valencia/PrimitiveFromConservative.cpp
trami18/spectre
6b1f6497bf2e26d1474bfadf143b3321942c40b4
[ "MIT" ]
null
null
null
src/Evolution/Systems/RelativisticEuler/Valencia/PrimitiveFromConservative.cpp
trami18/spectre
6b1f6497bf2e26d1474bfadf143b3321942c40b4
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #include "Evolution/Systems/RelativisticEuler/Valencia/PrimitiveFromConservative.hpp" #include <cmath> #include <limits> #include "DataStructures/DataVector.hpp" // IWYU pragma: keep #include "DataStructures/Tensor/EagerMath/DotProduct.hpp" #include "DataStructures/Tensor/Tensor.hpp" #include "NumericalAlgorithms/RootFinding/TOMS748.hpp" #include "PointwiseFunctions/GeneralRelativity/IndexManipulation.hpp" #include "Utilities/ConstantExpressions.hpp" #include "Utilities/ContainerHelpers.hpp" #include "Utilities/GenerateInstantiations.hpp" #include "Utilities/Gsl.hpp" // IWYU pragma: no_forward_declare EquationsOfState::EquationOfState namespace RelativisticEuler::Valencia { namespace { template <size_t ThermodynamicDim> class FunctionOfZ { public: FunctionOfZ(const Scalar<DataVector>& tilde_d, const Scalar<DataVector>& tilde_tau, const Scalar<DataVector>& tilde_s_magnitude, const Scalar<DataVector>& sqrt_det_spatial_metric, const EquationsOfState::EquationOfState<true, ThermodynamicDim>& equation_of_state) noexcept : tilde_d_(tilde_d), tilde_tau_(tilde_tau), tilde_s_magnitude_(tilde_s_magnitude), sqrt_det_spatial_metric_(sqrt_det_spatial_metric), equation_of_state_(equation_of_state) {} double operator()(const double z, const size_t i = 0) const noexcept { const double r = get_element(get(tilde_s_magnitude_), i) / get_element(get(tilde_d_), i); const double q = get_element(get(tilde_tau_), i) / get_element(get(tilde_d_), i); const double W = sqrt(1.0 + square(z)); const double rho = get_element(get(tilde_d_), i) / (W * get_element(get(sqrt_det_spatial_metric_), i)); // Note z^2/(1+W) is numerically more accurate than W-1 for small // velocities. const double epsilon = W * q - z * r + square(z) / (1.0 + W); const double e = rho * (1.0 + epsilon); double pressure = std::numeric_limits<double>::signaling_NaN(); if constexpr (ThermodynamicDim == 1) { pressure = get(equation_of_state_.pressure_from_density(Scalar<double>(rho))); } else if constexpr (ThermodynamicDim == 2) { pressure = get(equation_of_state_.pressure_from_density_and_energy( Scalar<double>(rho), Scalar<double>(epsilon))); } const double a = pressure / e; const double h = (1.0 + epsilon) * (1.0 + a); return z - r / h; } private: const Scalar<DataVector>& tilde_d_; const Scalar<DataVector>& tilde_tau_; const Scalar<DataVector>& tilde_s_magnitude_; const Scalar<DataVector>& sqrt_det_spatial_metric_; const EquationsOfState::EquationOfState<true, ThermodynamicDim>& equation_of_state_; }; } // namespace template <size_t ThermodynamicDim, size_t Dim> void PrimitiveFromConservative<ThermodynamicDim, Dim>::apply( const gsl::not_null<Scalar<DataVector>*> rest_mass_density, const gsl::not_null<Scalar<DataVector>*> specific_internal_energy, const gsl::not_null<Scalar<DataVector>*> lorentz_factor, const gsl::not_null<Scalar<DataVector>*> specific_enthalpy, const gsl::not_null<Scalar<DataVector>*> pressure, const gsl::not_null<tnsr::I<DataVector, Dim, Frame::Inertial>*> spatial_velocity, const Scalar<DataVector>& tilde_d, const Scalar<DataVector>& tilde_tau, const tnsr::i<DataVector, Dim, Frame::Inertial>& tilde_s, const tnsr::II<DataVector, Dim, Frame::Inertial>& inv_spatial_metric, const Scalar<DataVector>& sqrt_det_spatial_metric, const EquationsOfState::EquationOfState<true, ThermodynamicDim>& equation_of_state) noexcept { const auto tilde_s_M = raise_or_lower_index(tilde_s, inv_spatial_metric); const Scalar<DataVector> tilde_s_magnitude{ sqrt(get(dot_product(tilde_s, tilde_s_M)))}; // find z via root find // k not const to save allocation later DataVector k = get(tilde_s_magnitude) / (get(tilde_tau) + get(tilde_d)); const DataVector lower_bound = 0.5 * k / sqrt(1.0 - 0.25 * square(k)); const DataVector upper_bound = k / sqrt(1.0 - square(k)); const auto f_of_z = FunctionOfZ<ThermodynamicDim>{tilde_d, tilde_tau, tilde_s_magnitude, sqrt_det_spatial_metric, equation_of_state}; DataVector z; try { // NOLINTNEXTLINE(clang-analyzer-core) z = RootFinder::toms748(f_of_z, lower_bound, upper_bound, 10.0 * std::numeric_limits<double>::epsilon(), 10.0 * std::numeric_limits<double>::epsilon(), 100); } catch (std::exception& exception) { ERROR( "Failed to find the intermediate variable z with TOMS748 root finder " "while computing the primitive variables from the conserved variables. " "Got exception message:\n" << exception.what()); } get(*lorentz_factor) = sqrt(1.0 + square(z)); get(*rest_mass_density) = get(tilde_d) / (get(*lorentz_factor) * get(sqrt_det_spatial_metric)); get(*specific_internal_energy) = (get(*lorentz_factor) * get(tilde_tau) - z * get(tilde_s_magnitude)) / get(tilde_d) + square(z) / (1.0 + get(*lorentz_factor)); if constexpr (ThermodynamicDim == 1) { *pressure = equation_of_state.pressure_from_density(*rest_mass_density); } else if constexpr (ThermodynamicDim == 2) { *pressure = equation_of_state.pressure_from_density_and_energy( *rest_mass_density, *specific_internal_energy); } get(*specific_enthalpy) = 1.0 + get(*specific_internal_energy) + get(*pressure) / get(*rest_mass_density); // reuse k as a temporary DataVector denominator = std::move(k); denominator = get(tilde_d) * get(*lorentz_factor) * get(*specific_enthalpy); for (size_t d = 0; d < Dim; ++d) { spatial_velocity->get(d) = tilde_s_M.get(d) / denominator; } } #define DIM(data) BOOST_PP_TUPLE_ELEM(0, data) #define THERMODIM(data) BOOST_PP_TUPLE_ELEM(1, data) #define INSTANTIATION(_, data) \ template class PrimitiveFromConservative<THERMODIM(data), DIM(data)>; GENERATE_INSTANTIATIONS(INSTANTIATION, (1, 2, 3), (1, 2)) #undef INSTANTIATION #undef THERMODIM #undef DIM } // namespace RelativisticEuler::Valencia
40.544872
85
0.700553
trami18
33380e066506e538883f055b0d8f02de8251b3c7
3,277
hpp
C++
TstarMassReco/interface/RecoUtils.hpp
NTUHEP-Tstar/TstarAnalysis
d3bcdf6f0fd19b9a34bbacb1052143856917bea7
[ "MIT" ]
null
null
null
TstarMassReco/interface/RecoUtils.hpp
NTUHEP-Tstar/TstarAnalysis
d3bcdf6f0fd19b9a34bbacb1052143856917bea7
[ "MIT" ]
null
null
null
TstarMassReco/interface/RecoUtils.hpp
NTUHEP-Tstar/TstarAnalysis
d3bcdf6f0fd19b9a34bbacb1052143856917bea7
[ "MIT" ]
null
null
null
/******************************************************************************* * * Filename : RecoUtils.hh * Description : Utility functions for converting CMSSW object to fitting results * Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ] * *******************************************************************************/ #ifndef TSTARANALYSIS_TSTARMASSRECO_RECOUTILS_HPP #define TSTARANALYSIS_TSTARMASSRECO_RECOUTILS_HPP #include "CLHEP/Vector/LorentzVector.h" #include "DataFormats/PatCandidates/interface/Electron.h" #include "DataFormats/PatCandidates/interface/Jet.h" #include "DataFormats/PatCandidates/interface/MET.h" #include "DataFormats/PatCandidates/interface/Muon.h" #include "TLorentzVector.h" #include "TstarAnalysis/RootFormat/interface/FitParticle.hpp" #include <vector> /******************************************************************************* * Helper functions to extract Four momentum from non PAT objects *******************************************************************************/ extern TLorentzVector ConvertToRoot( const reco::Candidate& x ); extern TLorentzVector ConvertToRoot( const CLHEP::HepLorentzVector& x ); /******************************************************************************* * Helper function for getting JES scale of MET from a list of Jets * * -- Dumbed down version of algorithm (not complete!) * perform vector sum of jets for central * value, scaled up and scaled down four momentums, the error is then deprived * from the ration between the sum pt * *******************************************************************************/ void GetJESMET( const std::vector<const pat::Jet*>&, double& scaleup, double& scaledown ); /******************************************************************************* * Translations functions, the creating of the storage fit particles from * original pat objects. * * ** MakeResultJet - (int) to signify jet type in topology from fitting results * * ** MakeResultMET * - TLorentzVector for fitted four momentum of neutrino. * - doubles for effects of Jet energy corrections. * *******************************************************************************/ extern FitParticle MakeResultJet( const pat::Jet*, int ); extern FitParticle MakeResultMET( const pat::MET*, const TLorentzVector&, const double scaleup, const double scaledown ); extern FitParticle MakeResultMuon( const pat::Muon* ); extern FitParticle MakeResultElectron( const pat::Electron* ); /******************************************************************************* * Decay chain crawling function for hihg level control flow *******************************************************************************/ extern tstar::Particle_Label GetJetType( const reco::GenParticle* ); extern tstar::Particle_Label GetLeptonType( const reco::GenParticle* ); extern bool FromLeptonicTop( const reco::Candidate* ); extern bool FromHadronicTop( const reco::Candidate* ); extern bool FromLeptonicW( const reco::Candidate* ); extern bool FromHadronicW( const reco::Candidate* ); extern bool FromLeptonicTstar( const reco::Candidate* ); extern bool FromHadronicTstar( const reco::Candidate* ); #endif/* end of include guard: __RECO_UTILS_HH__ */
47.492754
121
0.577968
NTUHEP-Tstar
333d71890bba236bfb2410f0a18453cdae81f702
172
cpp
C++
sources/classes/c_baseclasses.cpp
lukis101/ArcanistsScribblings
f05f83314066c12fcf64405ef45e538294fec296
[ "MIT" ]
5
2018-01-31T16:50:39.000Z
2018-09-23T19:18:11.000Z
sources/classes/c_baseclasses.cpp
lukis101/ArcanistsScribblings
f05f83314066c12fcf64405ef45e538294fec296
[ "MIT" ]
null
null
null
sources/classes/c_baseclasses.cpp
lukis101/ArcanistsScribblings
f05f83314066c12fcf64405ef45e538294fec296
[ "MIT" ]
null
null
null
//#include "SDL/SDL.h" //#include <iostream> //#include "classes/c_baseclasses.h" //#include "functions/logic.h" //#include "globals.h" //#include "classes/c_baseclass.h"
21.5
36
0.697674
lukis101
333dc29672c97df278d65b1dffbbea7797dd0f20
1,293
hpp
C++
http_parser/utils/find.hpp
zerhud/std_http_utils
0c37eecc242a93a7bf7d2d7ea8f0eb9f51d77293
[ "MIT" ]
null
null
null
http_parser/utils/find.hpp
zerhud/std_http_utils
0c37eecc242a93a7bf7d2d7ea8f0eb9f51d77293
[ "MIT" ]
null
null
null
http_parser/utils/find.hpp
zerhud/std_http_utils
0c37eecc242a93a7bf7d2d7ea8f0eb9f51d77293
[ "MIT" ]
null
null
null
#pragma once /************************************************************************* * Copyright © 2022 Hudyaev Alexy <hudyaev.alexy@gmail.com> * This file is part of http_parser. * Distributed under the MIT License. * See accompanying file LICENSE (at the root of this repository) *************************************************************************/ #include <cstdint> namespace http_parser { std::size_t find(std::uint64_t* data, std::size_t size, std::uint8_t symbol) { std::uint64_t mask1 = symbol; std::uint64_t mask2 = mask1 << 8; std::uint64_t mask3 = mask2 << 8; std::uint64_t mask4 = mask3 << 8; std::uint64_t mask5 = mask4 << 8; std::uint64_t mask6 = mask5 << 8; std::uint64_t mask7 = mask6 << 8; std::uint64_t mask8 = mask7 << 8; std::size_t dsize = size/8; if(size%8!=0) ++dsize; for(std::size_t i=0;i<dsize;++i) { if((data[i] & mask1) == mask1) return (i*8); if((data[i] & mask2) == mask2) return (i*8)+1; if((data[i] & mask3) == mask3) return (i*8)+2; if((data[i] & mask4) == mask4) return (i*8)+3; if((data[i] & mask5) == mask5) return (i*8)+4; if((data[i] & mask6) == mask6) return (i*8)+5; if((data[i] & mask7) == mask7) return (i*8)+6; if((data[i] & mask8) == mask8) return (i*8)+7; } return size; } } // namespace http_parser
32.325
76
0.556071
zerhud
333e8c510602b4572f7fb7a665581c53fcf1d206
2,555
hpp
C++
modules/boost/simd/base/include/boost/simd/boolean/functions/if_one_else_zero.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/include/boost/simd/boolean/functions/if_one_else_zero.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/include/boost/simd/boolean/functions/if_one_else_zero.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_BOOLEAN_FUNCTIONS_IF_ONE_ELSE_ZERO_HPP_INCLUDED #define BOOST_SIMD_BOOLEAN_FUNCTIONS_IF_ONE_ELSE_ZERO_HPP_INCLUDED #include <boost/simd/include/functor.hpp> #include <boost/dispatch/include/functor.hpp> namespace boost { namespace simd { namespace tag { /*! @brief if_one_else_zero generic tag Represents the if_one_else_zero function in generic contexts. @par Models: Hierarchy **/ struct if_one_else_zero_ : ext::elementwise_<if_one_else_zero_> { /// @brief Parent hierarchy typedef ext::elementwise_<if_one_else_zero_> parent; template<class... Args> static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args) BOOST_AUTO_DECLTYPE_BODY( dispatching_if_one_else_zero_( ext::adl_helper(), static_cast<Args&&>(args)... ) ) }; } namespace ext { template<class Site, class... Ts> BOOST_FORCEINLINE generic_dispatcher<tag::if_one_else_zero_, Site> dispatching_if_one_else_zero_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...) { return generic_dispatcher<tag::if_one_else_zero_, Site>(); } template<class... Args> struct impl_if_one_else_zero_; } /*! If a0 is true returns zero else returns one @par Semantic: For every parameter of type T0 : @code T0::type r = if_one_else_zero(a0); @endcode is similar to: @code T0::type r = a0 ? one : zero; @endcode @par Alias: @c if_one_else_zero, @c ifoneelsezero, @c sb2b; @see @funcref{genmask} @par Note: @c T0:type denotes here @c T0 in most cases, but @c T if @c T0 is @c as_logical<T> @param a0 @return a value of the type associated to the logical value a0 **/ BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::if_one_else_zero_, if_one_else_zero, 1) BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::if_one_else_zero_, ifoneelsezero, 1) BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::if_one_else_zero_, sb2b, 1) } } #endif
31.9375
190
0.646184
psiha
333f597861ed901be25f25753175e181f6f94f6a
1,266
cpp
C++
source/plc/src/document/EXACTLY.cpp
dlin172/Plange
4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04
[ "BSD-3-Clause" ]
null
null
null
source/plc/src/document/EXACTLY.cpp
dlin172/Plange
4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04
[ "BSD-3-Clause" ]
null
null
null
source/plc/src/document/EXACTLY.cpp
dlin172/Plange
4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04
[ "BSD-3-Clause" ]
null
null
null
// This file was generated using Parlex's cpp_generator #include "EXACTLY.hpp" #include "plange_grammar.hpp" #include "parlex/detail/document.hpp" #include "EXPRESSION.hpp" #include "IC.hpp" plc::EXACTLY plc::EXACTLY::build(parlex::detail::ast_node const & n) { static auto const * b = state_machine().behavior; parlex::detail::document::walk w{ n.children.cbegin(), n.children.cend() }; auto const & children = b->children; auto v0 = parlex::detail::document::element<erased<EXPRESSION>>::build(&*children[0], w); auto v1 = parlex::detail::document::element<std::vector<erased<IC>>>::build(&*children[1], w); auto v2 = parlex::detail::document::element<parlex::detail::document::text<literal_exactly_t>>::build(&*children[2], w); auto v3 = parlex::detail::document::element<std::vector<erased<IC>>>::build(&*children[3], w); auto v4 = parlex::detail::document::element<erased<EXPRESSION>>::build(&*children[4], w); return EXACTLY(std::move(v0), std::move(v1), std::move(v2), std::move(v3), std::move(v4)); } parlex::detail::state_machine const & plc::EXACTLY::state_machine() { static auto const & result = *static_cast<parlex::detail::state_machine const *>(&plange_grammar::get().get_recognizer(plange_grammar::get().EXACTLY)); return result; }
45.214286
152
0.71248
dlin172
334038fc5382de376e28dc2a08b4190a2f11bbad
417
cpp
C++
BOCA/AB/src/validator.cpp
Raquel29/PC1-IFB-CC
36b55e95373a5f022651545248d8cb66bac1cd3f
[ "MIT" ]
1
2020-05-24T02:22:13.000Z
2020-05-24T02:22:13.000Z
BOCA/AB/src/validator.cpp
danielsaad/PC1-IFB-CC
36b55e95373a5f022651545248d8cb66bac1cd3f
[ "MIT" ]
null
null
null
BOCA/AB/src/validator.cpp
danielsaad/PC1-IFB-CC
36b55e95373a5f022651545248d8cb66bac1cd3f
[ "MIT" ]
4
2019-05-15T10:55:57.000Z
2019-10-26T13:46:48.000Z
#include "testlib.h" #include <bits/stdc++.h> using namespace std; const int MIN_N = 2; const int MAX_N = 1e5; const double MIN_VALUE = 0.0; const double MAX_VALUE = 10.0; int main(int argc, char* argv[]) { registerValidation(argc, argv); int n = inf.readInt(MIN_N,MAX_N,"n"); inf.readEoln(); inf.readDoubles(n,MIN_VALUE,MAX_VALUE,"values"); inf.readEoln(); inf.readEof(); return 0; }
19.857143
52
0.657074
Raquel29
33407ef0747e90112dffe5b4bd15a0c62064c56e
315,827
cpp
C++
test/std/experimental/string.view/string.view.ops/compare.size_size_sv_size_size.pass.cpp
georgix/llvm_libcxx
9962ddfa24575d41ffeeaaf4f90a33ea859980dd
[ "MIT" ]
1,244
2015-01-02T21:08:56.000Z
2022-03-22T21:34:16.000Z
test/std/experimental/string.view/string.view.ops/compare.size_size_sv_size_size.pass.cpp
georgix/llvm_libcxx
9962ddfa24575d41ffeeaaf4f90a33ea859980dd
[ "MIT" ]
125
2015-01-22T01:08:00.000Z
2020-05-25T08:28:17.000Z
test/std/experimental/string.view/string.view.ops/compare.size_size_sv_size_size.pass.cpp
georgix/llvm_libcxx
9962ddfa24575d41ffeeaaf4f90a33ea859980dd
[ "MIT" ]
124
2015-01-12T15:06:17.000Z
2022-03-26T07:48:53.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. // //===----------------------------------------------------------------------===// // <string_view> // constexpr int compare(size_type pos1, size_type n1, basic_string_view str, // size_type pos2, size_type n2) const; #include <experimental/string_view> #include <cassert> #include "constexpr_char_traits.hpp" int sign ( int x ) { return x > 0 ? 1 : ( x < 0 ? -1 : 0 ); } template<typename CharT> void test1 ( std::experimental::basic_string_view<CharT> sv1, size_t pos1, size_t n1, std::experimental::basic_string_view<CharT> sv2, size_t pos2, size_t n2, int expected ) { try { assert ( sign( sv1.compare(pos1, n1, sv2, pos2, n2)) == sign(expected)); assert(pos1 <= sv1.size()); assert(pos2 <= sv2.size()); } catch (const std::out_of_range&) { assert(pos1 > sv1.size() || pos2 > sv2.size()); } } template<typename CharT> void test ( const CharT *s1, size_t pos1, size_t n1, const CharT *s2, size_t pos2, size_t n2, int expected ) { typedef std::experimental::basic_string_view<CharT> string_view_t; string_view_t sv1 ( s1 ); string_view_t sv2 ( s2 ); test1(sv1, pos1, n1, sv2, pos2, n2, expected); } void test0() { test("", 0, 0, "", 0, 0, 0); test("", 0, 0, "", 0, 1, 0); test("", 0, 0, "", 1, 0, 0); test("", 0, 0, "abcde", 0, 0, 0); test("", 0, 0, "abcde", 0, 1, -1); test("", 0, 0, "abcde", 0, 2, -2); test("", 0, 0, "abcde", 0, 4, -4); test("", 0, 0, "abcde", 0, 5, -5); test("", 0, 0, "abcde", 0, 6, -5); test("", 0, 0, "abcde", 1, 0, 0); test("", 0, 0, "abcde", 1, 1, -1); test("", 0, 0, "abcde", 1, 2, -2); test("", 0, 0, "abcde", 1, 3, -3); test("", 0, 0, "abcde", 1, 4, -4); test("", 0, 0, "abcde", 1, 5, -4); test("", 0, 0, "abcde", 2, 0, 0); test("", 0, 0, "abcde", 2, 1, -1); test("", 0, 0, "abcde", 2, 2, -2); test("", 0, 0, "abcde", 2, 3, -3); test("", 0, 0, "abcde", 2, 4, -3); test("", 0, 0, "abcde", 4, 0, 0); test("", 0, 0, "abcde", 4, 1, -1); test("", 0, 0, "abcde", 4, 2, -1); test("", 0, 0, "abcde", 5, 0, 0); test("", 0, 0, "abcde", 5, 1, 0); test("", 0, 0, "abcde", 6, 0, 0); test("", 0, 0, "abcdefghij", 0, 0, 0); test("", 0, 0, "abcdefghij", 0, 1, -1); test("", 0, 0, "abcdefghij", 0, 5, -5); test("", 0, 0, "abcdefghij", 0, 9, -9); test("", 0, 0, "abcdefghij", 0, 10, -10); test("", 0, 0, "abcdefghij", 0, 11, -10); test("", 0, 0, "abcdefghij", 1, 0, 0); test("", 0, 0, "abcdefghij", 1, 1, -1); test("", 0, 0, "abcdefghij", 1, 4, -4); test("", 0, 0, "abcdefghij", 1, 8, -8); test("", 0, 0, "abcdefghij", 1, 9, -9); test("", 0, 0, "abcdefghij", 1, 10, -9); test("", 0, 0, "abcdefghij", 5, 0, 0); test("", 0, 0, "abcdefghij", 5, 1, -1); test("", 0, 0, "abcdefghij", 5, 2, -2); test("", 0, 0, "abcdefghij", 5, 4, -4); test("", 0, 0, "abcdefghij", 5, 5, -5); test("", 0, 0, "abcdefghij", 5, 6, -5); test("", 0, 0, "abcdefghij", 9, 0, 0); test("", 0, 0, "abcdefghij", 9, 1, -1); test("", 0, 0, "abcdefghij", 9, 2, -1); test("", 0, 0, "abcdefghij", 10, 0, 0); test("", 0, 0, "abcdefghij", 10, 1, 0); test("", 0, 0, "abcdefghij", 11, 0, 0); test("", 0, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("", 0, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("", 0, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("", 0, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("", 0, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("", 0, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("", 0, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("", 0, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("", 0, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("", 0, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("", 0, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("", 0, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("", 0, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("", 0, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("", 0, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("", 0, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("", 0, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("", 0, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("", 0, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("", 0, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("", 0, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("", 0, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("", 0, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("", 0, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("", 0, 1, "", 0, 0, 0); test("", 0, 1, "", 0, 1, 0); test("", 0, 1, "", 1, 0, 0); test("", 0, 1, "abcde", 0, 0, 0); test("", 0, 1, "abcde", 0, 1, -1); test("", 0, 1, "abcde", 0, 2, -2); test("", 0, 1, "abcde", 0, 4, -4); test("", 0, 1, "abcde", 0, 5, -5); test("", 0, 1, "abcde", 0, 6, -5); test("", 0, 1, "abcde", 1, 0, 0); test("", 0, 1, "abcde", 1, 1, -1); test("", 0, 1, "abcde", 1, 2, -2); test("", 0, 1, "abcde", 1, 3, -3); test("", 0, 1, "abcde", 1, 4, -4); test("", 0, 1, "abcde", 1, 5, -4); test("", 0, 1, "abcde", 2, 0, 0); test("", 0, 1, "abcde", 2, 1, -1); test("", 0, 1, "abcde", 2, 2, -2); test("", 0, 1, "abcde", 2, 3, -3); test("", 0, 1, "abcde", 2, 4, -3); test("", 0, 1, "abcde", 4, 0, 0); test("", 0, 1, "abcde", 4, 1, -1); test("", 0, 1, "abcde", 4, 2, -1); test("", 0, 1, "abcde", 5, 0, 0); test("", 0, 1, "abcde", 5, 1, 0); test("", 0, 1, "abcde", 6, 0, 0); } void test1() { test("", 0, 1, "abcdefghij", 0, 0, 0); test("", 0, 1, "abcdefghij", 0, 1, -1); test("", 0, 1, "abcdefghij", 0, 5, -5); test("", 0, 1, "abcdefghij", 0, 9, -9); test("", 0, 1, "abcdefghij", 0, 10, -10); test("", 0, 1, "abcdefghij", 0, 11, -10); test("", 0, 1, "abcdefghij", 1, 0, 0); test("", 0, 1, "abcdefghij", 1, 1, -1); test("", 0, 1, "abcdefghij", 1, 4, -4); test("", 0, 1, "abcdefghij", 1, 8, -8); test("", 0, 1, "abcdefghij", 1, 9, -9); test("", 0, 1, "abcdefghij", 1, 10, -9); test("", 0, 1, "abcdefghij", 5, 0, 0); test("", 0, 1, "abcdefghij", 5, 1, -1); test("", 0, 1, "abcdefghij", 5, 2, -2); test("", 0, 1, "abcdefghij", 5, 4, -4); test("", 0, 1, "abcdefghij", 5, 5, -5); test("", 0, 1, "abcdefghij", 5, 6, -5); test("", 0, 1, "abcdefghij", 9, 0, 0); test("", 0, 1, "abcdefghij", 9, 1, -1); test("", 0, 1, "abcdefghij", 9, 2, -1); test("", 0, 1, "abcdefghij", 10, 0, 0); test("", 0, 1, "abcdefghij", 10, 1, 0); test("", 0, 1, "abcdefghij", 11, 0, 0); test("", 0, 1, "abcdefghijklmnopqrst", 0, 0, 0); test("", 0, 1, "abcdefghijklmnopqrst", 0, 1, -1); test("", 0, 1, "abcdefghijklmnopqrst", 0, 10, -10); test("", 0, 1, "abcdefghijklmnopqrst", 0, 19, -19); test("", 0, 1, "abcdefghijklmnopqrst", 0, 20, -20); test("", 0, 1, "abcdefghijklmnopqrst", 0, 21, -20); test("", 0, 1, "abcdefghijklmnopqrst", 1, 0, 0); test("", 0, 1, "abcdefghijklmnopqrst", 1, 1, -1); test("", 0, 1, "abcdefghijklmnopqrst", 1, 9, -9); test("", 0, 1, "abcdefghijklmnopqrst", 1, 18, -18); test("", 0, 1, "abcdefghijklmnopqrst", 1, 19, -19); test("", 0, 1, "abcdefghijklmnopqrst", 1, 20, -19); test("", 0, 1, "abcdefghijklmnopqrst", 10, 0, 0); test("", 0, 1, "abcdefghijklmnopqrst", 10, 1, -1); test("", 0, 1, "abcdefghijklmnopqrst", 10, 5, -5); test("", 0, 1, "abcdefghijklmnopqrst", 10, 9, -9); test("", 0, 1, "abcdefghijklmnopqrst", 10, 10, -10); test("", 0, 1, "abcdefghijklmnopqrst", 10, 11, -10); test("", 0, 1, "abcdefghijklmnopqrst", 19, 0, 0); test("", 0, 1, "abcdefghijklmnopqrst", 19, 1, -1); test("", 0, 1, "abcdefghijklmnopqrst", 19, 2, -1); test("", 0, 1, "abcdefghijklmnopqrst", 20, 0, 0); test("", 0, 1, "abcdefghijklmnopqrst", 20, 1, 0); test("", 0, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("", 1, 0, "", 0, 0, 0); test("", 1, 0, "", 0, 1, 0); test("", 1, 0, "", 1, 0, 0); test("", 1, 0, "abcde", 0, 0, 0); test("", 1, 0, "abcde", 0, 1, 0); test("", 1, 0, "abcde", 0, 2, 0); test("", 1, 0, "abcde", 0, 4, 0); test("", 1, 0, "abcde", 0, 5, 0); test("", 1, 0, "abcde", 0, 6, 0); test("", 1, 0, "abcde", 1, 0, 0); test("", 1, 0, "abcde", 1, 1, 0); test("", 1, 0, "abcde", 1, 2, 0); test("", 1, 0, "abcde", 1, 3, 0); test("", 1, 0, "abcde", 1, 4, 0); test("", 1, 0, "abcde", 1, 5, 0); test("", 1, 0, "abcde", 2, 0, 0); test("", 1, 0, "abcde", 2, 1, 0); test("", 1, 0, "abcde", 2, 2, 0); test("", 1, 0, "abcde", 2, 3, 0); test("", 1, 0, "abcde", 2, 4, 0); test("", 1, 0, "abcde", 4, 0, 0); test("", 1, 0, "abcde", 4, 1, 0); test("", 1, 0, "abcde", 4, 2, 0); test("", 1, 0, "abcde", 5, 0, 0); test("", 1, 0, "abcde", 5, 1, 0); test("", 1, 0, "abcde", 6, 0, 0); test("", 1, 0, "abcdefghij", 0, 0, 0); test("", 1, 0, "abcdefghij", 0, 1, 0); test("", 1, 0, "abcdefghij", 0, 5, 0); test("", 1, 0, "abcdefghij", 0, 9, 0); test("", 1, 0, "abcdefghij", 0, 10, 0); test("", 1, 0, "abcdefghij", 0, 11, 0); test("", 1, 0, "abcdefghij", 1, 0, 0); test("", 1, 0, "abcdefghij", 1, 1, 0); test("", 1, 0, "abcdefghij", 1, 4, 0); test("", 1, 0, "abcdefghij", 1, 8, 0); test("", 1, 0, "abcdefghij", 1, 9, 0); test("", 1, 0, "abcdefghij", 1, 10, 0); test("", 1, 0, "abcdefghij", 5, 0, 0); test("", 1, 0, "abcdefghij", 5, 1, 0); test("", 1, 0, "abcdefghij", 5, 2, 0); test("", 1, 0, "abcdefghij", 5, 4, 0); test("", 1, 0, "abcdefghij", 5, 5, 0); test("", 1, 0, "abcdefghij", 5, 6, 0); test("", 1, 0, "abcdefghij", 9, 0, 0); test("", 1, 0, "abcdefghij", 9, 1, 0); test("", 1, 0, "abcdefghij", 9, 2, 0); test("", 1, 0, "abcdefghij", 10, 0, 0); test("", 1, 0, "abcdefghij", 10, 1, 0); test("", 1, 0, "abcdefghij", 11, 0, 0); test("", 1, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("", 1, 0, "abcdefghijklmnopqrst", 0, 1, 0); } void test2() { test("", 1, 0, "abcdefghijklmnopqrst", 0, 10, 0); test("", 1, 0, "abcdefghijklmnopqrst", 0, 19, 0); test("", 1, 0, "abcdefghijklmnopqrst", 0, 20, 0); test("", 1, 0, "abcdefghijklmnopqrst", 0, 21, 0); test("", 1, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("", 1, 0, "abcdefghijklmnopqrst", 1, 1, 0); test("", 1, 0, "abcdefghijklmnopqrst", 1, 9, 0); test("", 1, 0, "abcdefghijklmnopqrst", 1, 18, 0); test("", 1, 0, "abcdefghijklmnopqrst", 1, 19, 0); test("", 1, 0, "abcdefghijklmnopqrst", 1, 20, 0); test("", 1, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("", 1, 0, "abcdefghijklmnopqrst", 10, 1, 0); test("", 1, 0, "abcdefghijklmnopqrst", 10, 5, 0); test("", 1, 0, "abcdefghijklmnopqrst", 10, 9, 0); test("", 1, 0, "abcdefghijklmnopqrst", 10, 10, 0); test("", 1, 0, "abcdefghijklmnopqrst", 10, 11, 0); test("", 1, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("", 1, 0, "abcdefghijklmnopqrst", 19, 1, 0); test("", 1, 0, "abcdefghijklmnopqrst", 19, 2, 0); test("", 1, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("", 1, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("", 1, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 0, 0, "", 0, 0, 0); test("abcde", 0, 0, "", 0, 1, 0); test("abcde", 0, 0, "", 1, 0, 0); test("abcde", 0, 0, "abcde", 0, 0, 0); test("abcde", 0, 0, "abcde", 0, 1, -1); test("abcde", 0, 0, "abcde", 0, 2, -2); test("abcde", 0, 0, "abcde", 0, 4, -4); test("abcde", 0, 0, "abcde", 0, 5, -5); test("abcde", 0, 0, "abcde", 0, 6, -5); test("abcde", 0, 0, "abcde", 1, 0, 0); test("abcde", 0, 0, "abcde", 1, 1, -1); test("abcde", 0, 0, "abcde", 1, 2, -2); test("abcde", 0, 0, "abcde", 1, 3, -3); test("abcde", 0, 0, "abcde", 1, 4, -4); test("abcde", 0, 0, "abcde", 1, 5, -4); test("abcde", 0, 0, "abcde", 2, 0, 0); test("abcde", 0, 0, "abcde", 2, 1, -1); test("abcde", 0, 0, "abcde", 2, 2, -2); test("abcde", 0, 0, "abcde", 2, 3, -3); test("abcde", 0, 0, "abcde", 2, 4, -3); test("abcde", 0, 0, "abcde", 4, 0, 0); test("abcde", 0, 0, "abcde", 4, 1, -1); test("abcde", 0, 0, "abcde", 4, 2, -1); test("abcde", 0, 0, "abcde", 5, 0, 0); test("abcde", 0, 0, "abcde", 5, 1, 0); test("abcde", 0, 0, "abcde", 6, 0, 0); test("abcde", 0, 0, "abcdefghij", 0, 0, 0); test("abcde", 0, 0, "abcdefghij", 0, 1, -1); test("abcde", 0, 0, "abcdefghij", 0, 5, -5); test("abcde", 0, 0, "abcdefghij", 0, 9, -9); test("abcde", 0, 0, "abcdefghij", 0, 10, -10); test("abcde", 0, 0, "abcdefghij", 0, 11, -10); test("abcde", 0, 0, "abcdefghij", 1, 0, 0); test("abcde", 0, 0, "abcdefghij", 1, 1, -1); test("abcde", 0, 0, "abcdefghij", 1, 4, -4); test("abcde", 0, 0, "abcdefghij", 1, 8, -8); test("abcde", 0, 0, "abcdefghij", 1, 9, -9); test("abcde", 0, 0, "abcdefghij", 1, 10, -9); test("abcde", 0, 0, "abcdefghij", 5, 0, 0); test("abcde", 0, 0, "abcdefghij", 5, 1, -1); test("abcde", 0, 0, "abcdefghij", 5, 2, -2); test("abcde", 0, 0, "abcdefghij", 5, 4, -4); test("abcde", 0, 0, "abcdefghij", 5, 5, -5); test("abcde", 0, 0, "abcdefghij", 5, 6, -5); test("abcde", 0, 0, "abcdefghij", 9, 0, 0); test("abcde", 0, 0, "abcdefghij", 9, 1, -1); test("abcde", 0, 0, "abcdefghij", 9, 2, -1); test("abcde", 0, 0, "abcdefghij", 10, 0, 0); test("abcde", 0, 0, "abcdefghij", 10, 1, 0); test("abcde", 0, 0, "abcdefghij", 11, 0, 0); test("abcde", 0, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcde", 0, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcde", 0, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcde", 0, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcde", 0, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcde", 0, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcde", 0, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcde", 0, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcde", 0, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcde", 0, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcde", 0, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcde", 0, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcde", 0, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcde", 0, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcde", 0, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcde", 0, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcde", 0, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcde", 0, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcde", 0, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcde", 0, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcde", 0, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcde", 0, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcde", 0, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcde", 0, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 0, 1, "", 0, 0, 1); test("abcde", 0, 1, "", 0, 1, 1); test("abcde", 0, 1, "", 1, 0, 0); test("abcde", 0, 1, "abcde", 0, 0, 1); } void test3() { test("abcde", 0, 1, "abcde", 0, 1, 0); test("abcde", 0, 1, "abcde", 0, 2, -1); test("abcde", 0, 1, "abcde", 0, 4, -3); test("abcde", 0, 1, "abcde", 0, 5, -4); test("abcde", 0, 1, "abcde", 0, 6, -4); test("abcde", 0, 1, "abcde", 1, 0, 1); test("abcde", 0, 1, "abcde", 1, 1, -1); test("abcde", 0, 1, "abcde", 1, 2, -1); test("abcde", 0, 1, "abcde", 1, 3, -1); test("abcde", 0, 1, "abcde", 1, 4, -1); test("abcde", 0, 1, "abcde", 1, 5, -1); test("abcde", 0, 1, "abcde", 2, 0, 1); test("abcde", 0, 1, "abcde", 2, 1, -2); test("abcde", 0, 1, "abcde", 2, 2, -2); test("abcde", 0, 1, "abcde", 2, 3, -2); test("abcde", 0, 1, "abcde", 2, 4, -2); test("abcde", 0, 1, "abcde", 4, 0, 1); test("abcde", 0, 1, "abcde", 4, 1, -4); test("abcde", 0, 1, "abcde", 4, 2, -4); test("abcde", 0, 1, "abcde", 5, 0, 1); test("abcde", 0, 1, "abcde", 5, 1, 1); test("abcde", 0, 1, "abcde", 6, 0, 0); test("abcde", 0, 1, "abcdefghij", 0, 0, 1); test("abcde", 0, 1, "abcdefghij", 0, 1, 0); test("abcde", 0, 1, "abcdefghij", 0, 5, -4); test("abcde", 0, 1, "abcdefghij", 0, 9, -8); test("abcde", 0, 1, "abcdefghij", 0, 10, -9); test("abcde", 0, 1, "abcdefghij", 0, 11, -9); test("abcde", 0, 1, "abcdefghij", 1, 0, 1); test("abcde", 0, 1, "abcdefghij", 1, 1, -1); test("abcde", 0, 1, "abcdefghij", 1, 4, -1); test("abcde", 0, 1, "abcdefghij", 1, 8, -1); test("abcde", 0, 1, "abcdefghij", 1, 9, -1); test("abcde", 0, 1, "abcdefghij", 1, 10, -1); test("abcde", 0, 1, "abcdefghij", 5, 0, 1); test("abcde", 0, 1, "abcdefghij", 5, 1, -5); test("abcde", 0, 1, "abcdefghij", 5, 2, -5); test("abcde", 0, 1, "abcdefghij", 5, 4, -5); test("abcde", 0, 1, "abcdefghij", 5, 5, -5); test("abcde", 0, 1, "abcdefghij", 5, 6, -5); test("abcde", 0, 1, "abcdefghij", 9, 0, 1); test("abcde", 0, 1, "abcdefghij", 9, 1, -9); test("abcde", 0, 1, "abcdefghij", 9, 2, -9); test("abcde", 0, 1, "abcdefghij", 10, 0, 1); test("abcde", 0, 1, "abcdefghij", 10, 1, 1); test("abcde", 0, 1, "abcdefghij", 11, 0, 0); test("abcde", 0, 1, "abcdefghijklmnopqrst", 0, 0, 1); test("abcde", 0, 1, "abcdefghijklmnopqrst", 0, 1, 0); test("abcde", 0, 1, "abcdefghijklmnopqrst", 0, 10, -9); test("abcde", 0, 1, "abcdefghijklmnopqrst", 0, 19, -18); test("abcde", 0, 1, "abcdefghijklmnopqrst", 0, 20, -19); test("abcde", 0, 1, "abcdefghijklmnopqrst", 0, 21, -19); test("abcde", 0, 1, "abcdefghijklmnopqrst", 1, 0, 1); test("abcde", 0, 1, "abcdefghijklmnopqrst", 1, 1, -1); test("abcde", 0, 1, "abcdefghijklmnopqrst", 1, 9, -1); test("abcde", 0, 1, "abcdefghijklmnopqrst", 1, 18, -1); test("abcde", 0, 1, "abcdefghijklmnopqrst", 1, 19, -1); test("abcde", 0, 1, "abcdefghijklmnopqrst", 1, 20, -1); test("abcde", 0, 1, "abcdefghijklmnopqrst", 10, 0, 1); test("abcde", 0, 1, "abcdefghijklmnopqrst", 10, 1, -10); test("abcde", 0, 1, "abcdefghijklmnopqrst", 10, 5, -10); test("abcde", 0, 1, "abcdefghijklmnopqrst", 10, 9, -10); test("abcde", 0, 1, "abcdefghijklmnopqrst", 10, 10, -10); test("abcde", 0, 1, "abcdefghijklmnopqrst", 10, 11, -10); test("abcde", 0, 1, "abcdefghijklmnopqrst", 19, 0, 1); test("abcde", 0, 1, "abcdefghijklmnopqrst", 19, 1, -19); test("abcde", 0, 1, "abcdefghijklmnopqrst", 19, 2, -19); test("abcde", 0, 1, "abcdefghijklmnopqrst", 20, 0, 1); test("abcde", 0, 1, "abcdefghijklmnopqrst", 20, 1, 1); test("abcde", 0, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 0, 2, "", 0, 0, 2); test("abcde", 0, 2, "", 0, 1, 2); test("abcde", 0, 2, "", 1, 0, 0); test("abcde", 0, 2, "abcde", 0, 0, 2); test("abcde", 0, 2, "abcde", 0, 1, 1); test("abcde", 0, 2, "abcde", 0, 2, 0); test("abcde", 0, 2, "abcde", 0, 4, -2); test("abcde", 0, 2, "abcde", 0, 5, -3); test("abcde", 0, 2, "abcde", 0, 6, -3); test("abcde", 0, 2, "abcde", 1, 0, 2); test("abcde", 0, 2, "abcde", 1, 1, -1); test("abcde", 0, 2, "abcde", 1, 2, -1); test("abcde", 0, 2, "abcde", 1, 3, -1); test("abcde", 0, 2, "abcde", 1, 4, -1); test("abcde", 0, 2, "abcde", 1, 5, -1); test("abcde", 0, 2, "abcde", 2, 0, 2); test("abcde", 0, 2, "abcde", 2, 1, -2); test("abcde", 0, 2, "abcde", 2, 2, -2); test("abcde", 0, 2, "abcde", 2, 3, -2); test("abcde", 0, 2, "abcde", 2, 4, -2); test("abcde", 0, 2, "abcde", 4, 0, 2); test("abcde", 0, 2, "abcde", 4, 1, -4); test("abcde", 0, 2, "abcde", 4, 2, -4); test("abcde", 0, 2, "abcde", 5, 0, 2); test("abcde", 0, 2, "abcde", 5, 1, 2); test("abcde", 0, 2, "abcde", 6, 0, 0); test("abcde", 0, 2, "abcdefghij", 0, 0, 2); test("abcde", 0, 2, "abcdefghij", 0, 1, 1); test("abcde", 0, 2, "abcdefghij", 0, 5, -3); test("abcde", 0, 2, "abcdefghij", 0, 9, -7); } void test4() { test("abcde", 0, 2, "abcdefghij", 0, 10, -8); test("abcde", 0, 2, "abcdefghij", 0, 11, -8); test("abcde", 0, 2, "abcdefghij", 1, 0, 2); test("abcde", 0, 2, "abcdefghij", 1, 1, -1); test("abcde", 0, 2, "abcdefghij", 1, 4, -1); test("abcde", 0, 2, "abcdefghij", 1, 8, -1); test("abcde", 0, 2, "abcdefghij", 1, 9, -1); test("abcde", 0, 2, "abcdefghij", 1, 10, -1); test("abcde", 0, 2, "abcdefghij", 5, 0, 2); test("abcde", 0, 2, "abcdefghij", 5, 1, -5); test("abcde", 0, 2, "abcdefghij", 5, 2, -5); test("abcde", 0, 2, "abcdefghij", 5, 4, -5); test("abcde", 0, 2, "abcdefghij", 5, 5, -5); test("abcde", 0, 2, "abcdefghij", 5, 6, -5); test("abcde", 0, 2, "abcdefghij", 9, 0, 2); test("abcde", 0, 2, "abcdefghij", 9, 1, -9); test("abcde", 0, 2, "abcdefghij", 9, 2, -9); test("abcde", 0, 2, "abcdefghij", 10, 0, 2); test("abcde", 0, 2, "abcdefghij", 10, 1, 2); test("abcde", 0, 2, "abcdefghij", 11, 0, 0); test("abcde", 0, 2, "abcdefghijklmnopqrst", 0, 0, 2); test("abcde", 0, 2, "abcdefghijklmnopqrst", 0, 1, 1); test("abcde", 0, 2, "abcdefghijklmnopqrst", 0, 10, -8); test("abcde", 0, 2, "abcdefghijklmnopqrst", 0, 19, -17); test("abcde", 0, 2, "abcdefghijklmnopqrst", 0, 20, -18); test("abcde", 0, 2, "abcdefghijklmnopqrst", 0, 21, -18); test("abcde", 0, 2, "abcdefghijklmnopqrst", 1, 0, 2); test("abcde", 0, 2, "abcdefghijklmnopqrst", 1, 1, -1); test("abcde", 0, 2, "abcdefghijklmnopqrst", 1, 9, -1); test("abcde", 0, 2, "abcdefghijklmnopqrst", 1, 18, -1); test("abcde", 0, 2, "abcdefghijklmnopqrst", 1, 19, -1); test("abcde", 0, 2, "abcdefghijklmnopqrst", 1, 20, -1); test("abcde", 0, 2, "abcdefghijklmnopqrst", 10, 0, 2); test("abcde", 0, 2, "abcdefghijklmnopqrst", 10, 1, -10); test("abcde", 0, 2, "abcdefghijklmnopqrst", 10, 5, -10); test("abcde", 0, 2, "abcdefghijklmnopqrst", 10, 9, -10); test("abcde", 0, 2, "abcdefghijklmnopqrst", 10, 10, -10); test("abcde", 0, 2, "abcdefghijklmnopqrst", 10, 11, -10); test("abcde", 0, 2, "abcdefghijklmnopqrst", 19, 0, 2); test("abcde", 0, 2, "abcdefghijklmnopqrst", 19, 1, -19); test("abcde", 0, 2, "abcdefghijklmnopqrst", 19, 2, -19); test("abcde", 0, 2, "abcdefghijklmnopqrst", 20, 0, 2); test("abcde", 0, 2, "abcdefghijklmnopqrst", 20, 1, 2); test("abcde", 0, 2, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 0, 4, "", 0, 0, 4); test("abcde", 0, 4, "", 0, 1, 4); test("abcde", 0, 4, "", 1, 0, 0); test("abcde", 0, 4, "abcde", 0, 0, 4); test("abcde", 0, 4, "abcde", 0, 1, 3); test("abcde", 0, 4, "abcde", 0, 2, 2); test("abcde", 0, 4, "abcde", 0, 4, 0); test("abcde", 0, 4, "abcde", 0, 5, -1); test("abcde", 0, 4, "abcde", 0, 6, -1); test("abcde", 0, 4, "abcde", 1, 0, 4); test("abcde", 0, 4, "abcde", 1, 1, -1); test("abcde", 0, 4, "abcde", 1, 2, -1); test("abcde", 0, 4, "abcde", 1, 3, -1); test("abcde", 0, 4, "abcde", 1, 4, -1); test("abcde", 0, 4, "abcde", 1, 5, -1); test("abcde", 0, 4, "abcde", 2, 0, 4); test("abcde", 0, 4, "abcde", 2, 1, -2); test("abcde", 0, 4, "abcde", 2, 2, -2); test("abcde", 0, 4, "abcde", 2, 3, -2); test("abcde", 0, 4, "abcde", 2, 4, -2); test("abcde", 0, 4, "abcde", 4, 0, 4); test("abcde", 0, 4, "abcde", 4, 1, -4); test("abcde", 0, 4, "abcde", 4, 2, -4); test("abcde", 0, 4, "abcde", 5, 0, 4); test("abcde", 0, 4, "abcde", 5, 1, 4); test("abcde", 0, 4, "abcde", 6, 0, 0); test("abcde", 0, 4, "abcdefghij", 0, 0, 4); test("abcde", 0, 4, "abcdefghij", 0, 1, 3); test("abcde", 0, 4, "abcdefghij", 0, 5, -1); test("abcde", 0, 4, "abcdefghij", 0, 9, -5); test("abcde", 0, 4, "abcdefghij", 0, 10, -6); test("abcde", 0, 4, "abcdefghij", 0, 11, -6); test("abcde", 0, 4, "abcdefghij", 1, 0, 4); test("abcde", 0, 4, "abcdefghij", 1, 1, -1); test("abcde", 0, 4, "abcdefghij", 1, 4, -1); test("abcde", 0, 4, "abcdefghij", 1, 8, -1); test("abcde", 0, 4, "abcdefghij", 1, 9, -1); test("abcde", 0, 4, "abcdefghij", 1, 10, -1); test("abcde", 0, 4, "abcdefghij", 5, 0, 4); test("abcde", 0, 4, "abcdefghij", 5, 1, -5); test("abcde", 0, 4, "abcdefghij", 5, 2, -5); test("abcde", 0, 4, "abcdefghij", 5, 4, -5); test("abcde", 0, 4, "abcdefghij", 5, 5, -5); test("abcde", 0, 4, "abcdefghij", 5, 6, -5); test("abcde", 0, 4, "abcdefghij", 9, 0, 4); test("abcde", 0, 4, "abcdefghij", 9, 1, -9); test("abcde", 0, 4, "abcdefghij", 9, 2, -9); test("abcde", 0, 4, "abcdefghij", 10, 0, 4); test("abcde", 0, 4, "abcdefghij", 10, 1, 4); test("abcde", 0, 4, "abcdefghij", 11, 0, 0); test("abcde", 0, 4, "abcdefghijklmnopqrst", 0, 0, 4); test("abcde", 0, 4, "abcdefghijklmnopqrst", 0, 1, 3); test("abcde", 0, 4, "abcdefghijklmnopqrst", 0, 10, -6); test("abcde", 0, 4, "abcdefghijklmnopqrst", 0, 19, -15); test("abcde", 0, 4, "abcdefghijklmnopqrst", 0, 20, -16); test("abcde", 0, 4, "abcdefghijklmnopqrst", 0, 21, -16); } void test5() { test("abcde", 0, 4, "abcdefghijklmnopqrst", 1, 0, 4); test("abcde", 0, 4, "abcdefghijklmnopqrst", 1, 1, -1); test("abcde", 0, 4, "abcdefghijklmnopqrst", 1, 9, -1); test("abcde", 0, 4, "abcdefghijklmnopqrst", 1, 18, -1); test("abcde", 0, 4, "abcdefghijklmnopqrst", 1, 19, -1); test("abcde", 0, 4, "abcdefghijklmnopqrst", 1, 20, -1); test("abcde", 0, 4, "abcdefghijklmnopqrst", 10, 0, 4); test("abcde", 0, 4, "abcdefghijklmnopqrst", 10, 1, -10); test("abcde", 0, 4, "abcdefghijklmnopqrst", 10, 5, -10); test("abcde", 0, 4, "abcdefghijklmnopqrst", 10, 9, -10); test("abcde", 0, 4, "abcdefghijklmnopqrst", 10, 10, -10); test("abcde", 0, 4, "abcdefghijklmnopqrst", 10, 11, -10); test("abcde", 0, 4, "abcdefghijklmnopqrst", 19, 0, 4); test("abcde", 0, 4, "abcdefghijklmnopqrst", 19, 1, -19); test("abcde", 0, 4, "abcdefghijklmnopqrst", 19, 2, -19); test("abcde", 0, 4, "abcdefghijklmnopqrst", 20, 0, 4); test("abcde", 0, 4, "abcdefghijklmnopqrst", 20, 1, 4); test("abcde", 0, 4, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 0, 5, "", 0, 0, 5); test("abcde", 0, 5, "", 0, 1, 5); test("abcde", 0, 5, "", 1, 0, 0); test("abcde", 0, 5, "abcde", 0, 0, 5); test("abcde", 0, 5, "abcde", 0, 1, 4); test("abcde", 0, 5, "abcde", 0, 2, 3); test("abcde", 0, 5, "abcde", 0, 4, 1); test("abcde", 0, 5, "abcde", 0, 5, 0); test("abcde", 0, 5, "abcde", 0, 6, 0); test("abcde", 0, 5, "abcde", 1, 0, 5); test("abcde", 0, 5, "abcde", 1, 1, -1); test("abcde", 0, 5, "abcde", 1, 2, -1); test("abcde", 0, 5, "abcde", 1, 3, -1); test("abcde", 0, 5, "abcde", 1, 4, -1); test("abcde", 0, 5, "abcde", 1, 5, -1); test("abcde", 0, 5, "abcde", 2, 0, 5); test("abcde", 0, 5, "abcde", 2, 1, -2); test("abcde", 0, 5, "abcde", 2, 2, -2); test("abcde", 0, 5, "abcde", 2, 3, -2); test("abcde", 0, 5, "abcde", 2, 4, -2); test("abcde", 0, 5, "abcde", 4, 0, 5); test("abcde", 0, 5, "abcde", 4, 1, -4); test("abcde", 0, 5, "abcde", 4, 2, -4); test("abcde", 0, 5, "abcde", 5, 0, 5); test("abcde", 0, 5, "abcde", 5, 1, 5); test("abcde", 0, 5, "abcde", 6, 0, 0); test("abcde", 0, 5, "abcdefghij", 0, 0, 5); test("abcde", 0, 5, "abcdefghij", 0, 1, 4); test("abcde", 0, 5, "abcdefghij", 0, 5, 0); test("abcde", 0, 5, "abcdefghij", 0, 9, -4); test("abcde", 0, 5, "abcdefghij", 0, 10, -5); test("abcde", 0, 5, "abcdefghij", 0, 11, -5); test("abcde", 0, 5, "abcdefghij", 1, 0, 5); test("abcde", 0, 5, "abcdefghij", 1, 1, -1); test("abcde", 0, 5, "abcdefghij", 1, 4, -1); test("abcde", 0, 5, "abcdefghij", 1, 8, -1); test("abcde", 0, 5, "abcdefghij", 1, 9, -1); test("abcde", 0, 5, "abcdefghij", 1, 10, -1); test("abcde", 0, 5, "abcdefghij", 5, 0, 5); test("abcde", 0, 5, "abcdefghij", 5, 1, -5); test("abcde", 0, 5, "abcdefghij", 5, 2, -5); test("abcde", 0, 5, "abcdefghij", 5, 4, -5); test("abcde", 0, 5, "abcdefghij", 5, 5, -5); test("abcde", 0, 5, "abcdefghij", 5, 6, -5); test("abcde", 0, 5, "abcdefghij", 9, 0, 5); test("abcde", 0, 5, "abcdefghij", 9, 1, -9); test("abcde", 0, 5, "abcdefghij", 9, 2, -9); test("abcde", 0, 5, "abcdefghij", 10, 0, 5); test("abcde", 0, 5, "abcdefghij", 10, 1, 5); test("abcde", 0, 5, "abcdefghij", 11, 0, 0); test("abcde", 0, 5, "abcdefghijklmnopqrst", 0, 0, 5); test("abcde", 0, 5, "abcdefghijklmnopqrst", 0, 1, 4); test("abcde", 0, 5, "abcdefghijklmnopqrst", 0, 10, -5); test("abcde", 0, 5, "abcdefghijklmnopqrst", 0, 19, -14); test("abcde", 0, 5, "abcdefghijklmnopqrst", 0, 20, -15); test("abcde", 0, 5, "abcdefghijklmnopqrst", 0, 21, -15); test("abcde", 0, 5, "abcdefghijklmnopqrst", 1, 0, 5); test("abcde", 0, 5, "abcdefghijklmnopqrst", 1, 1, -1); test("abcde", 0, 5, "abcdefghijklmnopqrst", 1, 9, -1); test("abcde", 0, 5, "abcdefghijklmnopqrst", 1, 18, -1); test("abcde", 0, 5, "abcdefghijklmnopqrst", 1, 19, -1); test("abcde", 0, 5, "abcdefghijklmnopqrst", 1, 20, -1); test("abcde", 0, 5, "abcdefghijklmnopqrst", 10, 0, 5); test("abcde", 0, 5, "abcdefghijklmnopqrst", 10, 1, -10); test("abcde", 0, 5, "abcdefghijklmnopqrst", 10, 5, -10); test("abcde", 0, 5, "abcdefghijklmnopqrst", 10, 9, -10); test("abcde", 0, 5, "abcdefghijklmnopqrst", 10, 10, -10); test("abcde", 0, 5, "abcdefghijklmnopqrst", 10, 11, -10); test("abcde", 0, 5, "abcdefghijklmnopqrst", 19, 0, 5); test("abcde", 0, 5, "abcdefghijklmnopqrst", 19, 1, -19); test("abcde", 0, 5, "abcdefghijklmnopqrst", 19, 2, -19); test("abcde", 0, 5, "abcdefghijklmnopqrst", 20, 0, 5); test("abcde", 0, 5, "abcdefghijklmnopqrst", 20, 1, 5); test("abcde", 0, 5, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 0, 6, "", 0, 0, 5); test("abcde", 0, 6, "", 0, 1, 5); test("abcde", 0, 6, "", 1, 0, 0); test("abcde", 0, 6, "abcde", 0, 0, 5); test("abcde", 0, 6, "abcde", 0, 1, 4); test("abcde", 0, 6, "abcde", 0, 2, 3); test("abcde", 0, 6, "abcde", 0, 4, 1); test("abcde", 0, 6, "abcde", 0, 5, 0); } void test6() { test("abcde", 0, 6, "abcde", 0, 6, 0); test("abcde", 0, 6, "abcde", 1, 0, 5); test("abcde", 0, 6, "abcde", 1, 1, -1); test("abcde", 0, 6, "abcde", 1, 2, -1); test("abcde", 0, 6, "abcde", 1, 3, -1); test("abcde", 0, 6, "abcde", 1, 4, -1); test("abcde", 0, 6, "abcde", 1, 5, -1); test("abcde", 0, 6, "abcde", 2, 0, 5); test("abcde", 0, 6, "abcde", 2, 1, -2); test("abcde", 0, 6, "abcde", 2, 2, -2); test("abcde", 0, 6, "abcde", 2, 3, -2); test("abcde", 0, 6, "abcde", 2, 4, -2); test("abcde", 0, 6, "abcde", 4, 0, 5); test("abcde", 0, 6, "abcde", 4, 1, -4); test("abcde", 0, 6, "abcde", 4, 2, -4); test("abcde", 0, 6, "abcde", 5, 0, 5); test("abcde", 0, 6, "abcde", 5, 1, 5); test("abcde", 0, 6, "abcde", 6, 0, 0); test("abcde", 0, 6, "abcdefghij", 0, 0, 5); test("abcde", 0, 6, "abcdefghij", 0, 1, 4); test("abcde", 0, 6, "abcdefghij", 0, 5, 0); test("abcde", 0, 6, "abcdefghij", 0, 9, -4); test("abcde", 0, 6, "abcdefghij", 0, 10, -5); test("abcde", 0, 6, "abcdefghij", 0, 11, -5); test("abcde", 0, 6, "abcdefghij", 1, 0, 5); test("abcde", 0, 6, "abcdefghij", 1, 1, -1); test("abcde", 0, 6, "abcdefghij", 1, 4, -1); test("abcde", 0, 6, "abcdefghij", 1, 8, -1); test("abcde", 0, 6, "abcdefghij", 1, 9, -1); test("abcde", 0, 6, "abcdefghij", 1, 10, -1); test("abcde", 0, 6, "abcdefghij", 5, 0, 5); test("abcde", 0, 6, "abcdefghij", 5, 1, -5); test("abcde", 0, 6, "abcdefghij", 5, 2, -5); test("abcde", 0, 6, "abcdefghij", 5, 4, -5); test("abcde", 0, 6, "abcdefghij", 5, 5, -5); test("abcde", 0, 6, "abcdefghij", 5, 6, -5); test("abcde", 0, 6, "abcdefghij", 9, 0, 5); test("abcde", 0, 6, "abcdefghij", 9, 1, -9); test("abcde", 0, 6, "abcdefghij", 9, 2, -9); test("abcde", 0, 6, "abcdefghij", 10, 0, 5); test("abcde", 0, 6, "abcdefghij", 10, 1, 5); test("abcde", 0, 6, "abcdefghij", 11, 0, 0); test("abcde", 0, 6, "abcdefghijklmnopqrst", 0, 0, 5); test("abcde", 0, 6, "abcdefghijklmnopqrst", 0, 1, 4); test("abcde", 0, 6, "abcdefghijklmnopqrst", 0, 10, -5); test("abcde", 0, 6, "abcdefghijklmnopqrst", 0, 19, -14); test("abcde", 0, 6, "abcdefghijklmnopqrst", 0, 20, -15); test("abcde", 0, 6, "abcdefghijklmnopqrst", 0, 21, -15); test("abcde", 0, 6, "abcdefghijklmnopqrst", 1, 0, 5); test("abcde", 0, 6, "abcdefghijklmnopqrst", 1, 1, -1); test("abcde", 0, 6, "abcdefghijklmnopqrst", 1, 9, -1); test("abcde", 0, 6, "abcdefghijklmnopqrst", 1, 18, -1); test("abcde", 0, 6, "abcdefghijklmnopqrst", 1, 19, -1); test("abcde", 0, 6, "abcdefghijklmnopqrst", 1, 20, -1); test("abcde", 0, 6, "abcdefghijklmnopqrst", 10, 0, 5); test("abcde", 0, 6, "abcdefghijklmnopqrst", 10, 1, -10); test("abcde", 0, 6, "abcdefghijklmnopqrst", 10, 5, -10); test("abcde", 0, 6, "abcdefghijklmnopqrst", 10, 9, -10); test("abcde", 0, 6, "abcdefghijklmnopqrst", 10, 10, -10); test("abcde", 0, 6, "abcdefghijklmnopqrst", 10, 11, -10); test("abcde", 0, 6, "abcdefghijklmnopqrst", 19, 0, 5); test("abcde", 0, 6, "abcdefghijklmnopqrst", 19, 1, -19); test("abcde", 0, 6, "abcdefghijklmnopqrst", 19, 2, -19); test("abcde", 0, 6, "abcdefghijklmnopqrst", 20, 0, 5); test("abcde", 0, 6, "abcdefghijklmnopqrst", 20, 1, 5); test("abcde", 0, 6, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 1, 0, "", 0, 0, 0); test("abcde", 1, 0, "", 0, 1, 0); test("abcde", 1, 0, "", 1, 0, 0); test("abcde", 1, 0, "abcde", 0, 0, 0); test("abcde", 1, 0, "abcde", 0, 1, -1); test("abcde", 1, 0, "abcde", 0, 2, -2); test("abcde", 1, 0, "abcde", 0, 4, -4); test("abcde", 1, 0, "abcde", 0, 5, -5); test("abcde", 1, 0, "abcde", 0, 6, -5); test("abcde", 1, 0, "abcde", 1, 0, 0); test("abcde", 1, 0, "abcde", 1, 1, -1); test("abcde", 1, 0, "abcde", 1, 2, -2); test("abcde", 1, 0, "abcde", 1, 3, -3); test("abcde", 1, 0, "abcde", 1, 4, -4); test("abcde", 1, 0, "abcde", 1, 5, -4); test("abcde", 1, 0, "abcde", 2, 0, 0); test("abcde", 1, 0, "abcde", 2, 1, -1); test("abcde", 1, 0, "abcde", 2, 2, -2); test("abcde", 1, 0, "abcde", 2, 3, -3); test("abcde", 1, 0, "abcde", 2, 4, -3); test("abcde", 1, 0, "abcde", 4, 0, 0); test("abcde", 1, 0, "abcde", 4, 1, -1); test("abcde", 1, 0, "abcde", 4, 2, -1); test("abcde", 1, 0, "abcde", 5, 0, 0); test("abcde", 1, 0, "abcde", 5, 1, 0); test("abcde", 1, 0, "abcde", 6, 0, 0); test("abcde", 1, 0, "abcdefghij", 0, 0, 0); test("abcde", 1, 0, "abcdefghij", 0, 1, -1); test("abcde", 1, 0, "abcdefghij", 0, 5, -5); test("abcde", 1, 0, "abcdefghij", 0, 9, -9); test("abcde", 1, 0, "abcdefghij", 0, 10, -10); test("abcde", 1, 0, "abcdefghij", 0, 11, -10); test("abcde", 1, 0, "abcdefghij", 1, 0, 0); test("abcde", 1, 0, "abcdefghij", 1, 1, -1); } void test7() { test("abcde", 1, 0, "abcdefghij", 1, 4, -4); test("abcde", 1, 0, "abcdefghij", 1, 8, -8); test("abcde", 1, 0, "abcdefghij", 1, 9, -9); test("abcde", 1, 0, "abcdefghij", 1, 10, -9); test("abcde", 1, 0, "abcdefghij", 5, 0, 0); test("abcde", 1, 0, "abcdefghij", 5, 1, -1); test("abcde", 1, 0, "abcdefghij", 5, 2, -2); test("abcde", 1, 0, "abcdefghij", 5, 4, -4); test("abcde", 1, 0, "abcdefghij", 5, 5, -5); test("abcde", 1, 0, "abcdefghij", 5, 6, -5); test("abcde", 1, 0, "abcdefghij", 9, 0, 0); test("abcde", 1, 0, "abcdefghij", 9, 1, -1); test("abcde", 1, 0, "abcdefghij", 9, 2, -1); test("abcde", 1, 0, "abcdefghij", 10, 0, 0); test("abcde", 1, 0, "abcdefghij", 10, 1, 0); test("abcde", 1, 0, "abcdefghij", 11, 0, 0); test("abcde", 1, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcde", 1, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcde", 1, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcde", 1, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcde", 1, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcde", 1, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcde", 1, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcde", 1, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcde", 1, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcde", 1, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcde", 1, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcde", 1, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcde", 1, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcde", 1, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcde", 1, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcde", 1, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcde", 1, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcde", 1, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcde", 1, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcde", 1, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcde", 1, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcde", 1, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcde", 1, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcde", 1, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 1, 1, "", 0, 0, 1); test("abcde", 1, 1, "", 0, 1, 1); test("abcde", 1, 1, "", 1, 0, 0); test("abcde", 1, 1, "abcde", 0, 0, 1); test("abcde", 1, 1, "abcde", 0, 1, 1); test("abcde", 1, 1, "abcde", 0, 2, 1); test("abcde", 1, 1, "abcde", 0, 4, 1); test("abcde", 1, 1, "abcde", 0, 5, 1); test("abcde", 1, 1, "abcde", 0, 6, 1); test("abcde", 1, 1, "abcde", 1, 0, 1); test("abcde", 1, 1, "abcde", 1, 1, 0); test("abcde", 1, 1, "abcde", 1, 2, -1); test("abcde", 1, 1, "abcde", 1, 3, -2); test("abcde", 1, 1, "abcde", 1, 4, -3); test("abcde", 1, 1, "abcde", 1, 5, -3); test("abcde", 1, 1, "abcde", 2, 0, 1); test("abcde", 1, 1, "abcde", 2, 1, -1); test("abcde", 1, 1, "abcde", 2, 2, -1); test("abcde", 1, 1, "abcde", 2, 3, -1); test("abcde", 1, 1, "abcde", 2, 4, -1); test("abcde", 1, 1, "abcde", 4, 0, 1); test("abcde", 1, 1, "abcde", 4, 1, -3); test("abcde", 1, 1, "abcde", 4, 2, -3); test("abcde", 1, 1, "abcde", 5, 0, 1); test("abcde", 1, 1, "abcde", 5, 1, 1); test("abcde", 1, 1, "abcde", 6, 0, 0); test("abcde", 1, 1, "abcdefghij", 0, 0, 1); test("abcde", 1, 1, "abcdefghij", 0, 1, 1); test("abcde", 1, 1, "abcdefghij", 0, 5, 1); test("abcde", 1, 1, "abcdefghij", 0, 9, 1); test("abcde", 1, 1, "abcdefghij", 0, 10, 1); test("abcde", 1, 1, "abcdefghij", 0, 11, 1); test("abcde", 1, 1, "abcdefghij", 1, 0, 1); test("abcde", 1, 1, "abcdefghij", 1, 1, 0); test("abcde", 1, 1, "abcdefghij", 1, 4, -3); test("abcde", 1, 1, "abcdefghij", 1, 8, -7); test("abcde", 1, 1, "abcdefghij", 1, 9, -8); test("abcde", 1, 1, "abcdefghij", 1, 10, -8); test("abcde", 1, 1, "abcdefghij", 5, 0, 1); test("abcde", 1, 1, "abcdefghij", 5, 1, -4); test("abcde", 1, 1, "abcdefghij", 5, 2, -4); test("abcde", 1, 1, "abcdefghij", 5, 4, -4); test("abcde", 1, 1, "abcdefghij", 5, 5, -4); test("abcde", 1, 1, "abcdefghij", 5, 6, -4); test("abcde", 1, 1, "abcdefghij", 9, 0, 1); test("abcde", 1, 1, "abcdefghij", 9, 1, -8); test("abcde", 1, 1, "abcdefghij", 9, 2, -8); test("abcde", 1, 1, "abcdefghij", 10, 0, 1); test("abcde", 1, 1, "abcdefghij", 10, 1, 1); test("abcde", 1, 1, "abcdefghij", 11, 0, 0); test("abcde", 1, 1, "abcdefghijklmnopqrst", 0, 0, 1); test("abcde", 1, 1, "abcdefghijklmnopqrst", 0, 1, 1); test("abcde", 1, 1, "abcdefghijklmnopqrst", 0, 10, 1); test("abcde", 1, 1, "abcdefghijklmnopqrst", 0, 19, 1); test("abcde", 1, 1, "abcdefghijklmnopqrst", 0, 20, 1); test("abcde", 1, 1, "abcdefghijklmnopqrst", 0, 21, 1); test("abcde", 1, 1, "abcdefghijklmnopqrst", 1, 0, 1); test("abcde", 1, 1, "abcdefghijklmnopqrst", 1, 1, 0); test("abcde", 1, 1, "abcdefghijklmnopqrst", 1, 9, -8); test("abcde", 1, 1, "abcdefghijklmnopqrst", 1, 18, -17); } void test8() { test("abcde", 1, 1, "abcdefghijklmnopqrst", 1, 19, -18); test("abcde", 1, 1, "abcdefghijklmnopqrst", 1, 20, -18); test("abcde", 1, 1, "abcdefghijklmnopqrst", 10, 0, 1); test("abcde", 1, 1, "abcdefghijklmnopqrst", 10, 1, -9); test("abcde", 1, 1, "abcdefghijklmnopqrst", 10, 5, -9); test("abcde", 1, 1, "abcdefghijklmnopqrst", 10, 9, -9); test("abcde", 1, 1, "abcdefghijklmnopqrst", 10, 10, -9); test("abcde", 1, 1, "abcdefghijklmnopqrst", 10, 11, -9); test("abcde", 1, 1, "abcdefghijklmnopqrst", 19, 0, 1); test("abcde", 1, 1, "abcdefghijklmnopqrst", 19, 1, -18); test("abcde", 1, 1, "abcdefghijklmnopqrst", 19, 2, -18); test("abcde", 1, 1, "abcdefghijklmnopqrst", 20, 0, 1); test("abcde", 1, 1, "abcdefghijklmnopqrst", 20, 1, 1); test("abcde", 1, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 1, 2, "", 0, 0, 2); test("abcde", 1, 2, "", 0, 1, 2); test("abcde", 1, 2, "", 1, 0, 0); test("abcde", 1, 2, "abcde", 0, 0, 2); test("abcde", 1, 2, "abcde", 0, 1, 1); test("abcde", 1, 2, "abcde", 0, 2, 1); test("abcde", 1, 2, "abcde", 0, 4, 1); test("abcde", 1, 2, "abcde", 0, 5, 1); test("abcde", 1, 2, "abcde", 0, 6, 1); test("abcde", 1, 2, "abcde", 1, 0, 2); test("abcde", 1, 2, "abcde", 1, 1, 1); test("abcde", 1, 2, "abcde", 1, 2, 0); test("abcde", 1, 2, "abcde", 1, 3, -1); test("abcde", 1, 2, "abcde", 1, 4, -2); test("abcde", 1, 2, "abcde", 1, 5, -2); test("abcde", 1, 2, "abcde", 2, 0, 2); test("abcde", 1, 2, "abcde", 2, 1, -1); test("abcde", 1, 2, "abcde", 2, 2, -1); test("abcde", 1, 2, "abcde", 2, 3, -1); test("abcde", 1, 2, "abcde", 2, 4, -1); test("abcde", 1, 2, "abcde", 4, 0, 2); test("abcde", 1, 2, "abcde", 4, 1, -3); test("abcde", 1, 2, "abcde", 4, 2, -3); test("abcde", 1, 2, "abcde", 5, 0, 2); test("abcde", 1, 2, "abcde", 5, 1, 2); test("abcde", 1, 2, "abcde", 6, 0, 0); test("abcde", 1, 2, "abcdefghij", 0, 0, 2); test("abcde", 1, 2, "abcdefghij", 0, 1, 1); test("abcde", 1, 2, "abcdefghij", 0, 5, 1); test("abcde", 1, 2, "abcdefghij", 0, 9, 1); test("abcde", 1, 2, "abcdefghij", 0, 10, 1); test("abcde", 1, 2, "abcdefghij", 0, 11, 1); test("abcde", 1, 2, "abcdefghij", 1, 0, 2); test("abcde", 1, 2, "abcdefghij", 1, 1, 1); test("abcde", 1, 2, "abcdefghij", 1, 4, -2); test("abcde", 1, 2, "abcdefghij", 1, 8, -6); test("abcde", 1, 2, "abcdefghij", 1, 9, -7); test("abcde", 1, 2, "abcdefghij", 1, 10, -7); test("abcde", 1, 2, "abcdefghij", 5, 0, 2); test("abcde", 1, 2, "abcdefghij", 5, 1, -4); test("abcde", 1, 2, "abcdefghij", 5, 2, -4); test("abcde", 1, 2, "abcdefghij", 5, 4, -4); test("abcde", 1, 2, "abcdefghij", 5, 5, -4); test("abcde", 1, 2, "abcdefghij", 5, 6, -4); test("abcde", 1, 2, "abcdefghij", 9, 0, 2); test("abcde", 1, 2, "abcdefghij", 9, 1, -8); test("abcde", 1, 2, "abcdefghij", 9, 2, -8); test("abcde", 1, 2, "abcdefghij", 10, 0, 2); test("abcde", 1, 2, "abcdefghij", 10, 1, 2); test("abcde", 1, 2, "abcdefghij", 11, 0, 0); test("abcde", 1, 2, "abcdefghijklmnopqrst", 0, 0, 2); test("abcde", 1, 2, "abcdefghijklmnopqrst", 0, 1, 1); test("abcde", 1, 2, "abcdefghijklmnopqrst", 0, 10, 1); test("abcde", 1, 2, "abcdefghijklmnopqrst", 0, 19, 1); test("abcde", 1, 2, "abcdefghijklmnopqrst", 0, 20, 1); test("abcde", 1, 2, "abcdefghijklmnopqrst", 0, 21, 1); test("abcde", 1, 2, "abcdefghijklmnopqrst", 1, 0, 2); test("abcde", 1, 2, "abcdefghijklmnopqrst", 1, 1, 1); test("abcde", 1, 2, "abcdefghijklmnopqrst", 1, 9, -7); test("abcde", 1, 2, "abcdefghijklmnopqrst", 1, 18, -16); test("abcde", 1, 2, "abcdefghijklmnopqrst", 1, 19, -17); test("abcde", 1, 2, "abcdefghijklmnopqrst", 1, 20, -17); test("abcde", 1, 2, "abcdefghijklmnopqrst", 10, 0, 2); test("abcde", 1, 2, "abcdefghijklmnopqrst", 10, 1, -9); test("abcde", 1, 2, "abcdefghijklmnopqrst", 10, 5, -9); test("abcde", 1, 2, "abcdefghijklmnopqrst", 10, 9, -9); test("abcde", 1, 2, "abcdefghijklmnopqrst", 10, 10, -9); test("abcde", 1, 2, "abcdefghijklmnopqrst", 10, 11, -9); test("abcde", 1, 2, "abcdefghijklmnopqrst", 19, 0, 2); test("abcde", 1, 2, "abcdefghijklmnopqrst", 19, 1, -18); test("abcde", 1, 2, "abcdefghijklmnopqrst", 19, 2, -18); test("abcde", 1, 2, "abcdefghijklmnopqrst", 20, 0, 2); test("abcde", 1, 2, "abcdefghijklmnopqrst", 20, 1, 2); test("abcde", 1, 2, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 1, 3, "", 0, 0, 3); test("abcde", 1, 3, "", 0, 1, 3); test("abcde", 1, 3, "", 1, 0, 0); test("abcde", 1, 3, "abcde", 0, 0, 3); test("abcde", 1, 3, "abcde", 0, 1, 1); test("abcde", 1, 3, "abcde", 0, 2, 1); test("abcde", 1, 3, "abcde", 0, 4, 1); test("abcde", 1, 3, "abcde", 0, 5, 1); test("abcde", 1, 3, "abcde", 0, 6, 1); test("abcde", 1, 3, "abcde", 1, 0, 3); test("abcde", 1, 3, "abcde", 1, 1, 2); test("abcde", 1, 3, "abcde", 1, 2, 1); } void test9() { test("abcde", 1, 3, "abcde", 1, 3, 0); test("abcde", 1, 3, "abcde", 1, 4, -1); test("abcde", 1, 3, "abcde", 1, 5, -1); test("abcde", 1, 3, "abcde", 2, 0, 3); test("abcde", 1, 3, "abcde", 2, 1, -1); test("abcde", 1, 3, "abcde", 2, 2, -1); test("abcde", 1, 3, "abcde", 2, 3, -1); test("abcde", 1, 3, "abcde", 2, 4, -1); test("abcde", 1, 3, "abcde", 4, 0, 3); test("abcde", 1, 3, "abcde", 4, 1, -3); test("abcde", 1, 3, "abcde", 4, 2, -3); test("abcde", 1, 3, "abcde", 5, 0, 3); test("abcde", 1, 3, "abcde", 5, 1, 3); test("abcde", 1, 3, "abcde", 6, 0, 0); test("abcde", 1, 3, "abcdefghij", 0, 0, 3); test("abcde", 1, 3, "abcdefghij", 0, 1, 1); test("abcde", 1, 3, "abcdefghij", 0, 5, 1); test("abcde", 1, 3, "abcdefghij", 0, 9, 1); test("abcde", 1, 3, "abcdefghij", 0, 10, 1); test("abcde", 1, 3, "abcdefghij", 0, 11, 1); test("abcde", 1, 3, "abcdefghij", 1, 0, 3); test("abcde", 1, 3, "abcdefghij", 1, 1, 2); test("abcde", 1, 3, "abcdefghij", 1, 4, -1); test("abcde", 1, 3, "abcdefghij", 1, 8, -5); test("abcde", 1, 3, "abcdefghij", 1, 9, -6); test("abcde", 1, 3, "abcdefghij", 1, 10, -6); test("abcde", 1, 3, "abcdefghij", 5, 0, 3); test("abcde", 1, 3, "abcdefghij", 5, 1, -4); test("abcde", 1, 3, "abcdefghij", 5, 2, -4); test("abcde", 1, 3, "abcdefghij", 5, 4, -4); test("abcde", 1, 3, "abcdefghij", 5, 5, -4); test("abcde", 1, 3, "abcdefghij", 5, 6, -4); test("abcde", 1, 3, "abcdefghij", 9, 0, 3); test("abcde", 1, 3, "abcdefghij", 9, 1, -8); test("abcde", 1, 3, "abcdefghij", 9, 2, -8); test("abcde", 1, 3, "abcdefghij", 10, 0, 3); test("abcde", 1, 3, "abcdefghij", 10, 1, 3); test("abcde", 1, 3, "abcdefghij", 11, 0, 0); test("abcde", 1, 3, "abcdefghijklmnopqrst", 0, 0, 3); test("abcde", 1, 3, "abcdefghijklmnopqrst", 0, 1, 1); test("abcde", 1, 3, "abcdefghijklmnopqrst", 0, 10, 1); test("abcde", 1, 3, "abcdefghijklmnopqrst", 0, 19, 1); test("abcde", 1, 3, "abcdefghijklmnopqrst", 0, 20, 1); test("abcde", 1, 3, "abcdefghijklmnopqrst", 0, 21, 1); test("abcde", 1, 3, "abcdefghijklmnopqrst", 1, 0, 3); test("abcde", 1, 3, "abcdefghijklmnopqrst", 1, 1, 2); test("abcde", 1, 3, "abcdefghijklmnopqrst", 1, 9, -6); test("abcde", 1, 3, "abcdefghijklmnopqrst", 1, 18, -15); test("abcde", 1, 3, "abcdefghijklmnopqrst", 1, 19, -16); test("abcde", 1, 3, "abcdefghijklmnopqrst", 1, 20, -16); test("abcde", 1, 3, "abcdefghijklmnopqrst", 10, 0, 3); test("abcde", 1, 3, "abcdefghijklmnopqrst", 10, 1, -9); test("abcde", 1, 3, "abcdefghijklmnopqrst", 10, 5, -9); test("abcde", 1, 3, "abcdefghijklmnopqrst", 10, 9, -9); test("abcde", 1, 3, "abcdefghijklmnopqrst", 10, 10, -9); test("abcde", 1, 3, "abcdefghijklmnopqrst", 10, 11, -9); test("abcde", 1, 3, "abcdefghijklmnopqrst", 19, 0, 3); test("abcde", 1, 3, "abcdefghijklmnopqrst", 19, 1, -18); test("abcde", 1, 3, "abcdefghijklmnopqrst", 19, 2, -18); test("abcde", 1, 3, "abcdefghijklmnopqrst", 20, 0, 3); test("abcde", 1, 3, "abcdefghijklmnopqrst", 20, 1, 3); test("abcde", 1, 3, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 1, 4, "", 0, 0, 4); test("abcde", 1, 4, "", 0, 1, 4); test("abcde", 1, 4, "", 1, 0, 0); test("abcde", 1, 4, "abcde", 0, 0, 4); test("abcde", 1, 4, "abcde", 0, 1, 1); test("abcde", 1, 4, "abcde", 0, 2, 1); test("abcde", 1, 4, "abcde", 0, 4, 1); test("abcde", 1, 4, "abcde", 0, 5, 1); test("abcde", 1, 4, "abcde", 0, 6, 1); test("abcde", 1, 4, "abcde", 1, 0, 4); test("abcde", 1, 4, "abcde", 1, 1, 3); test("abcde", 1, 4, "abcde", 1, 2, 2); test("abcde", 1, 4, "abcde", 1, 3, 1); test("abcde", 1, 4, "abcde", 1, 4, 0); test("abcde", 1, 4, "abcde", 1, 5, 0); test("abcde", 1, 4, "abcde", 2, 0, 4); test("abcde", 1, 4, "abcde", 2, 1, -1); test("abcde", 1, 4, "abcde", 2, 2, -1); test("abcde", 1, 4, "abcde", 2, 3, -1); test("abcde", 1, 4, "abcde", 2, 4, -1); test("abcde", 1, 4, "abcde", 4, 0, 4); test("abcde", 1, 4, "abcde", 4, 1, -3); test("abcde", 1, 4, "abcde", 4, 2, -3); test("abcde", 1, 4, "abcde", 5, 0, 4); test("abcde", 1, 4, "abcde", 5, 1, 4); test("abcde", 1, 4, "abcde", 6, 0, 0); test("abcde", 1, 4, "abcdefghij", 0, 0, 4); test("abcde", 1, 4, "abcdefghij", 0, 1, 1); test("abcde", 1, 4, "abcdefghij", 0, 5, 1); test("abcde", 1, 4, "abcdefghij", 0, 9, 1); test("abcde", 1, 4, "abcdefghij", 0, 10, 1); test("abcde", 1, 4, "abcdefghij", 0, 11, 1); test("abcde", 1, 4, "abcdefghij", 1, 0, 4); test("abcde", 1, 4, "abcdefghij", 1, 1, 3); test("abcde", 1, 4, "abcdefghij", 1, 4, 0); test("abcde", 1, 4, "abcdefghij", 1, 8, -4); test("abcde", 1, 4, "abcdefghij", 1, 9, -5); test("abcde", 1, 4, "abcdefghij", 1, 10, -5); } void test10() { test("abcde", 1, 4, "abcdefghij", 5, 0, 4); test("abcde", 1, 4, "abcdefghij", 5, 1, -4); test("abcde", 1, 4, "abcdefghij", 5, 2, -4); test("abcde", 1, 4, "abcdefghij", 5, 4, -4); test("abcde", 1, 4, "abcdefghij", 5, 5, -4); test("abcde", 1, 4, "abcdefghij", 5, 6, -4); test("abcde", 1, 4, "abcdefghij", 9, 0, 4); test("abcde", 1, 4, "abcdefghij", 9, 1, -8); test("abcde", 1, 4, "abcdefghij", 9, 2, -8); test("abcde", 1, 4, "abcdefghij", 10, 0, 4); test("abcde", 1, 4, "abcdefghij", 10, 1, 4); test("abcde", 1, 4, "abcdefghij", 11, 0, 0); test("abcde", 1, 4, "abcdefghijklmnopqrst", 0, 0, 4); test("abcde", 1, 4, "abcdefghijklmnopqrst", 0, 1, 1); test("abcde", 1, 4, "abcdefghijklmnopqrst", 0, 10, 1); test("abcde", 1, 4, "abcdefghijklmnopqrst", 0, 19, 1); test("abcde", 1, 4, "abcdefghijklmnopqrst", 0, 20, 1); test("abcde", 1, 4, "abcdefghijklmnopqrst", 0, 21, 1); test("abcde", 1, 4, "abcdefghijklmnopqrst", 1, 0, 4); test("abcde", 1, 4, "abcdefghijklmnopqrst", 1, 1, 3); test("abcde", 1, 4, "abcdefghijklmnopqrst", 1, 9, -5); test("abcde", 1, 4, "abcdefghijklmnopqrst", 1, 18, -14); test("abcde", 1, 4, "abcdefghijklmnopqrst", 1, 19, -15); test("abcde", 1, 4, "abcdefghijklmnopqrst", 1, 20, -15); test("abcde", 1, 4, "abcdefghijklmnopqrst", 10, 0, 4); test("abcde", 1, 4, "abcdefghijklmnopqrst", 10, 1, -9); test("abcde", 1, 4, "abcdefghijklmnopqrst", 10, 5, -9); test("abcde", 1, 4, "abcdefghijklmnopqrst", 10, 9, -9); test("abcde", 1, 4, "abcdefghijklmnopqrst", 10, 10, -9); test("abcde", 1, 4, "abcdefghijklmnopqrst", 10, 11, -9); test("abcde", 1, 4, "abcdefghijklmnopqrst", 19, 0, 4); test("abcde", 1, 4, "abcdefghijklmnopqrst", 19, 1, -18); test("abcde", 1, 4, "abcdefghijklmnopqrst", 19, 2, -18); test("abcde", 1, 4, "abcdefghijklmnopqrst", 20, 0, 4); test("abcde", 1, 4, "abcdefghijklmnopqrst", 20, 1, 4); test("abcde", 1, 4, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 1, 5, "", 0, 0, 4); test("abcde", 1, 5, "", 0, 1, 4); test("abcde", 1, 5, "", 1, 0, 0); test("abcde", 1, 5, "abcde", 0, 0, 4); test("abcde", 1, 5, "abcde", 0, 1, 1); test("abcde", 1, 5, "abcde", 0, 2, 1); test("abcde", 1, 5, "abcde", 0, 4, 1); test("abcde", 1, 5, "abcde", 0, 5, 1); test("abcde", 1, 5, "abcde", 0, 6, 1); test("abcde", 1, 5, "abcde", 1, 0, 4); test("abcde", 1, 5, "abcde", 1, 1, 3); test("abcde", 1, 5, "abcde", 1, 2, 2); test("abcde", 1, 5, "abcde", 1, 3, 1); test("abcde", 1, 5, "abcde", 1, 4, 0); test("abcde", 1, 5, "abcde", 1, 5, 0); test("abcde", 1, 5, "abcde", 2, 0, 4); test("abcde", 1, 5, "abcde", 2, 1, -1); test("abcde", 1, 5, "abcde", 2, 2, -1); test("abcde", 1, 5, "abcde", 2, 3, -1); test("abcde", 1, 5, "abcde", 2, 4, -1); test("abcde", 1, 5, "abcde", 4, 0, 4); test("abcde", 1, 5, "abcde", 4, 1, -3); test("abcde", 1, 5, "abcde", 4, 2, -3); test("abcde", 1, 5, "abcde", 5, 0, 4); test("abcde", 1, 5, "abcde", 5, 1, 4); test("abcde", 1, 5, "abcde", 6, 0, 0); test("abcde", 1, 5, "abcdefghij", 0, 0, 4); test("abcde", 1, 5, "abcdefghij", 0, 1, 1); test("abcde", 1, 5, "abcdefghij", 0, 5, 1); test("abcde", 1, 5, "abcdefghij", 0, 9, 1); test("abcde", 1, 5, "abcdefghij", 0, 10, 1); test("abcde", 1, 5, "abcdefghij", 0, 11, 1); test("abcde", 1, 5, "abcdefghij", 1, 0, 4); test("abcde", 1, 5, "abcdefghij", 1, 1, 3); test("abcde", 1, 5, "abcdefghij", 1, 4, 0); test("abcde", 1, 5, "abcdefghij", 1, 8, -4); test("abcde", 1, 5, "abcdefghij", 1, 9, -5); test("abcde", 1, 5, "abcdefghij", 1, 10, -5); test("abcde", 1, 5, "abcdefghij", 5, 0, 4); test("abcde", 1, 5, "abcdefghij", 5, 1, -4); test("abcde", 1, 5, "abcdefghij", 5, 2, -4); test("abcde", 1, 5, "abcdefghij", 5, 4, -4); test("abcde", 1, 5, "abcdefghij", 5, 5, -4); test("abcde", 1, 5, "abcdefghij", 5, 6, -4); test("abcde", 1, 5, "abcdefghij", 9, 0, 4); test("abcde", 1, 5, "abcdefghij", 9, 1, -8); test("abcde", 1, 5, "abcdefghij", 9, 2, -8); test("abcde", 1, 5, "abcdefghij", 10, 0, 4); test("abcde", 1, 5, "abcdefghij", 10, 1, 4); test("abcde", 1, 5, "abcdefghij", 11, 0, 0); test("abcde", 1, 5, "abcdefghijklmnopqrst", 0, 0, 4); test("abcde", 1, 5, "abcdefghijklmnopqrst", 0, 1, 1); test("abcde", 1, 5, "abcdefghijklmnopqrst", 0, 10, 1); test("abcde", 1, 5, "abcdefghijklmnopqrst", 0, 19, 1); test("abcde", 1, 5, "abcdefghijklmnopqrst", 0, 20, 1); test("abcde", 1, 5, "abcdefghijklmnopqrst", 0, 21, 1); test("abcde", 1, 5, "abcdefghijklmnopqrst", 1, 0, 4); test("abcde", 1, 5, "abcdefghijklmnopqrst", 1, 1, 3); test("abcde", 1, 5, "abcdefghijklmnopqrst", 1, 9, -5); test("abcde", 1, 5, "abcdefghijklmnopqrst", 1, 18, -14); test("abcde", 1, 5, "abcdefghijklmnopqrst", 1, 19, -15); test("abcde", 1, 5, "abcdefghijklmnopqrst", 1, 20, -15); test("abcde", 1, 5, "abcdefghijklmnopqrst", 10, 0, 4); test("abcde", 1, 5, "abcdefghijklmnopqrst", 10, 1, -9); } void test11() { test("abcde", 1, 5, "abcdefghijklmnopqrst", 10, 5, -9); test("abcde", 1, 5, "abcdefghijklmnopqrst", 10, 9, -9); test("abcde", 1, 5, "abcdefghijklmnopqrst", 10, 10, -9); test("abcde", 1, 5, "abcdefghijklmnopqrst", 10, 11, -9); test("abcde", 1, 5, "abcdefghijklmnopqrst", 19, 0, 4); test("abcde", 1, 5, "abcdefghijklmnopqrst", 19, 1, -18); test("abcde", 1, 5, "abcdefghijklmnopqrst", 19, 2, -18); test("abcde", 1, 5, "abcdefghijklmnopqrst", 20, 0, 4); test("abcde", 1, 5, "abcdefghijklmnopqrst", 20, 1, 4); test("abcde", 1, 5, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 2, 0, "", 0, 0, 0); test("abcde", 2, 0, "", 0, 1, 0); test("abcde", 2, 0, "", 1, 0, 0); test("abcde", 2, 0, "abcde", 0, 0, 0); test("abcde", 2, 0, "abcde", 0, 1, -1); test("abcde", 2, 0, "abcde", 0, 2, -2); test("abcde", 2, 0, "abcde", 0, 4, -4); test("abcde", 2, 0, "abcde", 0, 5, -5); test("abcde", 2, 0, "abcde", 0, 6, -5); test("abcde", 2, 0, "abcde", 1, 0, 0); test("abcde", 2, 0, "abcde", 1, 1, -1); test("abcde", 2, 0, "abcde", 1, 2, -2); test("abcde", 2, 0, "abcde", 1, 3, -3); test("abcde", 2, 0, "abcde", 1, 4, -4); test("abcde", 2, 0, "abcde", 1, 5, -4); test("abcde", 2, 0, "abcde", 2, 0, 0); test("abcde", 2, 0, "abcde", 2, 1, -1); test("abcde", 2, 0, "abcde", 2, 2, -2); test("abcde", 2, 0, "abcde", 2, 3, -3); test("abcde", 2, 0, "abcde", 2, 4, -3); test("abcde", 2, 0, "abcde", 4, 0, 0); test("abcde", 2, 0, "abcde", 4, 1, -1); test("abcde", 2, 0, "abcde", 4, 2, -1); test("abcde", 2, 0, "abcde", 5, 0, 0); test("abcde", 2, 0, "abcde", 5, 1, 0); test("abcde", 2, 0, "abcde", 6, 0, 0); test("abcde", 2, 0, "abcdefghij", 0, 0, 0); test("abcde", 2, 0, "abcdefghij", 0, 1, -1); test("abcde", 2, 0, "abcdefghij", 0, 5, -5); test("abcde", 2, 0, "abcdefghij", 0, 9, -9); test("abcde", 2, 0, "abcdefghij", 0, 10, -10); test("abcde", 2, 0, "abcdefghij", 0, 11, -10); test("abcde", 2, 0, "abcdefghij", 1, 0, 0); test("abcde", 2, 0, "abcdefghij", 1, 1, -1); test("abcde", 2, 0, "abcdefghij", 1, 4, -4); test("abcde", 2, 0, "abcdefghij", 1, 8, -8); test("abcde", 2, 0, "abcdefghij", 1, 9, -9); test("abcde", 2, 0, "abcdefghij", 1, 10, -9); test("abcde", 2, 0, "abcdefghij", 5, 0, 0); test("abcde", 2, 0, "abcdefghij", 5, 1, -1); test("abcde", 2, 0, "abcdefghij", 5, 2, -2); test("abcde", 2, 0, "abcdefghij", 5, 4, -4); test("abcde", 2, 0, "abcdefghij", 5, 5, -5); test("abcde", 2, 0, "abcdefghij", 5, 6, -5); test("abcde", 2, 0, "abcdefghij", 9, 0, 0); test("abcde", 2, 0, "abcdefghij", 9, 1, -1); test("abcde", 2, 0, "abcdefghij", 9, 2, -1); test("abcde", 2, 0, "abcdefghij", 10, 0, 0); test("abcde", 2, 0, "abcdefghij", 10, 1, 0); test("abcde", 2, 0, "abcdefghij", 11, 0, 0); test("abcde", 2, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcde", 2, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcde", 2, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcde", 2, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcde", 2, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcde", 2, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcde", 2, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcde", 2, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcde", 2, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcde", 2, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcde", 2, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcde", 2, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcde", 2, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcde", 2, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcde", 2, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcde", 2, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcde", 2, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcde", 2, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcde", 2, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcde", 2, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcde", 2, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcde", 2, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcde", 2, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcde", 2, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 2, 1, "", 0, 0, 1); test("abcde", 2, 1, "", 0, 1, 1); test("abcde", 2, 1, "", 1, 0, 0); test("abcde", 2, 1, "abcde", 0, 0, 1); test("abcde", 2, 1, "abcde", 0, 1, 2); test("abcde", 2, 1, "abcde", 0, 2, 2); test("abcde", 2, 1, "abcde", 0, 4, 2); test("abcde", 2, 1, "abcde", 0, 5, 2); test("abcde", 2, 1, "abcde", 0, 6, 2); test("abcde", 2, 1, "abcde", 1, 0, 1); test("abcde", 2, 1, "abcde", 1, 1, 1); test("abcde", 2, 1, "abcde", 1, 2, 1); test("abcde", 2, 1, "abcde", 1, 3, 1); test("abcde", 2, 1, "abcde", 1, 4, 1); test("abcde", 2, 1, "abcde", 1, 5, 1); test("abcde", 2, 1, "abcde", 2, 0, 1); } void test12() { test("abcde", 2, 1, "abcde", 2, 1, 0); test("abcde", 2, 1, "abcde", 2, 2, -1); test("abcde", 2, 1, "abcde", 2, 3, -2); test("abcde", 2, 1, "abcde", 2, 4, -2); test("abcde", 2, 1, "abcde", 4, 0, 1); test("abcde", 2, 1, "abcde", 4, 1, -2); test("abcde", 2, 1, "abcde", 4, 2, -2); test("abcde", 2, 1, "abcde", 5, 0, 1); test("abcde", 2, 1, "abcde", 5, 1, 1); test("abcde", 2, 1, "abcde", 6, 0, 0); test("abcde", 2, 1, "abcdefghij", 0, 0, 1); test("abcde", 2, 1, "abcdefghij", 0, 1, 2); test("abcde", 2, 1, "abcdefghij", 0, 5, 2); test("abcde", 2, 1, "abcdefghij", 0, 9, 2); test("abcde", 2, 1, "abcdefghij", 0, 10, 2); test("abcde", 2, 1, "abcdefghij", 0, 11, 2); test("abcde", 2, 1, "abcdefghij", 1, 0, 1); test("abcde", 2, 1, "abcdefghij", 1, 1, 1); test("abcde", 2, 1, "abcdefghij", 1, 4, 1); test("abcde", 2, 1, "abcdefghij", 1, 8, 1); test("abcde", 2, 1, "abcdefghij", 1, 9, 1); test("abcde", 2, 1, "abcdefghij", 1, 10, 1); test("abcde", 2, 1, "abcdefghij", 5, 0, 1); test("abcde", 2, 1, "abcdefghij", 5, 1, -3); test("abcde", 2, 1, "abcdefghij", 5, 2, -3); test("abcde", 2, 1, "abcdefghij", 5, 4, -3); test("abcde", 2, 1, "abcdefghij", 5, 5, -3); test("abcde", 2, 1, "abcdefghij", 5, 6, -3); test("abcde", 2, 1, "abcdefghij", 9, 0, 1); test("abcde", 2, 1, "abcdefghij", 9, 1, -7); test("abcde", 2, 1, "abcdefghij", 9, 2, -7); test("abcde", 2, 1, "abcdefghij", 10, 0, 1); test("abcde", 2, 1, "abcdefghij", 10, 1, 1); test("abcde", 2, 1, "abcdefghij", 11, 0, 0); test("abcde", 2, 1, "abcdefghijklmnopqrst", 0, 0, 1); test("abcde", 2, 1, "abcdefghijklmnopqrst", 0, 1, 2); test("abcde", 2, 1, "abcdefghijklmnopqrst", 0, 10, 2); test("abcde", 2, 1, "abcdefghijklmnopqrst", 0, 19, 2); test("abcde", 2, 1, "abcdefghijklmnopqrst", 0, 20, 2); test("abcde", 2, 1, "abcdefghijklmnopqrst", 0, 21, 2); test("abcde", 2, 1, "abcdefghijklmnopqrst", 1, 0, 1); test("abcde", 2, 1, "abcdefghijklmnopqrst", 1, 1, 1); test("abcde", 2, 1, "abcdefghijklmnopqrst", 1, 9, 1); test("abcde", 2, 1, "abcdefghijklmnopqrst", 1, 18, 1); test("abcde", 2, 1, "abcdefghijklmnopqrst", 1, 19, 1); test("abcde", 2, 1, "abcdefghijklmnopqrst", 1, 20, 1); test("abcde", 2, 1, "abcdefghijklmnopqrst", 10, 0, 1); test("abcde", 2, 1, "abcdefghijklmnopqrst", 10, 1, -8); test("abcde", 2, 1, "abcdefghijklmnopqrst", 10, 5, -8); test("abcde", 2, 1, "abcdefghijklmnopqrst", 10, 9, -8); test("abcde", 2, 1, "abcdefghijklmnopqrst", 10, 10, -8); test("abcde", 2, 1, "abcdefghijklmnopqrst", 10, 11, -8); test("abcde", 2, 1, "abcdefghijklmnopqrst", 19, 0, 1); test("abcde", 2, 1, "abcdefghijklmnopqrst", 19, 1, -17); test("abcde", 2, 1, "abcdefghijklmnopqrst", 19, 2, -17); test("abcde", 2, 1, "abcdefghijklmnopqrst", 20, 0, 1); test("abcde", 2, 1, "abcdefghijklmnopqrst", 20, 1, 1); test("abcde", 2, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 2, 2, "", 0, 0, 2); test("abcde", 2, 2, "", 0, 1, 2); test("abcde", 2, 2, "", 1, 0, 0); test("abcde", 2, 2, "abcde", 0, 0, 2); test("abcde", 2, 2, "abcde", 0, 1, 2); test("abcde", 2, 2, "abcde", 0, 2, 2); test("abcde", 2, 2, "abcde", 0, 4, 2); test("abcde", 2, 2, "abcde", 0, 5, 2); test("abcde", 2, 2, "abcde", 0, 6, 2); test("abcde", 2, 2, "abcde", 1, 0, 2); test("abcde", 2, 2, "abcde", 1, 1, 1); test("abcde", 2, 2, "abcde", 1, 2, 1); test("abcde", 2, 2, "abcde", 1, 3, 1); test("abcde", 2, 2, "abcde", 1, 4, 1); test("abcde", 2, 2, "abcde", 1, 5, 1); test("abcde", 2, 2, "abcde", 2, 0, 2); test("abcde", 2, 2, "abcde", 2, 1, 1); test("abcde", 2, 2, "abcde", 2, 2, 0); test("abcde", 2, 2, "abcde", 2, 3, -1); test("abcde", 2, 2, "abcde", 2, 4, -1); test("abcde", 2, 2, "abcde", 4, 0, 2); test("abcde", 2, 2, "abcde", 4, 1, -2); test("abcde", 2, 2, "abcde", 4, 2, -2); test("abcde", 2, 2, "abcde", 5, 0, 2); test("abcde", 2, 2, "abcde", 5, 1, 2); test("abcde", 2, 2, "abcde", 6, 0, 0); test("abcde", 2, 2, "abcdefghij", 0, 0, 2); test("abcde", 2, 2, "abcdefghij", 0, 1, 2); test("abcde", 2, 2, "abcdefghij", 0, 5, 2); test("abcde", 2, 2, "abcdefghij", 0, 9, 2); test("abcde", 2, 2, "abcdefghij", 0, 10, 2); test("abcde", 2, 2, "abcdefghij", 0, 11, 2); test("abcde", 2, 2, "abcdefghij", 1, 0, 2); test("abcde", 2, 2, "abcdefghij", 1, 1, 1); test("abcde", 2, 2, "abcdefghij", 1, 4, 1); test("abcde", 2, 2, "abcdefghij", 1, 8, 1); test("abcde", 2, 2, "abcdefghij", 1, 9, 1); test("abcde", 2, 2, "abcdefghij", 1, 10, 1); test("abcde", 2, 2, "abcdefghij", 5, 0, 2); test("abcde", 2, 2, "abcdefghij", 5, 1, -3); test("abcde", 2, 2, "abcdefghij", 5, 2, -3); test("abcde", 2, 2, "abcdefghij", 5, 4, -3); } void test13() { test("abcde", 2, 2, "abcdefghij", 5, 5, -3); test("abcde", 2, 2, "abcdefghij", 5, 6, -3); test("abcde", 2, 2, "abcdefghij", 9, 0, 2); test("abcde", 2, 2, "abcdefghij", 9, 1, -7); test("abcde", 2, 2, "abcdefghij", 9, 2, -7); test("abcde", 2, 2, "abcdefghij", 10, 0, 2); test("abcde", 2, 2, "abcdefghij", 10, 1, 2); test("abcde", 2, 2, "abcdefghij", 11, 0, 0); test("abcde", 2, 2, "abcdefghijklmnopqrst", 0, 0, 2); test("abcde", 2, 2, "abcdefghijklmnopqrst", 0, 1, 2); test("abcde", 2, 2, "abcdefghijklmnopqrst", 0, 10, 2); test("abcde", 2, 2, "abcdefghijklmnopqrst", 0, 19, 2); test("abcde", 2, 2, "abcdefghijklmnopqrst", 0, 20, 2); test("abcde", 2, 2, "abcdefghijklmnopqrst", 0, 21, 2); test("abcde", 2, 2, "abcdefghijklmnopqrst", 1, 0, 2); test("abcde", 2, 2, "abcdefghijklmnopqrst", 1, 1, 1); test("abcde", 2, 2, "abcdefghijklmnopqrst", 1, 9, 1); test("abcde", 2, 2, "abcdefghijklmnopqrst", 1, 18, 1); test("abcde", 2, 2, "abcdefghijklmnopqrst", 1, 19, 1); test("abcde", 2, 2, "abcdefghijklmnopqrst", 1, 20, 1); test("abcde", 2, 2, "abcdefghijklmnopqrst", 10, 0, 2); test("abcde", 2, 2, "abcdefghijklmnopqrst", 10, 1, -8); test("abcde", 2, 2, "abcdefghijklmnopqrst", 10, 5, -8); test("abcde", 2, 2, "abcdefghijklmnopqrst", 10, 9, -8); test("abcde", 2, 2, "abcdefghijklmnopqrst", 10, 10, -8); test("abcde", 2, 2, "abcdefghijklmnopqrst", 10, 11, -8); test("abcde", 2, 2, "abcdefghijklmnopqrst", 19, 0, 2); test("abcde", 2, 2, "abcdefghijklmnopqrst", 19, 1, -17); test("abcde", 2, 2, "abcdefghijklmnopqrst", 19, 2, -17); test("abcde", 2, 2, "abcdefghijklmnopqrst", 20, 0, 2); test("abcde", 2, 2, "abcdefghijklmnopqrst", 20, 1, 2); test("abcde", 2, 2, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 2, 3, "", 0, 0, 3); test("abcde", 2, 3, "", 0, 1, 3); test("abcde", 2, 3, "", 1, 0, 0); test("abcde", 2, 3, "abcde", 0, 0, 3); test("abcde", 2, 3, "abcde", 0, 1, 2); test("abcde", 2, 3, "abcde", 0, 2, 2); test("abcde", 2, 3, "abcde", 0, 4, 2); test("abcde", 2, 3, "abcde", 0, 5, 2); test("abcde", 2, 3, "abcde", 0, 6, 2); test("abcde", 2, 3, "abcde", 1, 0, 3); test("abcde", 2, 3, "abcde", 1, 1, 1); test("abcde", 2, 3, "abcde", 1, 2, 1); test("abcde", 2, 3, "abcde", 1, 3, 1); test("abcde", 2, 3, "abcde", 1, 4, 1); test("abcde", 2, 3, "abcde", 1, 5, 1); test("abcde", 2, 3, "abcde", 2, 0, 3); test("abcde", 2, 3, "abcde", 2, 1, 2); test("abcde", 2, 3, "abcde", 2, 2, 1); test("abcde", 2, 3, "abcde", 2, 3, 0); test("abcde", 2, 3, "abcde", 2, 4, 0); test("abcde", 2, 3, "abcde", 4, 0, 3); test("abcde", 2, 3, "abcde", 4, 1, -2); test("abcde", 2, 3, "abcde", 4, 2, -2); test("abcde", 2, 3, "abcde", 5, 0, 3); test("abcde", 2, 3, "abcde", 5, 1, 3); test("abcde", 2, 3, "abcde", 6, 0, 0); test("abcde", 2, 3, "abcdefghij", 0, 0, 3); test("abcde", 2, 3, "abcdefghij", 0, 1, 2); test("abcde", 2, 3, "abcdefghij", 0, 5, 2); test("abcde", 2, 3, "abcdefghij", 0, 9, 2); test("abcde", 2, 3, "abcdefghij", 0, 10, 2); test("abcde", 2, 3, "abcdefghij", 0, 11, 2); test("abcde", 2, 3, "abcdefghij", 1, 0, 3); test("abcde", 2, 3, "abcdefghij", 1, 1, 1); test("abcde", 2, 3, "abcdefghij", 1, 4, 1); test("abcde", 2, 3, "abcdefghij", 1, 8, 1); test("abcde", 2, 3, "abcdefghij", 1, 9, 1); test("abcde", 2, 3, "abcdefghij", 1, 10, 1); test("abcde", 2, 3, "abcdefghij", 5, 0, 3); test("abcde", 2, 3, "abcdefghij", 5, 1, -3); test("abcde", 2, 3, "abcdefghij", 5, 2, -3); test("abcde", 2, 3, "abcdefghij", 5, 4, -3); test("abcde", 2, 3, "abcdefghij", 5, 5, -3); test("abcde", 2, 3, "abcdefghij", 5, 6, -3); test("abcde", 2, 3, "abcdefghij", 9, 0, 3); test("abcde", 2, 3, "abcdefghij", 9, 1, -7); test("abcde", 2, 3, "abcdefghij", 9, 2, -7); test("abcde", 2, 3, "abcdefghij", 10, 0, 3); test("abcde", 2, 3, "abcdefghij", 10, 1, 3); test("abcde", 2, 3, "abcdefghij", 11, 0, 0); test("abcde", 2, 3, "abcdefghijklmnopqrst", 0, 0, 3); test("abcde", 2, 3, "abcdefghijklmnopqrst", 0, 1, 2); test("abcde", 2, 3, "abcdefghijklmnopqrst", 0, 10, 2); test("abcde", 2, 3, "abcdefghijklmnopqrst", 0, 19, 2); test("abcde", 2, 3, "abcdefghijklmnopqrst", 0, 20, 2); test("abcde", 2, 3, "abcdefghijklmnopqrst", 0, 21, 2); test("abcde", 2, 3, "abcdefghijklmnopqrst", 1, 0, 3); test("abcde", 2, 3, "abcdefghijklmnopqrst", 1, 1, 1); test("abcde", 2, 3, "abcdefghijklmnopqrst", 1, 9, 1); test("abcde", 2, 3, "abcdefghijklmnopqrst", 1, 18, 1); test("abcde", 2, 3, "abcdefghijklmnopqrst", 1, 19, 1); test("abcde", 2, 3, "abcdefghijklmnopqrst", 1, 20, 1); test("abcde", 2, 3, "abcdefghijklmnopqrst", 10, 0, 3); test("abcde", 2, 3, "abcdefghijklmnopqrst", 10, 1, -8); test("abcde", 2, 3, "abcdefghijklmnopqrst", 10, 5, -8); test("abcde", 2, 3, "abcdefghijklmnopqrst", 10, 9, -8); test("abcde", 2, 3, "abcdefghijklmnopqrst", 10, 10, -8); test("abcde", 2, 3, "abcdefghijklmnopqrst", 10, 11, -8); } void test14() { test("abcde", 2, 3, "abcdefghijklmnopqrst", 19, 0, 3); test("abcde", 2, 3, "abcdefghijklmnopqrst", 19, 1, -17); test("abcde", 2, 3, "abcdefghijklmnopqrst", 19, 2, -17); test("abcde", 2, 3, "abcdefghijklmnopqrst", 20, 0, 3); test("abcde", 2, 3, "abcdefghijklmnopqrst", 20, 1, 3); test("abcde", 2, 3, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 2, 4, "", 0, 0, 3); test("abcde", 2, 4, "", 0, 1, 3); test("abcde", 2, 4, "", 1, 0, 0); test("abcde", 2, 4, "abcde", 0, 0, 3); test("abcde", 2, 4, "abcde", 0, 1, 2); test("abcde", 2, 4, "abcde", 0, 2, 2); test("abcde", 2, 4, "abcde", 0, 4, 2); test("abcde", 2, 4, "abcde", 0, 5, 2); test("abcde", 2, 4, "abcde", 0, 6, 2); test("abcde", 2, 4, "abcde", 1, 0, 3); test("abcde", 2, 4, "abcde", 1, 1, 1); test("abcde", 2, 4, "abcde", 1, 2, 1); test("abcde", 2, 4, "abcde", 1, 3, 1); test("abcde", 2, 4, "abcde", 1, 4, 1); test("abcde", 2, 4, "abcde", 1, 5, 1); test("abcde", 2, 4, "abcde", 2, 0, 3); test("abcde", 2, 4, "abcde", 2, 1, 2); test("abcde", 2, 4, "abcde", 2, 2, 1); test("abcde", 2, 4, "abcde", 2, 3, 0); test("abcde", 2, 4, "abcde", 2, 4, 0); test("abcde", 2, 4, "abcde", 4, 0, 3); test("abcde", 2, 4, "abcde", 4, 1, -2); test("abcde", 2, 4, "abcde", 4, 2, -2); test("abcde", 2, 4, "abcde", 5, 0, 3); test("abcde", 2, 4, "abcde", 5, 1, 3); test("abcde", 2, 4, "abcde", 6, 0, 0); test("abcde", 2, 4, "abcdefghij", 0, 0, 3); test("abcde", 2, 4, "abcdefghij", 0, 1, 2); test("abcde", 2, 4, "abcdefghij", 0, 5, 2); test("abcde", 2, 4, "abcdefghij", 0, 9, 2); test("abcde", 2, 4, "abcdefghij", 0, 10, 2); test("abcde", 2, 4, "abcdefghij", 0, 11, 2); test("abcde", 2, 4, "abcdefghij", 1, 0, 3); test("abcde", 2, 4, "abcdefghij", 1, 1, 1); test("abcde", 2, 4, "abcdefghij", 1, 4, 1); test("abcde", 2, 4, "abcdefghij", 1, 8, 1); test("abcde", 2, 4, "abcdefghij", 1, 9, 1); test("abcde", 2, 4, "abcdefghij", 1, 10, 1); test("abcde", 2, 4, "abcdefghij", 5, 0, 3); test("abcde", 2, 4, "abcdefghij", 5, 1, -3); test("abcde", 2, 4, "abcdefghij", 5, 2, -3); test("abcde", 2, 4, "abcdefghij", 5, 4, -3); test("abcde", 2, 4, "abcdefghij", 5, 5, -3); test("abcde", 2, 4, "abcdefghij", 5, 6, -3); test("abcde", 2, 4, "abcdefghij", 9, 0, 3); test("abcde", 2, 4, "abcdefghij", 9, 1, -7); test("abcde", 2, 4, "abcdefghij", 9, 2, -7); test("abcde", 2, 4, "abcdefghij", 10, 0, 3); test("abcde", 2, 4, "abcdefghij", 10, 1, 3); test("abcde", 2, 4, "abcdefghij", 11, 0, 0); test("abcde", 2, 4, "abcdefghijklmnopqrst", 0, 0, 3); test("abcde", 2, 4, "abcdefghijklmnopqrst", 0, 1, 2); test("abcde", 2, 4, "abcdefghijklmnopqrst", 0, 10, 2); test("abcde", 2, 4, "abcdefghijklmnopqrst", 0, 19, 2); test("abcde", 2, 4, "abcdefghijklmnopqrst", 0, 20, 2); test("abcde", 2, 4, "abcdefghijklmnopqrst", 0, 21, 2); test("abcde", 2, 4, "abcdefghijklmnopqrst", 1, 0, 3); test("abcde", 2, 4, "abcdefghijklmnopqrst", 1, 1, 1); test("abcde", 2, 4, "abcdefghijklmnopqrst", 1, 9, 1); test("abcde", 2, 4, "abcdefghijklmnopqrst", 1, 18, 1); test("abcde", 2, 4, "abcdefghijklmnopqrst", 1, 19, 1); test("abcde", 2, 4, "abcdefghijklmnopqrst", 1, 20, 1); test("abcde", 2, 4, "abcdefghijklmnopqrst", 10, 0, 3); test("abcde", 2, 4, "abcdefghijklmnopqrst", 10, 1, -8); test("abcde", 2, 4, "abcdefghijklmnopqrst", 10, 5, -8); test("abcde", 2, 4, "abcdefghijklmnopqrst", 10, 9, -8); test("abcde", 2, 4, "abcdefghijklmnopqrst", 10, 10, -8); test("abcde", 2, 4, "abcdefghijklmnopqrst", 10, 11, -8); test("abcde", 2, 4, "abcdefghijklmnopqrst", 19, 0, 3); test("abcde", 2, 4, "abcdefghijklmnopqrst", 19, 1, -17); test("abcde", 2, 4, "abcdefghijklmnopqrst", 19, 2, -17); test("abcde", 2, 4, "abcdefghijklmnopqrst", 20, 0, 3); test("abcde", 2, 4, "abcdefghijklmnopqrst", 20, 1, 3); test("abcde", 2, 4, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 4, 0, "", 0, 0, 0); test("abcde", 4, 0, "", 0, 1, 0); test("abcde", 4, 0, "", 1, 0, 0); test("abcde", 4, 0, "abcde", 0, 0, 0); test("abcde", 4, 0, "abcde", 0, 1, -1); test("abcde", 4, 0, "abcde", 0, 2, -2); test("abcde", 4, 0, "abcde", 0, 4, -4); test("abcde", 4, 0, "abcde", 0, 5, -5); test("abcde", 4, 0, "abcde", 0, 6, -5); test("abcde", 4, 0, "abcde", 1, 0, 0); test("abcde", 4, 0, "abcde", 1, 1, -1); test("abcde", 4, 0, "abcde", 1, 2, -2); test("abcde", 4, 0, "abcde", 1, 3, -3); test("abcde", 4, 0, "abcde", 1, 4, -4); test("abcde", 4, 0, "abcde", 1, 5, -4); test("abcde", 4, 0, "abcde", 2, 0, 0); test("abcde", 4, 0, "abcde", 2, 1, -1); test("abcde", 4, 0, "abcde", 2, 2, -2); test("abcde", 4, 0, "abcde", 2, 3, -3); test("abcde", 4, 0, "abcde", 2, 4, -3); } void test15() { test("abcde", 4, 0, "abcde", 4, 0, 0); test("abcde", 4, 0, "abcde", 4, 1, -1); test("abcde", 4, 0, "abcde", 4, 2, -1); test("abcde", 4, 0, "abcde", 5, 0, 0); test("abcde", 4, 0, "abcde", 5, 1, 0); test("abcde", 4, 0, "abcde", 6, 0, 0); test("abcde", 4, 0, "abcdefghij", 0, 0, 0); test("abcde", 4, 0, "abcdefghij", 0, 1, -1); test("abcde", 4, 0, "abcdefghij", 0, 5, -5); test("abcde", 4, 0, "abcdefghij", 0, 9, -9); test("abcde", 4, 0, "abcdefghij", 0, 10, -10); test("abcde", 4, 0, "abcdefghij", 0, 11, -10); test("abcde", 4, 0, "abcdefghij", 1, 0, 0); test("abcde", 4, 0, "abcdefghij", 1, 1, -1); test("abcde", 4, 0, "abcdefghij", 1, 4, -4); test("abcde", 4, 0, "abcdefghij", 1, 8, -8); test("abcde", 4, 0, "abcdefghij", 1, 9, -9); test("abcde", 4, 0, "abcdefghij", 1, 10, -9); test("abcde", 4, 0, "abcdefghij", 5, 0, 0); test("abcde", 4, 0, "abcdefghij", 5, 1, -1); test("abcde", 4, 0, "abcdefghij", 5, 2, -2); test("abcde", 4, 0, "abcdefghij", 5, 4, -4); test("abcde", 4, 0, "abcdefghij", 5, 5, -5); test("abcde", 4, 0, "abcdefghij", 5, 6, -5); test("abcde", 4, 0, "abcdefghij", 9, 0, 0); test("abcde", 4, 0, "abcdefghij", 9, 1, -1); test("abcde", 4, 0, "abcdefghij", 9, 2, -1); test("abcde", 4, 0, "abcdefghij", 10, 0, 0); test("abcde", 4, 0, "abcdefghij", 10, 1, 0); test("abcde", 4, 0, "abcdefghij", 11, 0, 0); test("abcde", 4, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcde", 4, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcde", 4, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcde", 4, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcde", 4, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcde", 4, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcde", 4, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcde", 4, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcde", 4, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcde", 4, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcde", 4, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcde", 4, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcde", 4, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcde", 4, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcde", 4, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcde", 4, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcde", 4, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcde", 4, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcde", 4, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcde", 4, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcde", 4, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcde", 4, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcde", 4, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcde", 4, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 4, 1, "", 0, 0, 1); test("abcde", 4, 1, "", 0, 1, 1); test("abcde", 4, 1, "", 1, 0, 0); test("abcde", 4, 1, "abcde", 0, 0, 1); test("abcde", 4, 1, "abcde", 0, 1, 4); test("abcde", 4, 1, "abcde", 0, 2, 4); test("abcde", 4, 1, "abcde", 0, 4, 4); test("abcde", 4, 1, "abcde", 0, 5, 4); test("abcde", 4, 1, "abcde", 0, 6, 4); test("abcde", 4, 1, "abcde", 1, 0, 1); test("abcde", 4, 1, "abcde", 1, 1, 3); test("abcde", 4, 1, "abcde", 1, 2, 3); test("abcde", 4, 1, "abcde", 1, 3, 3); test("abcde", 4, 1, "abcde", 1, 4, 3); test("abcde", 4, 1, "abcde", 1, 5, 3); test("abcde", 4, 1, "abcde", 2, 0, 1); test("abcde", 4, 1, "abcde", 2, 1, 2); test("abcde", 4, 1, "abcde", 2, 2, 2); test("abcde", 4, 1, "abcde", 2, 3, 2); test("abcde", 4, 1, "abcde", 2, 4, 2); test("abcde", 4, 1, "abcde", 4, 0, 1); test("abcde", 4, 1, "abcde", 4, 1, 0); test("abcde", 4, 1, "abcde", 4, 2, 0); test("abcde", 4, 1, "abcde", 5, 0, 1); test("abcde", 4, 1, "abcde", 5, 1, 1); test("abcde", 4, 1, "abcde", 6, 0, 0); test("abcde", 4, 1, "abcdefghij", 0, 0, 1); test("abcde", 4, 1, "abcdefghij", 0, 1, 4); test("abcde", 4, 1, "abcdefghij", 0, 5, 4); test("abcde", 4, 1, "abcdefghij", 0, 9, 4); test("abcde", 4, 1, "abcdefghij", 0, 10, 4); test("abcde", 4, 1, "abcdefghij", 0, 11, 4); test("abcde", 4, 1, "abcdefghij", 1, 0, 1); test("abcde", 4, 1, "abcdefghij", 1, 1, 3); test("abcde", 4, 1, "abcdefghij", 1, 4, 3); test("abcde", 4, 1, "abcdefghij", 1, 8, 3); test("abcde", 4, 1, "abcdefghij", 1, 9, 3); test("abcde", 4, 1, "abcdefghij", 1, 10, 3); test("abcde", 4, 1, "abcdefghij", 5, 0, 1); test("abcde", 4, 1, "abcdefghij", 5, 1, -1); test("abcde", 4, 1, "abcdefghij", 5, 2, -1); test("abcde", 4, 1, "abcdefghij", 5, 4, -1); test("abcde", 4, 1, "abcdefghij", 5, 5, -1); test("abcde", 4, 1, "abcdefghij", 5, 6, -1); test("abcde", 4, 1, "abcdefghij", 9, 0, 1); test("abcde", 4, 1, "abcdefghij", 9, 1, -5); } void test16() { test("abcde", 4, 1, "abcdefghij", 9, 2, -5); test("abcde", 4, 1, "abcdefghij", 10, 0, 1); test("abcde", 4, 1, "abcdefghij", 10, 1, 1); test("abcde", 4, 1, "abcdefghij", 11, 0, 0); test("abcde", 4, 1, "abcdefghijklmnopqrst", 0, 0, 1); test("abcde", 4, 1, "abcdefghijklmnopqrst", 0, 1, 4); test("abcde", 4, 1, "abcdefghijklmnopqrst", 0, 10, 4); test("abcde", 4, 1, "abcdefghijklmnopqrst", 0, 19, 4); test("abcde", 4, 1, "abcdefghijklmnopqrst", 0, 20, 4); test("abcde", 4, 1, "abcdefghijklmnopqrst", 0, 21, 4); test("abcde", 4, 1, "abcdefghijklmnopqrst", 1, 0, 1); test("abcde", 4, 1, "abcdefghijklmnopqrst", 1, 1, 3); test("abcde", 4, 1, "abcdefghijklmnopqrst", 1, 9, 3); test("abcde", 4, 1, "abcdefghijklmnopqrst", 1, 18, 3); test("abcde", 4, 1, "abcdefghijklmnopqrst", 1, 19, 3); test("abcde", 4, 1, "abcdefghijklmnopqrst", 1, 20, 3); test("abcde", 4, 1, "abcdefghijklmnopqrst", 10, 0, 1); test("abcde", 4, 1, "abcdefghijklmnopqrst", 10, 1, -6); test("abcde", 4, 1, "abcdefghijklmnopqrst", 10, 5, -6); test("abcde", 4, 1, "abcdefghijklmnopqrst", 10, 9, -6); test("abcde", 4, 1, "abcdefghijklmnopqrst", 10, 10, -6); test("abcde", 4, 1, "abcdefghijklmnopqrst", 10, 11, -6); test("abcde", 4, 1, "abcdefghijklmnopqrst", 19, 0, 1); test("abcde", 4, 1, "abcdefghijklmnopqrst", 19, 1, -15); test("abcde", 4, 1, "abcdefghijklmnopqrst", 19, 2, -15); test("abcde", 4, 1, "abcdefghijklmnopqrst", 20, 0, 1); test("abcde", 4, 1, "abcdefghijklmnopqrst", 20, 1, 1); test("abcde", 4, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 4, 2, "", 0, 0, 1); test("abcde", 4, 2, "", 0, 1, 1); test("abcde", 4, 2, "", 1, 0, 0); test("abcde", 4, 2, "abcde", 0, 0, 1); test("abcde", 4, 2, "abcde", 0, 1, 4); test("abcde", 4, 2, "abcde", 0, 2, 4); test("abcde", 4, 2, "abcde", 0, 4, 4); test("abcde", 4, 2, "abcde", 0, 5, 4); test("abcde", 4, 2, "abcde", 0, 6, 4); test("abcde", 4, 2, "abcde", 1, 0, 1); test("abcde", 4, 2, "abcde", 1, 1, 3); test("abcde", 4, 2, "abcde", 1, 2, 3); test("abcde", 4, 2, "abcde", 1, 3, 3); test("abcde", 4, 2, "abcde", 1, 4, 3); test("abcde", 4, 2, "abcde", 1, 5, 3); test("abcde", 4, 2, "abcde", 2, 0, 1); test("abcde", 4, 2, "abcde", 2, 1, 2); test("abcde", 4, 2, "abcde", 2, 2, 2); test("abcde", 4, 2, "abcde", 2, 3, 2); test("abcde", 4, 2, "abcde", 2, 4, 2); test("abcde", 4, 2, "abcde", 4, 0, 1); test("abcde", 4, 2, "abcde", 4, 1, 0); test("abcde", 4, 2, "abcde", 4, 2, 0); test("abcde", 4, 2, "abcde", 5, 0, 1); test("abcde", 4, 2, "abcde", 5, 1, 1); test("abcde", 4, 2, "abcde", 6, 0, 0); test("abcde", 4, 2, "abcdefghij", 0, 0, 1); test("abcde", 4, 2, "abcdefghij", 0, 1, 4); test("abcde", 4, 2, "abcdefghij", 0, 5, 4); test("abcde", 4, 2, "abcdefghij", 0, 9, 4); test("abcde", 4, 2, "abcdefghij", 0, 10, 4); test("abcde", 4, 2, "abcdefghij", 0, 11, 4); test("abcde", 4, 2, "abcdefghij", 1, 0, 1); test("abcde", 4, 2, "abcdefghij", 1, 1, 3); test("abcde", 4, 2, "abcdefghij", 1, 4, 3); test("abcde", 4, 2, "abcdefghij", 1, 8, 3); test("abcde", 4, 2, "abcdefghij", 1, 9, 3); test("abcde", 4, 2, "abcdefghij", 1, 10, 3); test("abcde", 4, 2, "abcdefghij", 5, 0, 1); test("abcde", 4, 2, "abcdefghij", 5, 1, -1); test("abcde", 4, 2, "abcdefghij", 5, 2, -1); test("abcde", 4, 2, "abcdefghij", 5, 4, -1); test("abcde", 4, 2, "abcdefghij", 5, 5, -1); test("abcde", 4, 2, "abcdefghij", 5, 6, -1); test("abcde", 4, 2, "abcdefghij", 9, 0, 1); test("abcde", 4, 2, "abcdefghij", 9, 1, -5); test("abcde", 4, 2, "abcdefghij", 9, 2, -5); test("abcde", 4, 2, "abcdefghij", 10, 0, 1); test("abcde", 4, 2, "abcdefghij", 10, 1, 1); test("abcde", 4, 2, "abcdefghij", 11, 0, 0); test("abcde", 4, 2, "abcdefghijklmnopqrst", 0, 0, 1); test("abcde", 4, 2, "abcdefghijklmnopqrst", 0, 1, 4); test("abcde", 4, 2, "abcdefghijklmnopqrst", 0, 10, 4); test("abcde", 4, 2, "abcdefghijklmnopqrst", 0, 19, 4); test("abcde", 4, 2, "abcdefghijklmnopqrst", 0, 20, 4); test("abcde", 4, 2, "abcdefghijklmnopqrst", 0, 21, 4); test("abcde", 4, 2, "abcdefghijklmnopqrst", 1, 0, 1); test("abcde", 4, 2, "abcdefghijklmnopqrst", 1, 1, 3); test("abcde", 4, 2, "abcdefghijklmnopqrst", 1, 9, 3); test("abcde", 4, 2, "abcdefghijklmnopqrst", 1, 18, 3); test("abcde", 4, 2, "abcdefghijklmnopqrst", 1, 19, 3); test("abcde", 4, 2, "abcdefghijklmnopqrst", 1, 20, 3); test("abcde", 4, 2, "abcdefghijklmnopqrst", 10, 0, 1); test("abcde", 4, 2, "abcdefghijklmnopqrst", 10, 1, -6); test("abcde", 4, 2, "abcdefghijklmnopqrst", 10, 5, -6); test("abcde", 4, 2, "abcdefghijklmnopqrst", 10, 9, -6); test("abcde", 4, 2, "abcdefghijklmnopqrst", 10, 10, -6); test("abcde", 4, 2, "abcdefghijklmnopqrst", 10, 11, -6); test("abcde", 4, 2, "abcdefghijklmnopqrst", 19, 0, 1); test("abcde", 4, 2, "abcdefghijklmnopqrst", 19, 1, -15); test("abcde", 4, 2, "abcdefghijklmnopqrst", 19, 2, -15); test("abcde", 4, 2, "abcdefghijklmnopqrst", 20, 0, 1); } void test17() { test("abcde", 4, 2, "abcdefghijklmnopqrst", 20, 1, 1); test("abcde", 4, 2, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 5, 0, "", 0, 0, 0); test("abcde", 5, 0, "", 0, 1, 0); test("abcde", 5, 0, "", 1, 0, 0); test("abcde", 5, 0, "abcde", 0, 0, 0); test("abcde", 5, 0, "abcde", 0, 1, -1); test("abcde", 5, 0, "abcde", 0, 2, -2); test("abcde", 5, 0, "abcde", 0, 4, -4); test("abcde", 5, 0, "abcde", 0, 5, -5); test("abcde", 5, 0, "abcde", 0, 6, -5); test("abcde", 5, 0, "abcde", 1, 0, 0); test("abcde", 5, 0, "abcde", 1, 1, -1); test("abcde", 5, 0, "abcde", 1, 2, -2); test("abcde", 5, 0, "abcde", 1, 3, -3); test("abcde", 5, 0, "abcde", 1, 4, -4); test("abcde", 5, 0, "abcde", 1, 5, -4); test("abcde", 5, 0, "abcde", 2, 0, 0); test("abcde", 5, 0, "abcde", 2, 1, -1); test("abcde", 5, 0, "abcde", 2, 2, -2); test("abcde", 5, 0, "abcde", 2, 3, -3); test("abcde", 5, 0, "abcde", 2, 4, -3); test("abcde", 5, 0, "abcde", 4, 0, 0); test("abcde", 5, 0, "abcde", 4, 1, -1); test("abcde", 5, 0, "abcde", 4, 2, -1); test("abcde", 5, 0, "abcde", 5, 0, 0); test("abcde", 5, 0, "abcde", 5, 1, 0); test("abcde", 5, 0, "abcde", 6, 0, 0); test("abcde", 5, 0, "abcdefghij", 0, 0, 0); test("abcde", 5, 0, "abcdefghij", 0, 1, -1); test("abcde", 5, 0, "abcdefghij", 0, 5, -5); test("abcde", 5, 0, "abcdefghij", 0, 9, -9); test("abcde", 5, 0, "abcdefghij", 0, 10, -10); test("abcde", 5, 0, "abcdefghij", 0, 11, -10); test("abcde", 5, 0, "abcdefghij", 1, 0, 0); test("abcde", 5, 0, "abcdefghij", 1, 1, -1); test("abcde", 5, 0, "abcdefghij", 1, 4, -4); test("abcde", 5, 0, "abcdefghij", 1, 8, -8); test("abcde", 5, 0, "abcdefghij", 1, 9, -9); test("abcde", 5, 0, "abcdefghij", 1, 10, -9); test("abcde", 5, 0, "abcdefghij", 5, 0, 0); test("abcde", 5, 0, "abcdefghij", 5, 1, -1); test("abcde", 5, 0, "abcdefghij", 5, 2, -2); test("abcde", 5, 0, "abcdefghij", 5, 4, -4); test("abcde", 5, 0, "abcdefghij", 5, 5, -5); test("abcde", 5, 0, "abcdefghij", 5, 6, -5); test("abcde", 5, 0, "abcdefghij", 9, 0, 0); test("abcde", 5, 0, "abcdefghij", 9, 1, -1); test("abcde", 5, 0, "abcdefghij", 9, 2, -1); test("abcde", 5, 0, "abcdefghij", 10, 0, 0); test("abcde", 5, 0, "abcdefghij", 10, 1, 0); test("abcde", 5, 0, "abcdefghij", 11, 0, 0); test("abcde", 5, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcde", 5, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcde", 5, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcde", 5, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcde", 5, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcde", 5, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcde", 5, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcde", 5, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcde", 5, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcde", 5, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcde", 5, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcde", 5, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcde", 5, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcde", 5, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcde", 5, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcde", 5, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcde", 5, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcde", 5, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcde", 5, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcde", 5, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcde", 5, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcde", 5, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcde", 5, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcde", 5, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 5, 1, "", 0, 0, 0); test("abcde", 5, 1, "", 0, 1, 0); test("abcde", 5, 1, "", 1, 0, 0); test("abcde", 5, 1, "abcde", 0, 0, 0); test("abcde", 5, 1, "abcde", 0, 1, -1); test("abcde", 5, 1, "abcde", 0, 2, -2); test("abcde", 5, 1, "abcde", 0, 4, -4); test("abcde", 5, 1, "abcde", 0, 5, -5); test("abcde", 5, 1, "abcde", 0, 6, -5); test("abcde", 5, 1, "abcde", 1, 0, 0); test("abcde", 5, 1, "abcde", 1, 1, -1); test("abcde", 5, 1, "abcde", 1, 2, -2); test("abcde", 5, 1, "abcde", 1, 3, -3); test("abcde", 5, 1, "abcde", 1, 4, -4); test("abcde", 5, 1, "abcde", 1, 5, -4); test("abcde", 5, 1, "abcde", 2, 0, 0); test("abcde", 5, 1, "abcde", 2, 1, -1); test("abcde", 5, 1, "abcde", 2, 2, -2); test("abcde", 5, 1, "abcde", 2, 3, -3); test("abcde", 5, 1, "abcde", 2, 4, -3); test("abcde", 5, 1, "abcde", 4, 0, 0); test("abcde", 5, 1, "abcde", 4, 1, -1); test("abcde", 5, 1, "abcde", 4, 2, -1); test("abcde", 5, 1, "abcde", 5, 0, 0); } void test18() { test("abcde", 5, 1, "abcde", 5, 1, 0); test("abcde", 5, 1, "abcde", 6, 0, 0); test("abcde", 5, 1, "abcdefghij", 0, 0, 0); test("abcde", 5, 1, "abcdefghij", 0, 1, -1); test("abcde", 5, 1, "abcdefghij", 0, 5, -5); test("abcde", 5, 1, "abcdefghij", 0, 9, -9); test("abcde", 5, 1, "abcdefghij", 0, 10, -10); test("abcde", 5, 1, "abcdefghij", 0, 11, -10); test("abcde", 5, 1, "abcdefghij", 1, 0, 0); test("abcde", 5, 1, "abcdefghij", 1, 1, -1); test("abcde", 5, 1, "abcdefghij", 1, 4, -4); test("abcde", 5, 1, "abcdefghij", 1, 8, -8); test("abcde", 5, 1, "abcdefghij", 1, 9, -9); test("abcde", 5, 1, "abcdefghij", 1, 10, -9); test("abcde", 5, 1, "abcdefghij", 5, 0, 0); test("abcde", 5, 1, "abcdefghij", 5, 1, -1); test("abcde", 5, 1, "abcdefghij", 5, 2, -2); test("abcde", 5, 1, "abcdefghij", 5, 4, -4); test("abcde", 5, 1, "abcdefghij", 5, 5, -5); test("abcde", 5, 1, "abcdefghij", 5, 6, -5); test("abcde", 5, 1, "abcdefghij", 9, 0, 0); test("abcde", 5, 1, "abcdefghij", 9, 1, -1); test("abcde", 5, 1, "abcdefghij", 9, 2, -1); test("abcde", 5, 1, "abcdefghij", 10, 0, 0); test("abcde", 5, 1, "abcdefghij", 10, 1, 0); test("abcde", 5, 1, "abcdefghij", 11, 0, 0); test("abcde", 5, 1, "abcdefghijklmnopqrst", 0, 0, 0); test("abcde", 5, 1, "abcdefghijklmnopqrst", 0, 1, -1); test("abcde", 5, 1, "abcdefghijklmnopqrst", 0, 10, -10); test("abcde", 5, 1, "abcdefghijklmnopqrst", 0, 19, -19); test("abcde", 5, 1, "abcdefghijklmnopqrst", 0, 20, -20); test("abcde", 5, 1, "abcdefghijklmnopqrst", 0, 21, -20); test("abcde", 5, 1, "abcdefghijklmnopqrst", 1, 0, 0); test("abcde", 5, 1, "abcdefghijklmnopqrst", 1, 1, -1); test("abcde", 5, 1, "abcdefghijklmnopqrst", 1, 9, -9); test("abcde", 5, 1, "abcdefghijklmnopqrst", 1, 18, -18); test("abcde", 5, 1, "abcdefghijklmnopqrst", 1, 19, -19); test("abcde", 5, 1, "abcdefghijklmnopqrst", 1, 20, -19); test("abcde", 5, 1, "abcdefghijklmnopqrst", 10, 0, 0); test("abcde", 5, 1, "abcdefghijklmnopqrst", 10, 1, -1); test("abcde", 5, 1, "abcdefghijklmnopqrst", 10, 5, -5); test("abcde", 5, 1, "abcdefghijklmnopqrst", 10, 9, -9); test("abcde", 5, 1, "abcdefghijklmnopqrst", 10, 10, -10); test("abcde", 5, 1, "abcdefghijklmnopqrst", 10, 11, -10); test("abcde", 5, 1, "abcdefghijklmnopqrst", 19, 0, 0); test("abcde", 5, 1, "abcdefghijklmnopqrst", 19, 1, -1); test("abcde", 5, 1, "abcdefghijklmnopqrst", 19, 2, -1); test("abcde", 5, 1, "abcdefghijklmnopqrst", 20, 0, 0); test("abcde", 5, 1, "abcdefghijklmnopqrst", 20, 1, 0); test("abcde", 5, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcde", 6, 0, "", 0, 0, 0); test("abcde", 6, 0, "", 0, 1, 0); test("abcde", 6, 0, "", 1, 0, 0); test("abcde", 6, 0, "abcde", 0, 0, 0); test("abcde", 6, 0, "abcde", 0, 1, 0); test("abcde", 6, 0, "abcde", 0, 2, 0); test("abcde", 6, 0, "abcde", 0, 4, 0); test("abcde", 6, 0, "abcde", 0, 5, 0); test("abcde", 6, 0, "abcde", 0, 6, 0); test("abcde", 6, 0, "abcde", 1, 0, 0); test("abcde", 6, 0, "abcde", 1, 1, 0); test("abcde", 6, 0, "abcde", 1, 2, 0); test("abcde", 6, 0, "abcde", 1, 3, 0); test("abcde", 6, 0, "abcde", 1, 4, 0); test("abcde", 6, 0, "abcde", 1, 5, 0); test("abcde", 6, 0, "abcde", 2, 0, 0); test("abcde", 6, 0, "abcde", 2, 1, 0); test("abcde", 6, 0, "abcde", 2, 2, 0); test("abcde", 6, 0, "abcde", 2, 3, 0); test("abcde", 6, 0, "abcde", 2, 4, 0); test("abcde", 6, 0, "abcde", 4, 0, 0); test("abcde", 6, 0, "abcde", 4, 1, 0); test("abcde", 6, 0, "abcde", 4, 2, 0); test("abcde", 6, 0, "abcde", 5, 0, 0); test("abcde", 6, 0, "abcde", 5, 1, 0); test("abcde", 6, 0, "abcde", 6, 0, 0); test("abcde", 6, 0, "abcdefghij", 0, 0, 0); test("abcde", 6, 0, "abcdefghij", 0, 1, 0); test("abcde", 6, 0, "abcdefghij", 0, 5, 0); test("abcde", 6, 0, "abcdefghij", 0, 9, 0); test("abcde", 6, 0, "abcdefghij", 0, 10, 0); test("abcde", 6, 0, "abcdefghij", 0, 11, 0); test("abcde", 6, 0, "abcdefghij", 1, 0, 0); test("abcde", 6, 0, "abcdefghij", 1, 1, 0); test("abcde", 6, 0, "abcdefghij", 1, 4, 0); test("abcde", 6, 0, "abcdefghij", 1, 8, 0); test("abcde", 6, 0, "abcdefghij", 1, 9, 0); test("abcde", 6, 0, "abcdefghij", 1, 10, 0); test("abcde", 6, 0, "abcdefghij", 5, 0, 0); test("abcde", 6, 0, "abcdefghij", 5, 1, 0); test("abcde", 6, 0, "abcdefghij", 5, 2, 0); test("abcde", 6, 0, "abcdefghij", 5, 4, 0); test("abcde", 6, 0, "abcdefghij", 5, 5, 0); test("abcde", 6, 0, "abcdefghij", 5, 6, 0); test("abcde", 6, 0, "abcdefghij", 9, 0, 0); test("abcde", 6, 0, "abcdefghij", 9, 1, 0); test("abcde", 6, 0, "abcdefghij", 9, 2, 0); test("abcde", 6, 0, "abcdefghij", 10, 0, 0); test("abcde", 6, 0, "abcdefghij", 10, 1, 0); test("abcde", 6, 0, "abcdefghij", 11, 0, 0); } void test19() { test("abcde", 6, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 0, 1, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 0, 10, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 0, 19, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 0, 20, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 0, 21, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 1, 1, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 1, 9, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 1, 18, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 1, 19, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 1, 20, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 10, 1, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 10, 5, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 10, 9, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 10, 10, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 10, 11, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 19, 1, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 19, 2, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcde", 6, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 0, 0, "", 0, 0, 0); test("abcdefghij", 0, 0, "", 0, 1, 0); test("abcdefghij", 0, 0, "", 1, 0, 0); test("abcdefghij", 0, 0, "abcde", 0, 0, 0); test("abcdefghij", 0, 0, "abcde", 0, 1, -1); test("abcdefghij", 0, 0, "abcde", 0, 2, -2); test("abcdefghij", 0, 0, "abcde", 0, 4, -4); test("abcdefghij", 0, 0, "abcde", 0, 5, -5); test("abcdefghij", 0, 0, "abcde", 0, 6, -5); test("abcdefghij", 0, 0, "abcde", 1, 0, 0); test("abcdefghij", 0, 0, "abcde", 1, 1, -1); test("abcdefghij", 0, 0, "abcde", 1, 2, -2); test("abcdefghij", 0, 0, "abcde", 1, 3, -3); test("abcdefghij", 0, 0, "abcde", 1, 4, -4); test("abcdefghij", 0, 0, "abcde", 1, 5, -4); test("abcdefghij", 0, 0, "abcde", 2, 0, 0); test("abcdefghij", 0, 0, "abcde", 2, 1, -1); test("abcdefghij", 0, 0, "abcde", 2, 2, -2); test("abcdefghij", 0, 0, "abcde", 2, 3, -3); test("abcdefghij", 0, 0, "abcde", 2, 4, -3); test("abcdefghij", 0, 0, "abcde", 4, 0, 0); test("abcdefghij", 0, 0, "abcde", 4, 1, -1); test("abcdefghij", 0, 0, "abcde", 4, 2, -1); test("abcdefghij", 0, 0, "abcde", 5, 0, 0); test("abcdefghij", 0, 0, "abcde", 5, 1, 0); test("abcdefghij", 0, 0, "abcde", 6, 0, 0); test("abcdefghij", 0, 0, "abcdefghij", 0, 0, 0); test("abcdefghij", 0, 0, "abcdefghij", 0, 1, -1); test("abcdefghij", 0, 0, "abcdefghij", 0, 5, -5); test("abcdefghij", 0, 0, "abcdefghij", 0, 9, -9); test("abcdefghij", 0, 0, "abcdefghij", 0, 10, -10); test("abcdefghij", 0, 0, "abcdefghij", 0, 11, -10); test("abcdefghij", 0, 0, "abcdefghij", 1, 0, 0); test("abcdefghij", 0, 0, "abcdefghij", 1, 1, -1); test("abcdefghij", 0, 0, "abcdefghij", 1, 4, -4); test("abcdefghij", 0, 0, "abcdefghij", 1, 8, -8); test("abcdefghij", 0, 0, "abcdefghij", 1, 9, -9); test("abcdefghij", 0, 0, "abcdefghij", 1, 10, -9); test("abcdefghij", 0, 0, "abcdefghij", 5, 0, 0); test("abcdefghij", 0, 0, "abcdefghij", 5, 1, -1); test("abcdefghij", 0, 0, "abcdefghij", 5, 2, -2); test("abcdefghij", 0, 0, "abcdefghij", 5, 4, -4); test("abcdefghij", 0, 0, "abcdefghij", 5, 5, -5); test("abcdefghij", 0, 0, "abcdefghij", 5, 6, -5); test("abcdefghij", 0, 0, "abcdefghij", 9, 0, 0); test("abcdefghij", 0, 0, "abcdefghij", 9, 1, -1); test("abcdefghij", 0, 0, "abcdefghij", 9, 2, -1); test("abcdefghij", 0, 0, "abcdefghij", 10, 0, 0); test("abcdefghij", 0, 0, "abcdefghij", 10, 1, 0); test("abcdefghij", 0, 0, "abcdefghij", 11, 0, 0); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghij", 0, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 0, 1, "", 0, 0, 1); test("abcdefghij", 0, 1, "", 0, 1, 1); } void test20() { test("abcdefghij", 0, 1, "", 1, 0, 0); test("abcdefghij", 0, 1, "abcde", 0, 0, 1); test("abcdefghij", 0, 1, "abcde", 0, 1, 0); test("abcdefghij", 0, 1, "abcde", 0, 2, -1); test("abcdefghij", 0, 1, "abcde", 0, 4, -3); test("abcdefghij", 0, 1, "abcde", 0, 5, -4); test("abcdefghij", 0, 1, "abcde", 0, 6, -4); test("abcdefghij", 0, 1, "abcde", 1, 0, 1); test("abcdefghij", 0, 1, "abcde", 1, 1, -1); test("abcdefghij", 0, 1, "abcde", 1, 2, -1); test("abcdefghij", 0, 1, "abcde", 1, 3, -1); test("abcdefghij", 0, 1, "abcde", 1, 4, -1); test("abcdefghij", 0, 1, "abcde", 1, 5, -1); test("abcdefghij", 0, 1, "abcde", 2, 0, 1); test("abcdefghij", 0, 1, "abcde", 2, 1, -2); test("abcdefghij", 0, 1, "abcde", 2, 2, -2); test("abcdefghij", 0, 1, "abcde", 2, 3, -2); test("abcdefghij", 0, 1, "abcde", 2, 4, -2); test("abcdefghij", 0, 1, "abcde", 4, 0, 1); test("abcdefghij", 0, 1, "abcde", 4, 1, -4); test("abcdefghij", 0, 1, "abcde", 4, 2, -4); test("abcdefghij", 0, 1, "abcde", 5, 0, 1); test("abcdefghij", 0, 1, "abcde", 5, 1, 1); test("abcdefghij", 0, 1, "abcde", 6, 0, 0); test("abcdefghij", 0, 1, "abcdefghij", 0, 0, 1); test("abcdefghij", 0, 1, "abcdefghij", 0, 1, 0); test("abcdefghij", 0, 1, "abcdefghij", 0, 5, -4); test("abcdefghij", 0, 1, "abcdefghij", 0, 9, -8); test("abcdefghij", 0, 1, "abcdefghij", 0, 10, -9); test("abcdefghij", 0, 1, "abcdefghij", 0, 11, -9); test("abcdefghij", 0, 1, "abcdefghij", 1, 0, 1); test("abcdefghij", 0, 1, "abcdefghij", 1, 1, -1); test("abcdefghij", 0, 1, "abcdefghij", 1, 4, -1); test("abcdefghij", 0, 1, "abcdefghij", 1, 8, -1); test("abcdefghij", 0, 1, "abcdefghij", 1, 9, -1); test("abcdefghij", 0, 1, "abcdefghij", 1, 10, -1); test("abcdefghij", 0, 1, "abcdefghij", 5, 0, 1); test("abcdefghij", 0, 1, "abcdefghij", 5, 1, -5); test("abcdefghij", 0, 1, "abcdefghij", 5, 2, -5); test("abcdefghij", 0, 1, "abcdefghij", 5, 4, -5); test("abcdefghij", 0, 1, "abcdefghij", 5, 5, -5); test("abcdefghij", 0, 1, "abcdefghij", 5, 6, -5); test("abcdefghij", 0, 1, "abcdefghij", 9, 0, 1); test("abcdefghij", 0, 1, "abcdefghij", 9, 1, -9); test("abcdefghij", 0, 1, "abcdefghij", 9, 2, -9); test("abcdefghij", 0, 1, "abcdefghij", 10, 0, 1); test("abcdefghij", 0, 1, "abcdefghij", 10, 1, 1); test("abcdefghij", 0, 1, "abcdefghij", 11, 0, 0); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 0, 0, 1); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 0, 1, 0); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 0, 10, -9); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 0, 19, -18); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 0, 20, -19); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 0, 21, -19); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 1, 0, 1); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 1, 9, -1); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 1, 18, -1); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 1, 19, -1); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 1, 20, -1); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 10, 0, 1); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 10, 1, -10); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 10, 5, -10); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 10, 9, -10); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 19, 0, 1); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 19, 1, -19); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 19, 2, -19); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 20, 0, 1); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 20, 1, 1); test("abcdefghij", 0, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 0, 5, "", 0, 0, 5); test("abcdefghij", 0, 5, "", 0, 1, 5); test("abcdefghij", 0, 5, "", 1, 0, 0); test("abcdefghij", 0, 5, "abcde", 0, 0, 5); test("abcdefghij", 0, 5, "abcde", 0, 1, 4); test("abcdefghij", 0, 5, "abcde", 0, 2, 3); test("abcdefghij", 0, 5, "abcde", 0, 4, 1); test("abcdefghij", 0, 5, "abcde", 0, 5, 0); test("abcdefghij", 0, 5, "abcde", 0, 6, 0); test("abcdefghij", 0, 5, "abcde", 1, 0, 5); test("abcdefghij", 0, 5, "abcde", 1, 1, -1); test("abcdefghij", 0, 5, "abcde", 1, 2, -1); test("abcdefghij", 0, 5, "abcde", 1, 3, -1); test("abcdefghij", 0, 5, "abcde", 1, 4, -1); test("abcdefghij", 0, 5, "abcde", 1, 5, -1); test("abcdefghij", 0, 5, "abcde", 2, 0, 5); test("abcdefghij", 0, 5, "abcde", 2, 1, -2); test("abcdefghij", 0, 5, "abcde", 2, 2, -2); test("abcdefghij", 0, 5, "abcde", 2, 3, -2); test("abcdefghij", 0, 5, "abcde", 2, 4, -2); test("abcdefghij", 0, 5, "abcde", 4, 0, 5); test("abcdefghij", 0, 5, "abcde", 4, 1, -4); test("abcdefghij", 0, 5, "abcde", 4, 2, -4); test("abcdefghij", 0, 5, "abcde", 5, 0, 5); test("abcdefghij", 0, 5, "abcde", 5, 1, 5); test("abcdefghij", 0, 5, "abcde", 6, 0, 0); test("abcdefghij", 0, 5, "abcdefghij", 0, 0, 5); test("abcdefghij", 0, 5, "abcdefghij", 0, 1, 4); } void test21() { test("abcdefghij", 0, 5, "abcdefghij", 0, 5, 0); test("abcdefghij", 0, 5, "abcdefghij", 0, 9, -4); test("abcdefghij", 0, 5, "abcdefghij", 0, 10, -5); test("abcdefghij", 0, 5, "abcdefghij", 0, 11, -5); test("abcdefghij", 0, 5, "abcdefghij", 1, 0, 5); test("abcdefghij", 0, 5, "abcdefghij", 1, 1, -1); test("abcdefghij", 0, 5, "abcdefghij", 1, 4, -1); test("abcdefghij", 0, 5, "abcdefghij", 1, 8, -1); test("abcdefghij", 0, 5, "abcdefghij", 1, 9, -1); test("abcdefghij", 0, 5, "abcdefghij", 1, 10, -1); test("abcdefghij", 0, 5, "abcdefghij", 5, 0, 5); test("abcdefghij", 0, 5, "abcdefghij", 5, 1, -5); test("abcdefghij", 0, 5, "abcdefghij", 5, 2, -5); test("abcdefghij", 0, 5, "abcdefghij", 5, 4, -5); test("abcdefghij", 0, 5, "abcdefghij", 5, 5, -5); test("abcdefghij", 0, 5, "abcdefghij", 5, 6, -5); test("abcdefghij", 0, 5, "abcdefghij", 9, 0, 5); test("abcdefghij", 0, 5, "abcdefghij", 9, 1, -9); test("abcdefghij", 0, 5, "abcdefghij", 9, 2, -9); test("abcdefghij", 0, 5, "abcdefghij", 10, 0, 5); test("abcdefghij", 0, 5, "abcdefghij", 10, 1, 5); test("abcdefghij", 0, 5, "abcdefghij", 11, 0, 0); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 0, 0, 5); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 0, 1, 4); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 0, 10, -5); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 0, 19, -14); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 0, 20, -15); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 0, 21, -15); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 1, 0, 5); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 1, 9, -1); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 1, 18, -1); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 1, 19, -1); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 1, 20, -1); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 10, 0, 5); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 10, 1, -10); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 10, 5, -10); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 10, 9, -10); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 19, 0, 5); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 19, 1, -19); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 19, 2, -19); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 20, 0, 5); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 20, 1, 5); test("abcdefghij", 0, 5, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 0, 9, "", 0, 0, 9); test("abcdefghij", 0, 9, "", 0, 1, 9); test("abcdefghij", 0, 9, "", 1, 0, 0); test("abcdefghij", 0, 9, "abcde", 0, 0, 9); test("abcdefghij", 0, 9, "abcde", 0, 1, 8); test("abcdefghij", 0, 9, "abcde", 0, 2, 7); test("abcdefghij", 0, 9, "abcde", 0, 4, 5); test("abcdefghij", 0, 9, "abcde", 0, 5, 4); test("abcdefghij", 0, 9, "abcde", 0, 6, 4); test("abcdefghij", 0, 9, "abcde", 1, 0, 9); test("abcdefghij", 0, 9, "abcde", 1, 1, -1); test("abcdefghij", 0, 9, "abcde", 1, 2, -1); test("abcdefghij", 0, 9, "abcde", 1, 3, -1); test("abcdefghij", 0, 9, "abcde", 1, 4, -1); test("abcdefghij", 0, 9, "abcde", 1, 5, -1); test("abcdefghij", 0, 9, "abcde", 2, 0, 9); test("abcdefghij", 0, 9, "abcde", 2, 1, -2); test("abcdefghij", 0, 9, "abcde", 2, 2, -2); test("abcdefghij", 0, 9, "abcde", 2, 3, -2); test("abcdefghij", 0, 9, "abcde", 2, 4, -2); test("abcdefghij", 0, 9, "abcde", 4, 0, 9); test("abcdefghij", 0, 9, "abcde", 4, 1, -4); test("abcdefghij", 0, 9, "abcde", 4, 2, -4); test("abcdefghij", 0, 9, "abcde", 5, 0, 9); test("abcdefghij", 0, 9, "abcde", 5, 1, 9); test("abcdefghij", 0, 9, "abcde", 6, 0, 0); test("abcdefghij", 0, 9, "abcdefghij", 0, 0, 9); test("abcdefghij", 0, 9, "abcdefghij", 0, 1, 8); test("abcdefghij", 0, 9, "abcdefghij", 0, 5, 4); test("abcdefghij", 0, 9, "abcdefghij", 0, 9, 0); test("abcdefghij", 0, 9, "abcdefghij", 0, 10, -1); test("abcdefghij", 0, 9, "abcdefghij", 0, 11, -1); test("abcdefghij", 0, 9, "abcdefghij", 1, 0, 9); test("abcdefghij", 0, 9, "abcdefghij", 1, 1, -1); test("abcdefghij", 0, 9, "abcdefghij", 1, 4, -1); test("abcdefghij", 0, 9, "abcdefghij", 1, 8, -1); test("abcdefghij", 0, 9, "abcdefghij", 1, 9, -1); test("abcdefghij", 0, 9, "abcdefghij", 1, 10, -1); test("abcdefghij", 0, 9, "abcdefghij", 5, 0, 9); test("abcdefghij", 0, 9, "abcdefghij", 5, 1, -5); test("abcdefghij", 0, 9, "abcdefghij", 5, 2, -5); test("abcdefghij", 0, 9, "abcdefghij", 5, 4, -5); test("abcdefghij", 0, 9, "abcdefghij", 5, 5, -5); test("abcdefghij", 0, 9, "abcdefghij", 5, 6, -5); test("abcdefghij", 0, 9, "abcdefghij", 9, 0, 9); test("abcdefghij", 0, 9, "abcdefghij", 9, 1, -9); test("abcdefghij", 0, 9, "abcdefghij", 9, 2, -9); test("abcdefghij", 0, 9, "abcdefghij", 10, 0, 9); test("abcdefghij", 0, 9, "abcdefghij", 10, 1, 9); test("abcdefghij", 0, 9, "abcdefghij", 11, 0, 0); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 0, 0, 9); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 0, 1, 8); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 0, 10, -1); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 0, 19, -10); } void test22() { test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 0, 20, -11); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 0, 21, -11); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 1, 0, 9); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 1, 9, -1); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 1, 18, -1); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 1, 19, -1); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 1, 20, -1); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 10, 0, 9); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 10, 1, -10); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 10, 5, -10); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 10, 9, -10); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 19, 0, 9); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 19, 1, -19); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 19, 2, -19); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 20, 0, 9); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 20, 1, 9); test("abcdefghij", 0, 9, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 0, 10, "", 0, 0, 10); test("abcdefghij", 0, 10, "", 0, 1, 10); test("abcdefghij", 0, 10, "", 1, 0, 0); test("abcdefghij", 0, 10, "abcde", 0, 0, 10); test("abcdefghij", 0, 10, "abcde", 0, 1, 9); test("abcdefghij", 0, 10, "abcde", 0, 2, 8); test("abcdefghij", 0, 10, "abcde", 0, 4, 6); test("abcdefghij", 0, 10, "abcde", 0, 5, 5); test("abcdefghij", 0, 10, "abcde", 0, 6, 5); test("abcdefghij", 0, 10, "abcde", 1, 0, 10); test("abcdefghij", 0, 10, "abcde", 1, 1, -1); test("abcdefghij", 0, 10, "abcde", 1, 2, -1); test("abcdefghij", 0, 10, "abcde", 1, 3, -1); test("abcdefghij", 0, 10, "abcde", 1, 4, -1); test("abcdefghij", 0, 10, "abcde", 1, 5, -1); test("abcdefghij", 0, 10, "abcde", 2, 0, 10); test("abcdefghij", 0, 10, "abcde", 2, 1, -2); test("abcdefghij", 0, 10, "abcde", 2, 2, -2); test("abcdefghij", 0, 10, "abcde", 2, 3, -2); test("abcdefghij", 0, 10, "abcde", 2, 4, -2); test("abcdefghij", 0, 10, "abcde", 4, 0, 10); test("abcdefghij", 0, 10, "abcde", 4, 1, -4); test("abcdefghij", 0, 10, "abcde", 4, 2, -4); test("abcdefghij", 0, 10, "abcde", 5, 0, 10); test("abcdefghij", 0, 10, "abcde", 5, 1, 10); test("abcdefghij", 0, 10, "abcde", 6, 0, 0); test("abcdefghij", 0, 10, "abcdefghij", 0, 0, 10); test("abcdefghij", 0, 10, "abcdefghij", 0, 1, 9); test("abcdefghij", 0, 10, "abcdefghij", 0, 5, 5); test("abcdefghij", 0, 10, "abcdefghij", 0, 9, 1); test("abcdefghij", 0, 10, "abcdefghij", 0, 10, 0); test("abcdefghij", 0, 10, "abcdefghij", 0, 11, 0); test("abcdefghij", 0, 10, "abcdefghij", 1, 0, 10); test("abcdefghij", 0, 10, "abcdefghij", 1, 1, -1); test("abcdefghij", 0, 10, "abcdefghij", 1, 4, -1); test("abcdefghij", 0, 10, "abcdefghij", 1, 8, -1); test("abcdefghij", 0, 10, "abcdefghij", 1, 9, -1); test("abcdefghij", 0, 10, "abcdefghij", 1, 10, -1); test("abcdefghij", 0, 10, "abcdefghij", 5, 0, 10); test("abcdefghij", 0, 10, "abcdefghij", 5, 1, -5); test("abcdefghij", 0, 10, "abcdefghij", 5, 2, -5); test("abcdefghij", 0, 10, "abcdefghij", 5, 4, -5); test("abcdefghij", 0, 10, "abcdefghij", 5, 5, -5); test("abcdefghij", 0, 10, "abcdefghij", 5, 6, -5); test("abcdefghij", 0, 10, "abcdefghij", 9, 0, 10); test("abcdefghij", 0, 10, "abcdefghij", 9, 1, -9); test("abcdefghij", 0, 10, "abcdefghij", 9, 2, -9); test("abcdefghij", 0, 10, "abcdefghij", 10, 0, 10); test("abcdefghij", 0, 10, "abcdefghij", 10, 1, 10); test("abcdefghij", 0, 10, "abcdefghij", 11, 0, 0); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 0, 0, 10); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 0, 1, 9); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 0, 10, 0); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 0, 19, -9); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 0, 20, -10); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 0, 21, -10); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 1, 0, 10); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 1, 9, -1); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 1, 18, -1); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 1, 19, -1); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 1, 20, -1); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 10, 0, 10); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 10, 1, -10); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 10, 5, -10); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 10, 9, -10); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 19, 0, 10); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 19, 1, -19); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 19, 2, -19); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 20, 0, 10); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 20, 1, 10); test("abcdefghij", 0, 10, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 0, 11, "", 0, 0, 10); test("abcdefghij", 0, 11, "", 0, 1, 10); test("abcdefghij", 0, 11, "", 1, 0, 0); test("abcdefghij", 0, 11, "abcde", 0, 0, 10); test("abcdefghij", 0, 11, "abcde", 0, 1, 9); test("abcdefghij", 0, 11, "abcde", 0, 2, 8); } void test23() { test("abcdefghij", 0, 11, "abcde", 0, 4, 6); test("abcdefghij", 0, 11, "abcde", 0, 5, 5); test("abcdefghij", 0, 11, "abcde", 0, 6, 5); test("abcdefghij", 0, 11, "abcde", 1, 0, 10); test("abcdefghij", 0, 11, "abcde", 1, 1, -1); test("abcdefghij", 0, 11, "abcde", 1, 2, -1); test("abcdefghij", 0, 11, "abcde", 1, 3, -1); test("abcdefghij", 0, 11, "abcde", 1, 4, -1); test("abcdefghij", 0, 11, "abcde", 1, 5, -1); test("abcdefghij", 0, 11, "abcde", 2, 0, 10); test("abcdefghij", 0, 11, "abcde", 2, 1, -2); test("abcdefghij", 0, 11, "abcde", 2, 2, -2); test("abcdefghij", 0, 11, "abcde", 2, 3, -2); test("abcdefghij", 0, 11, "abcde", 2, 4, -2); test("abcdefghij", 0, 11, "abcde", 4, 0, 10); test("abcdefghij", 0, 11, "abcde", 4, 1, -4); test("abcdefghij", 0, 11, "abcde", 4, 2, -4); test("abcdefghij", 0, 11, "abcde", 5, 0, 10); test("abcdefghij", 0, 11, "abcde", 5, 1, 10); test("abcdefghij", 0, 11, "abcde", 6, 0, 0); test("abcdefghij", 0, 11, "abcdefghij", 0, 0, 10); test("abcdefghij", 0, 11, "abcdefghij", 0, 1, 9); test("abcdefghij", 0, 11, "abcdefghij", 0, 5, 5); test("abcdefghij", 0, 11, "abcdefghij", 0, 9, 1); test("abcdefghij", 0, 11, "abcdefghij", 0, 10, 0); test("abcdefghij", 0, 11, "abcdefghij", 0, 11, 0); test("abcdefghij", 0, 11, "abcdefghij", 1, 0, 10); test("abcdefghij", 0, 11, "abcdefghij", 1, 1, -1); test("abcdefghij", 0, 11, "abcdefghij", 1, 4, -1); test("abcdefghij", 0, 11, "abcdefghij", 1, 8, -1); test("abcdefghij", 0, 11, "abcdefghij", 1, 9, -1); test("abcdefghij", 0, 11, "abcdefghij", 1, 10, -1); test("abcdefghij", 0, 11, "abcdefghij", 5, 0, 10); test("abcdefghij", 0, 11, "abcdefghij", 5, 1, -5); test("abcdefghij", 0, 11, "abcdefghij", 5, 2, -5); test("abcdefghij", 0, 11, "abcdefghij", 5, 4, -5); test("abcdefghij", 0, 11, "abcdefghij", 5, 5, -5); test("abcdefghij", 0, 11, "abcdefghij", 5, 6, -5); test("abcdefghij", 0, 11, "abcdefghij", 9, 0, 10); test("abcdefghij", 0, 11, "abcdefghij", 9, 1, -9); test("abcdefghij", 0, 11, "abcdefghij", 9, 2, -9); test("abcdefghij", 0, 11, "abcdefghij", 10, 0, 10); test("abcdefghij", 0, 11, "abcdefghij", 10, 1, 10); test("abcdefghij", 0, 11, "abcdefghij", 11, 0, 0); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 0, 0, 10); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 0, 1, 9); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 0, 10, 0); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 0, 19, -9); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 0, 20, -10); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 0, 21, -10); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 1, 0, 10); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 1, 9, -1); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 1, 18, -1); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 1, 19, -1); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 1, 20, -1); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 10, 0, 10); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 10, 1, -10); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 10, 5, -10); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 10, 9, -10); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 19, 0, 10); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 19, 1, -19); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 19, 2, -19); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 20, 0, 10); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 20, 1, 10); test("abcdefghij", 0, 11, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 1, 0, "", 0, 0, 0); test("abcdefghij", 1, 0, "", 0, 1, 0); test("abcdefghij", 1, 0, "", 1, 0, 0); test("abcdefghij", 1, 0, "abcde", 0, 0, 0); test("abcdefghij", 1, 0, "abcde", 0, 1, -1); test("abcdefghij", 1, 0, "abcde", 0, 2, -2); test("abcdefghij", 1, 0, "abcde", 0, 4, -4); test("abcdefghij", 1, 0, "abcde", 0, 5, -5); test("abcdefghij", 1, 0, "abcde", 0, 6, -5); test("abcdefghij", 1, 0, "abcde", 1, 0, 0); test("abcdefghij", 1, 0, "abcde", 1, 1, -1); test("abcdefghij", 1, 0, "abcde", 1, 2, -2); test("abcdefghij", 1, 0, "abcde", 1, 3, -3); test("abcdefghij", 1, 0, "abcde", 1, 4, -4); test("abcdefghij", 1, 0, "abcde", 1, 5, -4); test("abcdefghij", 1, 0, "abcde", 2, 0, 0); test("abcdefghij", 1, 0, "abcde", 2, 1, -1); test("abcdefghij", 1, 0, "abcde", 2, 2, -2); test("abcdefghij", 1, 0, "abcde", 2, 3, -3); test("abcdefghij", 1, 0, "abcde", 2, 4, -3); test("abcdefghij", 1, 0, "abcde", 4, 0, 0); test("abcdefghij", 1, 0, "abcde", 4, 1, -1); test("abcdefghij", 1, 0, "abcde", 4, 2, -1); test("abcdefghij", 1, 0, "abcde", 5, 0, 0); test("abcdefghij", 1, 0, "abcde", 5, 1, 0); test("abcdefghij", 1, 0, "abcde", 6, 0, 0); test("abcdefghij", 1, 0, "abcdefghij", 0, 0, 0); test("abcdefghij", 1, 0, "abcdefghij", 0, 1, -1); test("abcdefghij", 1, 0, "abcdefghij", 0, 5, -5); test("abcdefghij", 1, 0, "abcdefghij", 0, 9, -9); test("abcdefghij", 1, 0, "abcdefghij", 0, 10, -10); test("abcdefghij", 1, 0, "abcdefghij", 0, 11, -10); } void test24() { test("abcdefghij", 1, 0, "abcdefghij", 1, 0, 0); test("abcdefghij", 1, 0, "abcdefghij", 1, 1, -1); test("abcdefghij", 1, 0, "abcdefghij", 1, 4, -4); test("abcdefghij", 1, 0, "abcdefghij", 1, 8, -8); test("abcdefghij", 1, 0, "abcdefghij", 1, 9, -9); test("abcdefghij", 1, 0, "abcdefghij", 1, 10, -9); test("abcdefghij", 1, 0, "abcdefghij", 5, 0, 0); test("abcdefghij", 1, 0, "abcdefghij", 5, 1, -1); test("abcdefghij", 1, 0, "abcdefghij", 5, 2, -2); test("abcdefghij", 1, 0, "abcdefghij", 5, 4, -4); test("abcdefghij", 1, 0, "abcdefghij", 5, 5, -5); test("abcdefghij", 1, 0, "abcdefghij", 5, 6, -5); test("abcdefghij", 1, 0, "abcdefghij", 9, 0, 0); test("abcdefghij", 1, 0, "abcdefghij", 9, 1, -1); test("abcdefghij", 1, 0, "abcdefghij", 9, 2, -1); test("abcdefghij", 1, 0, "abcdefghij", 10, 0, 0); test("abcdefghij", 1, 0, "abcdefghij", 10, 1, 0); test("abcdefghij", 1, 0, "abcdefghij", 11, 0, 0); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghij", 1, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 1, 1, "", 0, 0, 1); test("abcdefghij", 1, 1, "", 0, 1, 1); test("abcdefghij", 1, 1, "", 1, 0, 0); test("abcdefghij", 1, 1, "abcde", 0, 0, 1); test("abcdefghij", 1, 1, "abcde", 0, 1, 1); test("abcdefghij", 1, 1, "abcde", 0, 2, 1); test("abcdefghij", 1, 1, "abcde", 0, 4, 1); test("abcdefghij", 1, 1, "abcde", 0, 5, 1); test("abcdefghij", 1, 1, "abcde", 0, 6, 1); test("abcdefghij", 1, 1, "abcde", 1, 0, 1); test("abcdefghij", 1, 1, "abcde", 1, 1, 0); test("abcdefghij", 1, 1, "abcde", 1, 2, -1); test("abcdefghij", 1, 1, "abcde", 1, 3, -2); test("abcdefghij", 1, 1, "abcde", 1, 4, -3); test("abcdefghij", 1, 1, "abcde", 1, 5, -3); test("abcdefghij", 1, 1, "abcde", 2, 0, 1); test("abcdefghij", 1, 1, "abcde", 2, 1, -1); test("abcdefghij", 1, 1, "abcde", 2, 2, -1); test("abcdefghij", 1, 1, "abcde", 2, 3, -1); test("abcdefghij", 1, 1, "abcde", 2, 4, -1); test("abcdefghij", 1, 1, "abcde", 4, 0, 1); test("abcdefghij", 1, 1, "abcde", 4, 1, -3); test("abcdefghij", 1, 1, "abcde", 4, 2, -3); test("abcdefghij", 1, 1, "abcde", 5, 0, 1); test("abcdefghij", 1, 1, "abcde", 5, 1, 1); test("abcdefghij", 1, 1, "abcde", 6, 0, 0); test("abcdefghij", 1, 1, "abcdefghij", 0, 0, 1); test("abcdefghij", 1, 1, "abcdefghij", 0, 1, 1); test("abcdefghij", 1, 1, "abcdefghij", 0, 5, 1); test("abcdefghij", 1, 1, "abcdefghij", 0, 9, 1); test("abcdefghij", 1, 1, "abcdefghij", 0, 10, 1); test("abcdefghij", 1, 1, "abcdefghij", 0, 11, 1); test("abcdefghij", 1, 1, "abcdefghij", 1, 0, 1); test("abcdefghij", 1, 1, "abcdefghij", 1, 1, 0); test("abcdefghij", 1, 1, "abcdefghij", 1, 4, -3); test("abcdefghij", 1, 1, "abcdefghij", 1, 8, -7); test("abcdefghij", 1, 1, "abcdefghij", 1, 9, -8); test("abcdefghij", 1, 1, "abcdefghij", 1, 10, -8); test("abcdefghij", 1, 1, "abcdefghij", 5, 0, 1); test("abcdefghij", 1, 1, "abcdefghij", 5, 1, -4); test("abcdefghij", 1, 1, "abcdefghij", 5, 2, -4); test("abcdefghij", 1, 1, "abcdefghij", 5, 4, -4); test("abcdefghij", 1, 1, "abcdefghij", 5, 5, -4); test("abcdefghij", 1, 1, "abcdefghij", 5, 6, -4); test("abcdefghij", 1, 1, "abcdefghij", 9, 0, 1); test("abcdefghij", 1, 1, "abcdefghij", 9, 1, -8); test("abcdefghij", 1, 1, "abcdefghij", 9, 2, -8); test("abcdefghij", 1, 1, "abcdefghij", 10, 0, 1); test("abcdefghij", 1, 1, "abcdefghij", 10, 1, 1); test("abcdefghij", 1, 1, "abcdefghij", 11, 0, 0); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 0, 0, 1); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 0, 1, 1); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 0, 10, 1); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 0, 19, 1); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 0, 20, 1); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 0, 21, 1); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 1, 0, 1); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 1, 1, 0); } void test25() { test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 1, 9, -8); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 1, 18, -17); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 1, 19, -18); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 1, 20, -18); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 10, 0, 1); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 10, 1, -9); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 10, 5, -9); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 10, 10, -9); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 10, 11, -9); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 19, 0, 1); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 19, 1, -18); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 19, 2, -18); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 20, 0, 1); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 20, 1, 1); test("abcdefghij", 1, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 1, 4, "", 0, 0, 4); test("abcdefghij", 1, 4, "", 0, 1, 4); test("abcdefghij", 1, 4, "", 1, 0, 0); test("abcdefghij", 1, 4, "abcde", 0, 0, 4); test("abcdefghij", 1, 4, "abcde", 0, 1, 1); test("abcdefghij", 1, 4, "abcde", 0, 2, 1); test("abcdefghij", 1, 4, "abcde", 0, 4, 1); test("abcdefghij", 1, 4, "abcde", 0, 5, 1); test("abcdefghij", 1, 4, "abcde", 0, 6, 1); test("abcdefghij", 1, 4, "abcde", 1, 0, 4); test("abcdefghij", 1, 4, "abcde", 1, 1, 3); test("abcdefghij", 1, 4, "abcde", 1, 2, 2); test("abcdefghij", 1, 4, "abcde", 1, 3, 1); test("abcdefghij", 1, 4, "abcde", 1, 4, 0); test("abcdefghij", 1, 4, "abcde", 1, 5, 0); test("abcdefghij", 1, 4, "abcde", 2, 0, 4); test("abcdefghij", 1, 4, "abcde", 2, 1, -1); test("abcdefghij", 1, 4, "abcde", 2, 2, -1); test("abcdefghij", 1, 4, "abcde", 2, 3, -1); test("abcdefghij", 1, 4, "abcde", 2, 4, -1); test("abcdefghij", 1, 4, "abcde", 4, 0, 4); test("abcdefghij", 1, 4, "abcde", 4, 1, -3); test("abcdefghij", 1, 4, "abcde", 4, 2, -3); test("abcdefghij", 1, 4, "abcde", 5, 0, 4); test("abcdefghij", 1, 4, "abcde", 5, 1, 4); test("abcdefghij", 1, 4, "abcde", 6, 0, 0); test("abcdefghij", 1, 4, "abcdefghij", 0, 0, 4); test("abcdefghij", 1, 4, "abcdefghij", 0, 1, 1); test("abcdefghij", 1, 4, "abcdefghij", 0, 5, 1); test("abcdefghij", 1, 4, "abcdefghij", 0, 9, 1); test("abcdefghij", 1, 4, "abcdefghij", 0, 10, 1); test("abcdefghij", 1, 4, "abcdefghij", 0, 11, 1); test("abcdefghij", 1, 4, "abcdefghij", 1, 0, 4); test("abcdefghij", 1, 4, "abcdefghij", 1, 1, 3); test("abcdefghij", 1, 4, "abcdefghij", 1, 4, 0); test("abcdefghij", 1, 4, "abcdefghij", 1, 8, -4); test("abcdefghij", 1, 4, "abcdefghij", 1, 9, -5); test("abcdefghij", 1, 4, "abcdefghij", 1, 10, -5); test("abcdefghij", 1, 4, "abcdefghij", 5, 0, 4); test("abcdefghij", 1, 4, "abcdefghij", 5, 1, -4); test("abcdefghij", 1, 4, "abcdefghij", 5, 2, -4); test("abcdefghij", 1, 4, "abcdefghij", 5, 4, -4); test("abcdefghij", 1, 4, "abcdefghij", 5, 5, -4); test("abcdefghij", 1, 4, "abcdefghij", 5, 6, -4); test("abcdefghij", 1, 4, "abcdefghij", 9, 0, 4); test("abcdefghij", 1, 4, "abcdefghij", 9, 1, -8); test("abcdefghij", 1, 4, "abcdefghij", 9, 2, -8); test("abcdefghij", 1, 4, "abcdefghij", 10, 0, 4); test("abcdefghij", 1, 4, "abcdefghij", 10, 1, 4); test("abcdefghij", 1, 4, "abcdefghij", 11, 0, 0); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 0, 0, 4); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 0, 1, 1); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 0, 10, 1); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 0, 19, 1); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 0, 20, 1); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 0, 21, 1); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 1, 0, 4); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 1, 1, 3); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 1, 9, -5); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 1, 18, -14); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 1, 19, -15); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 1, 20, -15); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 10, 0, 4); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 10, 1, -9); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 10, 5, -9); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 10, 10, -9); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 10, 11, -9); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 19, 0, 4); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 19, 1, -18); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 19, 2, -18); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 20, 0, 4); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 20, 1, 4); test("abcdefghij", 1, 4, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 1, 8, "", 0, 0, 8); test("abcdefghij", 1, 8, "", 0, 1, 8); test("abcdefghij", 1, 8, "", 1, 0, 0); test("abcdefghij", 1, 8, "abcde", 0, 0, 8); test("abcdefghij", 1, 8, "abcde", 0, 1, 1); test("abcdefghij", 1, 8, "abcde", 0, 2, 1); test("abcdefghij", 1, 8, "abcde", 0, 4, 1); test("abcdefghij", 1, 8, "abcde", 0, 5, 1); test("abcdefghij", 1, 8, "abcde", 0, 6, 1); test("abcdefghij", 1, 8, "abcde", 1, 0, 8); } void test26() { test("abcdefghij", 1, 8, "abcde", 1, 1, 7); test("abcdefghij", 1, 8, "abcde", 1, 2, 6); test("abcdefghij", 1, 8, "abcde", 1, 3, 5); test("abcdefghij", 1, 8, "abcde", 1, 4, 4); test("abcdefghij", 1, 8, "abcde", 1, 5, 4); test("abcdefghij", 1, 8, "abcde", 2, 0, 8); test("abcdefghij", 1, 8, "abcde", 2, 1, -1); test("abcdefghij", 1, 8, "abcde", 2, 2, -1); test("abcdefghij", 1, 8, "abcde", 2, 3, -1); test("abcdefghij", 1, 8, "abcde", 2, 4, -1); test("abcdefghij", 1, 8, "abcde", 4, 0, 8); test("abcdefghij", 1, 8, "abcde", 4, 1, -3); test("abcdefghij", 1, 8, "abcde", 4, 2, -3); test("abcdefghij", 1, 8, "abcde", 5, 0, 8); test("abcdefghij", 1, 8, "abcde", 5, 1, 8); test("abcdefghij", 1, 8, "abcde", 6, 0, 0); test("abcdefghij", 1, 8, "abcdefghij", 0, 0, 8); test("abcdefghij", 1, 8, "abcdefghij", 0, 1, 1); test("abcdefghij", 1, 8, "abcdefghij", 0, 5, 1); test("abcdefghij", 1, 8, "abcdefghij", 0, 9, 1); test("abcdefghij", 1, 8, "abcdefghij", 0, 10, 1); test("abcdefghij", 1, 8, "abcdefghij", 0, 11, 1); test("abcdefghij", 1, 8, "abcdefghij", 1, 0, 8); test("abcdefghij", 1, 8, "abcdefghij", 1, 1, 7); test("abcdefghij", 1, 8, "abcdefghij", 1, 4, 4); test("abcdefghij", 1, 8, "abcdefghij", 1, 8, 0); test("abcdefghij", 1, 8, "abcdefghij", 1, 9, -1); test("abcdefghij", 1, 8, "abcdefghij", 1, 10, -1); test("abcdefghij", 1, 8, "abcdefghij", 5, 0, 8); test("abcdefghij", 1, 8, "abcdefghij", 5, 1, -4); test("abcdefghij", 1, 8, "abcdefghij", 5, 2, -4); test("abcdefghij", 1, 8, "abcdefghij", 5, 4, -4); test("abcdefghij", 1, 8, "abcdefghij", 5, 5, -4); test("abcdefghij", 1, 8, "abcdefghij", 5, 6, -4); test("abcdefghij", 1, 8, "abcdefghij", 9, 0, 8); test("abcdefghij", 1, 8, "abcdefghij", 9, 1, -8); test("abcdefghij", 1, 8, "abcdefghij", 9, 2, -8); test("abcdefghij", 1, 8, "abcdefghij", 10, 0, 8); test("abcdefghij", 1, 8, "abcdefghij", 10, 1, 8); test("abcdefghij", 1, 8, "abcdefghij", 11, 0, 0); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 0, 0, 8); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 0, 1, 1); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 0, 10, 1); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 0, 19, 1); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 0, 20, 1); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 0, 21, 1); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 1, 0, 8); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 1, 1, 7); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 1, 9, -1); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 1, 18, -10); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 1, 19, -11); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 1, 20, -11); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 10, 0, 8); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 10, 1, -9); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 10, 5, -9); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 10, 10, -9); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 10, 11, -9); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 19, 0, 8); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 19, 1, -18); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 19, 2, -18); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 20, 0, 8); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 20, 1, 8); test("abcdefghij", 1, 8, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 1, 9, "", 0, 0, 9); test("abcdefghij", 1, 9, "", 0, 1, 9); test("abcdefghij", 1, 9, "", 1, 0, 0); test("abcdefghij", 1, 9, "abcde", 0, 0, 9); test("abcdefghij", 1, 9, "abcde", 0, 1, 1); test("abcdefghij", 1, 9, "abcde", 0, 2, 1); test("abcdefghij", 1, 9, "abcde", 0, 4, 1); test("abcdefghij", 1, 9, "abcde", 0, 5, 1); test("abcdefghij", 1, 9, "abcde", 0, 6, 1); test("abcdefghij", 1, 9, "abcde", 1, 0, 9); test("abcdefghij", 1, 9, "abcde", 1, 1, 8); test("abcdefghij", 1, 9, "abcde", 1, 2, 7); test("abcdefghij", 1, 9, "abcde", 1, 3, 6); test("abcdefghij", 1, 9, "abcde", 1, 4, 5); test("abcdefghij", 1, 9, "abcde", 1, 5, 5); test("abcdefghij", 1, 9, "abcde", 2, 0, 9); test("abcdefghij", 1, 9, "abcde", 2, 1, -1); test("abcdefghij", 1, 9, "abcde", 2, 2, -1); test("abcdefghij", 1, 9, "abcde", 2, 3, -1); test("abcdefghij", 1, 9, "abcde", 2, 4, -1); test("abcdefghij", 1, 9, "abcde", 4, 0, 9); test("abcdefghij", 1, 9, "abcde", 4, 1, -3); test("abcdefghij", 1, 9, "abcde", 4, 2, -3); test("abcdefghij", 1, 9, "abcde", 5, 0, 9); test("abcdefghij", 1, 9, "abcde", 5, 1, 9); test("abcdefghij", 1, 9, "abcde", 6, 0, 0); test("abcdefghij", 1, 9, "abcdefghij", 0, 0, 9); test("abcdefghij", 1, 9, "abcdefghij", 0, 1, 1); test("abcdefghij", 1, 9, "abcdefghij", 0, 5, 1); test("abcdefghij", 1, 9, "abcdefghij", 0, 9, 1); test("abcdefghij", 1, 9, "abcdefghij", 0, 10, 1); test("abcdefghij", 1, 9, "abcdefghij", 0, 11, 1); test("abcdefghij", 1, 9, "abcdefghij", 1, 0, 9); test("abcdefghij", 1, 9, "abcdefghij", 1, 1, 8); test("abcdefghij", 1, 9, "abcdefghij", 1, 4, 5); test("abcdefghij", 1, 9, "abcdefghij", 1, 8, 1); } void test27() { test("abcdefghij", 1, 9, "abcdefghij", 1, 9, 0); test("abcdefghij", 1, 9, "abcdefghij", 1, 10, 0); test("abcdefghij", 1, 9, "abcdefghij", 5, 0, 9); test("abcdefghij", 1, 9, "abcdefghij", 5, 1, -4); test("abcdefghij", 1, 9, "abcdefghij", 5, 2, -4); test("abcdefghij", 1, 9, "abcdefghij", 5, 4, -4); test("abcdefghij", 1, 9, "abcdefghij", 5, 5, -4); test("abcdefghij", 1, 9, "abcdefghij", 5, 6, -4); test("abcdefghij", 1, 9, "abcdefghij", 9, 0, 9); test("abcdefghij", 1, 9, "abcdefghij", 9, 1, -8); test("abcdefghij", 1, 9, "abcdefghij", 9, 2, -8); test("abcdefghij", 1, 9, "abcdefghij", 10, 0, 9); test("abcdefghij", 1, 9, "abcdefghij", 10, 1, 9); test("abcdefghij", 1, 9, "abcdefghij", 11, 0, 0); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 0, 0, 9); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 0, 1, 1); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 0, 10, 1); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 0, 19, 1); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 0, 20, 1); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 0, 21, 1); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 1, 0, 9); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 1, 1, 8); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 1, 9, 0); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 1, 18, -9); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 1, 19, -10); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 1, 20, -10); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 10, 0, 9); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 10, 1, -9); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 10, 5, -9); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 10, 10, -9); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 10, 11, -9); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 19, 0, 9); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 19, 1, -18); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 19, 2, -18); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 20, 0, 9); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 20, 1, 9); test("abcdefghij", 1, 9, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 1, 10, "", 0, 0, 9); test("abcdefghij", 1, 10, "", 0, 1, 9); test("abcdefghij", 1, 10, "", 1, 0, 0); test("abcdefghij", 1, 10, "abcde", 0, 0, 9); test("abcdefghij", 1, 10, "abcde", 0, 1, 1); test("abcdefghij", 1, 10, "abcde", 0, 2, 1); test("abcdefghij", 1, 10, "abcde", 0, 4, 1); test("abcdefghij", 1, 10, "abcde", 0, 5, 1); test("abcdefghij", 1, 10, "abcde", 0, 6, 1); test("abcdefghij", 1, 10, "abcde", 1, 0, 9); test("abcdefghij", 1, 10, "abcde", 1, 1, 8); test("abcdefghij", 1, 10, "abcde", 1, 2, 7); test("abcdefghij", 1, 10, "abcde", 1, 3, 6); test("abcdefghij", 1, 10, "abcde", 1, 4, 5); test("abcdefghij", 1, 10, "abcde", 1, 5, 5); test("abcdefghij", 1, 10, "abcde", 2, 0, 9); test("abcdefghij", 1, 10, "abcde", 2, 1, -1); test("abcdefghij", 1, 10, "abcde", 2, 2, -1); test("abcdefghij", 1, 10, "abcde", 2, 3, -1); test("abcdefghij", 1, 10, "abcde", 2, 4, -1); test("abcdefghij", 1, 10, "abcde", 4, 0, 9); test("abcdefghij", 1, 10, "abcde", 4, 1, -3); test("abcdefghij", 1, 10, "abcde", 4, 2, -3); test("abcdefghij", 1, 10, "abcde", 5, 0, 9); test("abcdefghij", 1, 10, "abcde", 5, 1, 9); test("abcdefghij", 1, 10, "abcde", 6, 0, 0); test("abcdefghij", 1, 10, "abcdefghij", 0, 0, 9); test("abcdefghij", 1, 10, "abcdefghij", 0, 1, 1); test("abcdefghij", 1, 10, "abcdefghij", 0, 5, 1); test("abcdefghij", 1, 10, "abcdefghij", 0, 9, 1); test("abcdefghij", 1, 10, "abcdefghij", 0, 10, 1); test("abcdefghij", 1, 10, "abcdefghij", 0, 11, 1); test("abcdefghij", 1, 10, "abcdefghij", 1, 0, 9); test("abcdefghij", 1, 10, "abcdefghij", 1, 1, 8); test("abcdefghij", 1, 10, "abcdefghij", 1, 4, 5); test("abcdefghij", 1, 10, "abcdefghij", 1, 8, 1); test("abcdefghij", 1, 10, "abcdefghij", 1, 9, 0); test("abcdefghij", 1, 10, "abcdefghij", 1, 10, 0); test("abcdefghij", 1, 10, "abcdefghij", 5, 0, 9); test("abcdefghij", 1, 10, "abcdefghij", 5, 1, -4); test("abcdefghij", 1, 10, "abcdefghij", 5, 2, -4); test("abcdefghij", 1, 10, "abcdefghij", 5, 4, -4); test("abcdefghij", 1, 10, "abcdefghij", 5, 5, -4); test("abcdefghij", 1, 10, "abcdefghij", 5, 6, -4); test("abcdefghij", 1, 10, "abcdefghij", 9, 0, 9); test("abcdefghij", 1, 10, "abcdefghij", 9, 1, -8); test("abcdefghij", 1, 10, "abcdefghij", 9, 2, -8); test("abcdefghij", 1, 10, "abcdefghij", 10, 0, 9); test("abcdefghij", 1, 10, "abcdefghij", 10, 1, 9); test("abcdefghij", 1, 10, "abcdefghij", 11, 0, 0); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 0, 0, 9); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 0, 1, 1); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 0, 10, 1); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 0, 19, 1); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 0, 20, 1); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 0, 21, 1); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 1, 0, 9); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 1, 1, 8); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 1, 9, 0); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 1, 18, -9); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 1, 19, -10); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 1, 20, -10); } void test28() { test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 10, 0, 9); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 10, 1, -9); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 10, 5, -9); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 10, 10, -9); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 10, 11, -9); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 19, 0, 9); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 19, 1, -18); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 19, 2, -18); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 20, 0, 9); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 20, 1, 9); test("abcdefghij", 1, 10, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 5, 0, "", 0, 0, 0); test("abcdefghij", 5, 0, "", 0, 1, 0); test("abcdefghij", 5, 0, "", 1, 0, 0); test("abcdefghij", 5, 0, "abcde", 0, 0, 0); test("abcdefghij", 5, 0, "abcde", 0, 1, -1); test("abcdefghij", 5, 0, "abcde", 0, 2, -2); test("abcdefghij", 5, 0, "abcde", 0, 4, -4); test("abcdefghij", 5, 0, "abcde", 0, 5, -5); test("abcdefghij", 5, 0, "abcde", 0, 6, -5); test("abcdefghij", 5, 0, "abcde", 1, 0, 0); test("abcdefghij", 5, 0, "abcde", 1, 1, -1); test("abcdefghij", 5, 0, "abcde", 1, 2, -2); test("abcdefghij", 5, 0, "abcde", 1, 3, -3); test("abcdefghij", 5, 0, "abcde", 1, 4, -4); test("abcdefghij", 5, 0, "abcde", 1, 5, -4); test("abcdefghij", 5, 0, "abcde", 2, 0, 0); test("abcdefghij", 5, 0, "abcde", 2, 1, -1); test("abcdefghij", 5, 0, "abcde", 2, 2, -2); test("abcdefghij", 5, 0, "abcde", 2, 3, -3); test("abcdefghij", 5, 0, "abcde", 2, 4, -3); test("abcdefghij", 5, 0, "abcde", 4, 0, 0); test("abcdefghij", 5, 0, "abcde", 4, 1, -1); test("abcdefghij", 5, 0, "abcde", 4, 2, -1); test("abcdefghij", 5, 0, "abcde", 5, 0, 0); test("abcdefghij", 5, 0, "abcde", 5, 1, 0); test("abcdefghij", 5, 0, "abcde", 6, 0, 0); test("abcdefghij", 5, 0, "abcdefghij", 0, 0, 0); test("abcdefghij", 5, 0, "abcdefghij", 0, 1, -1); test("abcdefghij", 5, 0, "abcdefghij", 0, 5, -5); test("abcdefghij", 5, 0, "abcdefghij", 0, 9, -9); test("abcdefghij", 5, 0, "abcdefghij", 0, 10, -10); test("abcdefghij", 5, 0, "abcdefghij", 0, 11, -10); test("abcdefghij", 5, 0, "abcdefghij", 1, 0, 0); test("abcdefghij", 5, 0, "abcdefghij", 1, 1, -1); test("abcdefghij", 5, 0, "abcdefghij", 1, 4, -4); test("abcdefghij", 5, 0, "abcdefghij", 1, 8, -8); test("abcdefghij", 5, 0, "abcdefghij", 1, 9, -9); test("abcdefghij", 5, 0, "abcdefghij", 1, 10, -9); test("abcdefghij", 5, 0, "abcdefghij", 5, 0, 0); test("abcdefghij", 5, 0, "abcdefghij", 5, 1, -1); test("abcdefghij", 5, 0, "abcdefghij", 5, 2, -2); test("abcdefghij", 5, 0, "abcdefghij", 5, 4, -4); test("abcdefghij", 5, 0, "abcdefghij", 5, 5, -5); test("abcdefghij", 5, 0, "abcdefghij", 5, 6, -5); test("abcdefghij", 5, 0, "abcdefghij", 9, 0, 0); test("abcdefghij", 5, 0, "abcdefghij", 9, 1, -1); test("abcdefghij", 5, 0, "abcdefghij", 9, 2, -1); test("abcdefghij", 5, 0, "abcdefghij", 10, 0, 0); test("abcdefghij", 5, 0, "abcdefghij", 10, 1, 0); test("abcdefghij", 5, 0, "abcdefghij", 11, 0, 0); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghij", 5, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 5, 1, "", 0, 0, 1); test("abcdefghij", 5, 1, "", 0, 1, 1); test("abcdefghij", 5, 1, "", 1, 0, 0); test("abcdefghij", 5, 1, "abcde", 0, 0, 1); test("abcdefghij", 5, 1, "abcde", 0, 1, 5); test("abcdefghij", 5, 1, "abcde", 0, 2, 5); test("abcdefghij", 5, 1, "abcde", 0, 4, 5); test("abcdefghij", 5, 1, "abcde", 0, 5, 5); test("abcdefghij", 5, 1, "abcde", 0, 6, 5); test("abcdefghij", 5, 1, "abcde", 1, 0, 1); test("abcdefghij", 5, 1, "abcde", 1, 1, 4); test("abcdefghij", 5, 1, "abcde", 1, 2, 4); test("abcdefghij", 5, 1, "abcde", 1, 3, 4); test("abcdefghij", 5, 1, "abcde", 1, 4, 4); } void test29() { test("abcdefghij", 5, 1, "abcde", 1, 5, 4); test("abcdefghij", 5, 1, "abcde", 2, 0, 1); test("abcdefghij", 5, 1, "abcde", 2, 1, 3); test("abcdefghij", 5, 1, "abcde", 2, 2, 3); test("abcdefghij", 5, 1, "abcde", 2, 3, 3); test("abcdefghij", 5, 1, "abcde", 2, 4, 3); test("abcdefghij", 5, 1, "abcde", 4, 0, 1); test("abcdefghij", 5, 1, "abcde", 4, 1, 1); test("abcdefghij", 5, 1, "abcde", 4, 2, 1); test("abcdefghij", 5, 1, "abcde", 5, 0, 1); test("abcdefghij", 5, 1, "abcde", 5, 1, 1); test("abcdefghij", 5, 1, "abcde", 6, 0, 0); test("abcdefghij", 5, 1, "abcdefghij", 0, 0, 1); test("abcdefghij", 5, 1, "abcdefghij", 0, 1, 5); test("abcdefghij", 5, 1, "abcdefghij", 0, 5, 5); test("abcdefghij", 5, 1, "abcdefghij", 0, 9, 5); test("abcdefghij", 5, 1, "abcdefghij", 0, 10, 5); test("abcdefghij", 5, 1, "abcdefghij", 0, 11, 5); test("abcdefghij", 5, 1, "abcdefghij", 1, 0, 1); test("abcdefghij", 5, 1, "abcdefghij", 1, 1, 4); test("abcdefghij", 5, 1, "abcdefghij", 1, 4, 4); test("abcdefghij", 5, 1, "abcdefghij", 1, 8, 4); test("abcdefghij", 5, 1, "abcdefghij", 1, 9, 4); test("abcdefghij", 5, 1, "abcdefghij", 1, 10, 4); test("abcdefghij", 5, 1, "abcdefghij", 5, 0, 1); test("abcdefghij", 5, 1, "abcdefghij", 5, 1, 0); test("abcdefghij", 5, 1, "abcdefghij", 5, 2, -1); test("abcdefghij", 5, 1, "abcdefghij", 5, 4, -3); test("abcdefghij", 5, 1, "abcdefghij", 5, 5, -4); test("abcdefghij", 5, 1, "abcdefghij", 5, 6, -4); test("abcdefghij", 5, 1, "abcdefghij", 9, 0, 1); test("abcdefghij", 5, 1, "abcdefghij", 9, 1, -4); test("abcdefghij", 5, 1, "abcdefghij", 9, 2, -4); test("abcdefghij", 5, 1, "abcdefghij", 10, 0, 1); test("abcdefghij", 5, 1, "abcdefghij", 10, 1, 1); test("abcdefghij", 5, 1, "abcdefghij", 11, 0, 0); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 0, 0, 1); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 0, 1, 5); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 0, 10, 5); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 0, 19, 5); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 0, 20, 5); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 0, 21, 5); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 1, 0, 1); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 1, 1, 4); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 1, 9, 4); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 1, 18, 4); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 1, 19, 4); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 1, 20, 4); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 10, 0, 1); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 10, 1, -5); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 10, 9, -5); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 10, 10, -5); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 10, 11, -5); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 19, 0, 1); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 19, 1, -14); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 19, 2, -14); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 20, 0, 1); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 20, 1, 1); test("abcdefghij", 5, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 5, 2, "", 0, 0, 2); test("abcdefghij", 5, 2, "", 0, 1, 2); test("abcdefghij", 5, 2, "", 1, 0, 0); test("abcdefghij", 5, 2, "abcde", 0, 0, 2); test("abcdefghij", 5, 2, "abcde", 0, 1, 5); test("abcdefghij", 5, 2, "abcde", 0, 2, 5); test("abcdefghij", 5, 2, "abcde", 0, 4, 5); test("abcdefghij", 5, 2, "abcde", 0, 5, 5); test("abcdefghij", 5, 2, "abcde", 0, 6, 5); test("abcdefghij", 5, 2, "abcde", 1, 0, 2); test("abcdefghij", 5, 2, "abcde", 1, 1, 4); test("abcdefghij", 5, 2, "abcde", 1, 2, 4); test("abcdefghij", 5, 2, "abcde", 1, 3, 4); test("abcdefghij", 5, 2, "abcde", 1, 4, 4); test("abcdefghij", 5, 2, "abcde", 1, 5, 4); test("abcdefghij", 5, 2, "abcde", 2, 0, 2); test("abcdefghij", 5, 2, "abcde", 2, 1, 3); test("abcdefghij", 5, 2, "abcde", 2, 2, 3); test("abcdefghij", 5, 2, "abcde", 2, 3, 3); test("abcdefghij", 5, 2, "abcde", 2, 4, 3); test("abcdefghij", 5, 2, "abcde", 4, 0, 2); test("abcdefghij", 5, 2, "abcde", 4, 1, 1); test("abcdefghij", 5, 2, "abcde", 4, 2, 1); test("abcdefghij", 5, 2, "abcde", 5, 0, 2); test("abcdefghij", 5, 2, "abcde", 5, 1, 2); test("abcdefghij", 5, 2, "abcde", 6, 0, 0); test("abcdefghij", 5, 2, "abcdefghij", 0, 0, 2); test("abcdefghij", 5, 2, "abcdefghij", 0, 1, 5); test("abcdefghij", 5, 2, "abcdefghij", 0, 5, 5); test("abcdefghij", 5, 2, "abcdefghij", 0, 9, 5); test("abcdefghij", 5, 2, "abcdefghij", 0, 10, 5); test("abcdefghij", 5, 2, "abcdefghij", 0, 11, 5); test("abcdefghij", 5, 2, "abcdefghij", 1, 0, 2); test("abcdefghij", 5, 2, "abcdefghij", 1, 1, 4); test("abcdefghij", 5, 2, "abcdefghij", 1, 4, 4); test("abcdefghij", 5, 2, "abcdefghij", 1, 8, 4); test("abcdefghij", 5, 2, "abcdefghij", 1, 9, 4); test("abcdefghij", 5, 2, "abcdefghij", 1, 10, 4); test("abcdefghij", 5, 2, "abcdefghij", 5, 0, 2); test("abcdefghij", 5, 2, "abcdefghij", 5, 1, 1); } void test30() { test("abcdefghij", 5, 2, "abcdefghij", 5, 2, 0); test("abcdefghij", 5, 2, "abcdefghij", 5, 4, -2); test("abcdefghij", 5, 2, "abcdefghij", 5, 5, -3); test("abcdefghij", 5, 2, "abcdefghij", 5, 6, -3); test("abcdefghij", 5, 2, "abcdefghij", 9, 0, 2); test("abcdefghij", 5, 2, "abcdefghij", 9, 1, -4); test("abcdefghij", 5, 2, "abcdefghij", 9, 2, -4); test("abcdefghij", 5, 2, "abcdefghij", 10, 0, 2); test("abcdefghij", 5, 2, "abcdefghij", 10, 1, 2); test("abcdefghij", 5, 2, "abcdefghij", 11, 0, 0); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 0, 0, 2); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 0, 1, 5); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 0, 10, 5); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 0, 19, 5); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 0, 20, 5); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 0, 21, 5); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 1, 0, 2); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 1, 1, 4); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 1, 9, 4); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 1, 18, 4); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 1, 19, 4); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 1, 20, 4); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 10, 0, 2); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 10, 1, -5); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 10, 9, -5); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 10, 10, -5); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 10, 11, -5); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 19, 0, 2); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 19, 1, -14); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 19, 2, -14); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 20, 0, 2); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 20, 1, 2); test("abcdefghij", 5, 2, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 5, 4, "", 0, 0, 4); test("abcdefghij", 5, 4, "", 0, 1, 4); test("abcdefghij", 5, 4, "", 1, 0, 0); test("abcdefghij", 5, 4, "abcde", 0, 0, 4); test("abcdefghij", 5, 4, "abcde", 0, 1, 5); test("abcdefghij", 5, 4, "abcde", 0, 2, 5); test("abcdefghij", 5, 4, "abcde", 0, 4, 5); test("abcdefghij", 5, 4, "abcde", 0, 5, 5); test("abcdefghij", 5, 4, "abcde", 0, 6, 5); test("abcdefghij", 5, 4, "abcde", 1, 0, 4); test("abcdefghij", 5, 4, "abcde", 1, 1, 4); test("abcdefghij", 5, 4, "abcde", 1, 2, 4); test("abcdefghij", 5, 4, "abcde", 1, 3, 4); test("abcdefghij", 5, 4, "abcde", 1, 4, 4); test("abcdefghij", 5, 4, "abcde", 1, 5, 4); test("abcdefghij", 5, 4, "abcde", 2, 0, 4); test("abcdefghij", 5, 4, "abcde", 2, 1, 3); test("abcdefghij", 5, 4, "abcde", 2, 2, 3); test("abcdefghij", 5, 4, "abcde", 2, 3, 3); test("abcdefghij", 5, 4, "abcde", 2, 4, 3); test("abcdefghij", 5, 4, "abcde", 4, 0, 4); test("abcdefghij", 5, 4, "abcde", 4, 1, 1); test("abcdefghij", 5, 4, "abcde", 4, 2, 1); test("abcdefghij", 5, 4, "abcde", 5, 0, 4); test("abcdefghij", 5, 4, "abcde", 5, 1, 4); test("abcdefghij", 5, 4, "abcde", 6, 0, 0); test("abcdefghij", 5, 4, "abcdefghij", 0, 0, 4); test("abcdefghij", 5, 4, "abcdefghij", 0, 1, 5); test("abcdefghij", 5, 4, "abcdefghij", 0, 5, 5); test("abcdefghij", 5, 4, "abcdefghij", 0, 9, 5); test("abcdefghij", 5, 4, "abcdefghij", 0, 10, 5); test("abcdefghij", 5, 4, "abcdefghij", 0, 11, 5); test("abcdefghij", 5, 4, "abcdefghij", 1, 0, 4); test("abcdefghij", 5, 4, "abcdefghij", 1, 1, 4); test("abcdefghij", 5, 4, "abcdefghij", 1, 4, 4); test("abcdefghij", 5, 4, "abcdefghij", 1, 8, 4); test("abcdefghij", 5, 4, "abcdefghij", 1, 9, 4); test("abcdefghij", 5, 4, "abcdefghij", 1, 10, 4); test("abcdefghij", 5, 4, "abcdefghij", 5, 0, 4); test("abcdefghij", 5, 4, "abcdefghij", 5, 1, 3); test("abcdefghij", 5, 4, "abcdefghij", 5, 2, 2); test("abcdefghij", 5, 4, "abcdefghij", 5, 4, 0); test("abcdefghij", 5, 4, "abcdefghij", 5, 5, -1); test("abcdefghij", 5, 4, "abcdefghij", 5, 6, -1); test("abcdefghij", 5, 4, "abcdefghij", 9, 0, 4); test("abcdefghij", 5, 4, "abcdefghij", 9, 1, -4); test("abcdefghij", 5, 4, "abcdefghij", 9, 2, -4); test("abcdefghij", 5, 4, "abcdefghij", 10, 0, 4); test("abcdefghij", 5, 4, "abcdefghij", 10, 1, 4); test("abcdefghij", 5, 4, "abcdefghij", 11, 0, 0); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 0, 0, 4); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 0, 1, 5); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 0, 10, 5); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 0, 19, 5); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 0, 20, 5); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 0, 21, 5); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 1, 0, 4); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 1, 1, 4); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 1, 9, 4); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 1, 18, 4); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 1, 19, 4); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 1, 20, 4); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 10, 0, 4); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 10, 1, -5); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 10, 9, -5); } void test31() { test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 10, 10, -5); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 10, 11, -5); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 19, 0, 4); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 19, 1, -14); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 19, 2, -14); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 20, 0, 4); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 20, 1, 4); test("abcdefghij", 5, 4, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 5, 5, "", 0, 0, 5); test("abcdefghij", 5, 5, "", 0, 1, 5); test("abcdefghij", 5, 5, "", 1, 0, 0); test("abcdefghij", 5, 5, "abcde", 0, 0, 5); test("abcdefghij", 5, 5, "abcde", 0, 1, 5); test("abcdefghij", 5, 5, "abcde", 0, 2, 5); test("abcdefghij", 5, 5, "abcde", 0, 4, 5); test("abcdefghij", 5, 5, "abcde", 0, 5, 5); test("abcdefghij", 5, 5, "abcde", 0, 6, 5); test("abcdefghij", 5, 5, "abcde", 1, 0, 5); test("abcdefghij", 5, 5, "abcde", 1, 1, 4); test("abcdefghij", 5, 5, "abcde", 1, 2, 4); test("abcdefghij", 5, 5, "abcde", 1, 3, 4); test("abcdefghij", 5, 5, "abcde", 1, 4, 4); test("abcdefghij", 5, 5, "abcde", 1, 5, 4); test("abcdefghij", 5, 5, "abcde", 2, 0, 5); test("abcdefghij", 5, 5, "abcde", 2, 1, 3); test("abcdefghij", 5, 5, "abcde", 2, 2, 3); test("abcdefghij", 5, 5, "abcde", 2, 3, 3); test("abcdefghij", 5, 5, "abcde", 2, 4, 3); test("abcdefghij", 5, 5, "abcde", 4, 0, 5); test("abcdefghij", 5, 5, "abcde", 4, 1, 1); test("abcdefghij", 5, 5, "abcde", 4, 2, 1); test("abcdefghij", 5, 5, "abcde", 5, 0, 5); test("abcdefghij", 5, 5, "abcde", 5, 1, 5); test("abcdefghij", 5, 5, "abcde", 6, 0, 0); test("abcdefghij", 5, 5, "abcdefghij", 0, 0, 5); test("abcdefghij", 5, 5, "abcdefghij", 0, 1, 5); test("abcdefghij", 5, 5, "abcdefghij", 0, 5, 5); test("abcdefghij", 5, 5, "abcdefghij", 0, 9, 5); test("abcdefghij", 5, 5, "abcdefghij", 0, 10, 5); test("abcdefghij", 5, 5, "abcdefghij", 0, 11, 5); test("abcdefghij", 5, 5, "abcdefghij", 1, 0, 5); test("abcdefghij", 5, 5, "abcdefghij", 1, 1, 4); test("abcdefghij", 5, 5, "abcdefghij", 1, 4, 4); test("abcdefghij", 5, 5, "abcdefghij", 1, 8, 4); test("abcdefghij", 5, 5, "abcdefghij", 1, 9, 4); test("abcdefghij", 5, 5, "abcdefghij", 1, 10, 4); test("abcdefghij", 5, 5, "abcdefghij", 5, 0, 5); test("abcdefghij", 5, 5, "abcdefghij", 5, 1, 4); test("abcdefghij", 5, 5, "abcdefghij", 5, 2, 3); test("abcdefghij", 5, 5, "abcdefghij", 5, 4, 1); test("abcdefghij", 5, 5, "abcdefghij", 5, 5, 0); test("abcdefghij", 5, 5, "abcdefghij", 5, 6, 0); test("abcdefghij", 5, 5, "abcdefghij", 9, 0, 5); test("abcdefghij", 5, 5, "abcdefghij", 9, 1, -4); test("abcdefghij", 5, 5, "abcdefghij", 9, 2, -4); test("abcdefghij", 5, 5, "abcdefghij", 10, 0, 5); test("abcdefghij", 5, 5, "abcdefghij", 10, 1, 5); test("abcdefghij", 5, 5, "abcdefghij", 11, 0, 0); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 0, 0, 5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 0, 1, 5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 0, 10, 5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 0, 19, 5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 0, 20, 5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 0, 21, 5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 1, 0, 5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 1, 1, 4); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 1, 9, 4); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 1, 18, 4); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 1, 19, 4); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 1, 20, 4); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 10, 0, 5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 10, 1, -5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 10, 9, -5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 10, 10, -5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 10, 11, -5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 19, 0, 5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 19, 1, -14); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 19, 2, -14); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 20, 0, 5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 20, 1, 5); test("abcdefghij", 5, 5, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 5, 6, "", 0, 0, 5); test("abcdefghij", 5, 6, "", 0, 1, 5); test("abcdefghij", 5, 6, "", 1, 0, 0); test("abcdefghij", 5, 6, "abcde", 0, 0, 5); test("abcdefghij", 5, 6, "abcde", 0, 1, 5); test("abcdefghij", 5, 6, "abcde", 0, 2, 5); test("abcdefghij", 5, 6, "abcde", 0, 4, 5); test("abcdefghij", 5, 6, "abcde", 0, 5, 5); test("abcdefghij", 5, 6, "abcde", 0, 6, 5); test("abcdefghij", 5, 6, "abcde", 1, 0, 5); test("abcdefghij", 5, 6, "abcde", 1, 1, 4); test("abcdefghij", 5, 6, "abcde", 1, 2, 4); test("abcdefghij", 5, 6, "abcde", 1, 3, 4); test("abcdefghij", 5, 6, "abcde", 1, 4, 4); test("abcdefghij", 5, 6, "abcde", 1, 5, 4); test("abcdefghij", 5, 6, "abcde", 2, 0, 5); test("abcdefghij", 5, 6, "abcde", 2, 1, 3); test("abcdefghij", 5, 6, "abcde", 2, 2, 3); } void test32() { test("abcdefghij", 5, 6, "abcde", 2, 3, 3); test("abcdefghij", 5, 6, "abcde", 2, 4, 3); test("abcdefghij", 5, 6, "abcde", 4, 0, 5); test("abcdefghij", 5, 6, "abcde", 4, 1, 1); test("abcdefghij", 5, 6, "abcde", 4, 2, 1); test("abcdefghij", 5, 6, "abcde", 5, 0, 5); test("abcdefghij", 5, 6, "abcde", 5, 1, 5); test("abcdefghij", 5, 6, "abcde", 6, 0, 0); test("abcdefghij", 5, 6, "abcdefghij", 0, 0, 5); test("abcdefghij", 5, 6, "abcdefghij", 0, 1, 5); test("abcdefghij", 5, 6, "abcdefghij", 0, 5, 5); test("abcdefghij", 5, 6, "abcdefghij", 0, 9, 5); test("abcdefghij", 5, 6, "abcdefghij", 0, 10, 5); test("abcdefghij", 5, 6, "abcdefghij", 0, 11, 5); test("abcdefghij", 5, 6, "abcdefghij", 1, 0, 5); test("abcdefghij", 5, 6, "abcdefghij", 1, 1, 4); test("abcdefghij", 5, 6, "abcdefghij", 1, 4, 4); test("abcdefghij", 5, 6, "abcdefghij", 1, 8, 4); test("abcdefghij", 5, 6, "abcdefghij", 1, 9, 4); test("abcdefghij", 5, 6, "abcdefghij", 1, 10, 4); test("abcdefghij", 5, 6, "abcdefghij", 5, 0, 5); test("abcdefghij", 5, 6, "abcdefghij", 5, 1, 4); test("abcdefghij", 5, 6, "abcdefghij", 5, 2, 3); test("abcdefghij", 5, 6, "abcdefghij", 5, 4, 1); test("abcdefghij", 5, 6, "abcdefghij", 5, 5, 0); test("abcdefghij", 5, 6, "abcdefghij", 5, 6, 0); test("abcdefghij", 5, 6, "abcdefghij", 9, 0, 5); test("abcdefghij", 5, 6, "abcdefghij", 9, 1, -4); test("abcdefghij", 5, 6, "abcdefghij", 9, 2, -4); test("abcdefghij", 5, 6, "abcdefghij", 10, 0, 5); test("abcdefghij", 5, 6, "abcdefghij", 10, 1, 5); test("abcdefghij", 5, 6, "abcdefghij", 11, 0, 0); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 0, 0, 5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 0, 1, 5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 0, 10, 5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 0, 19, 5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 0, 20, 5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 0, 21, 5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 1, 0, 5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 1, 1, 4); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 1, 9, 4); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 1, 18, 4); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 1, 19, 4); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 1, 20, 4); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 10, 0, 5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 10, 1, -5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 10, 9, -5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 10, 10, -5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 10, 11, -5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 19, 0, 5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 19, 1, -14); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 19, 2, -14); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 20, 0, 5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 20, 1, 5); test("abcdefghij", 5, 6, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 9, 0, "", 0, 0, 0); test("abcdefghij", 9, 0, "", 0, 1, 0); test("abcdefghij", 9, 0, "", 1, 0, 0); test("abcdefghij", 9, 0, "abcde", 0, 0, 0); test("abcdefghij", 9, 0, "abcde", 0, 1, -1); test("abcdefghij", 9, 0, "abcde", 0, 2, -2); test("abcdefghij", 9, 0, "abcde", 0, 4, -4); test("abcdefghij", 9, 0, "abcde", 0, 5, -5); test("abcdefghij", 9, 0, "abcde", 0, 6, -5); test("abcdefghij", 9, 0, "abcde", 1, 0, 0); test("abcdefghij", 9, 0, "abcde", 1, 1, -1); test("abcdefghij", 9, 0, "abcde", 1, 2, -2); test("abcdefghij", 9, 0, "abcde", 1, 3, -3); test("abcdefghij", 9, 0, "abcde", 1, 4, -4); test("abcdefghij", 9, 0, "abcde", 1, 5, -4); test("abcdefghij", 9, 0, "abcde", 2, 0, 0); test("abcdefghij", 9, 0, "abcde", 2, 1, -1); test("abcdefghij", 9, 0, "abcde", 2, 2, -2); test("abcdefghij", 9, 0, "abcde", 2, 3, -3); test("abcdefghij", 9, 0, "abcde", 2, 4, -3); test("abcdefghij", 9, 0, "abcde", 4, 0, 0); test("abcdefghij", 9, 0, "abcde", 4, 1, -1); test("abcdefghij", 9, 0, "abcde", 4, 2, -1); test("abcdefghij", 9, 0, "abcde", 5, 0, 0); test("abcdefghij", 9, 0, "abcde", 5, 1, 0); test("abcdefghij", 9, 0, "abcde", 6, 0, 0); test("abcdefghij", 9, 0, "abcdefghij", 0, 0, 0); test("abcdefghij", 9, 0, "abcdefghij", 0, 1, -1); test("abcdefghij", 9, 0, "abcdefghij", 0, 5, -5); test("abcdefghij", 9, 0, "abcdefghij", 0, 9, -9); test("abcdefghij", 9, 0, "abcdefghij", 0, 10, -10); test("abcdefghij", 9, 0, "abcdefghij", 0, 11, -10); test("abcdefghij", 9, 0, "abcdefghij", 1, 0, 0); test("abcdefghij", 9, 0, "abcdefghij", 1, 1, -1); test("abcdefghij", 9, 0, "abcdefghij", 1, 4, -4); test("abcdefghij", 9, 0, "abcdefghij", 1, 8, -8); test("abcdefghij", 9, 0, "abcdefghij", 1, 9, -9); test("abcdefghij", 9, 0, "abcdefghij", 1, 10, -9); test("abcdefghij", 9, 0, "abcdefghij", 5, 0, 0); test("abcdefghij", 9, 0, "abcdefghij", 5, 1, -1); test("abcdefghij", 9, 0, "abcdefghij", 5, 2, -2); test("abcdefghij", 9, 0, "abcdefghij", 5, 4, -4); test("abcdefghij", 9, 0, "abcdefghij", 5, 5, -5); test("abcdefghij", 9, 0, "abcdefghij", 5, 6, -5); } void test33() { test("abcdefghij", 9, 0, "abcdefghij", 9, 0, 0); test("abcdefghij", 9, 0, "abcdefghij", 9, 1, -1); test("abcdefghij", 9, 0, "abcdefghij", 9, 2, -1); test("abcdefghij", 9, 0, "abcdefghij", 10, 0, 0); test("abcdefghij", 9, 0, "abcdefghij", 10, 1, 0); test("abcdefghij", 9, 0, "abcdefghij", 11, 0, 0); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghij", 9, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 9, 1, "", 0, 0, 1); test("abcdefghij", 9, 1, "", 0, 1, 1); test("abcdefghij", 9, 1, "", 1, 0, 0); test("abcdefghij", 9, 1, "abcde", 0, 0, 1); test("abcdefghij", 9, 1, "abcde", 0, 1, 9); test("abcdefghij", 9, 1, "abcde", 0, 2, 9); test("abcdefghij", 9, 1, "abcde", 0, 4, 9); test("abcdefghij", 9, 1, "abcde", 0, 5, 9); test("abcdefghij", 9, 1, "abcde", 0, 6, 9); test("abcdefghij", 9, 1, "abcde", 1, 0, 1); test("abcdefghij", 9, 1, "abcde", 1, 1, 8); test("abcdefghij", 9, 1, "abcde", 1, 2, 8); test("abcdefghij", 9, 1, "abcde", 1, 3, 8); test("abcdefghij", 9, 1, "abcde", 1, 4, 8); test("abcdefghij", 9, 1, "abcde", 1, 5, 8); test("abcdefghij", 9, 1, "abcde", 2, 0, 1); test("abcdefghij", 9, 1, "abcde", 2, 1, 7); test("abcdefghij", 9, 1, "abcde", 2, 2, 7); test("abcdefghij", 9, 1, "abcde", 2, 3, 7); test("abcdefghij", 9, 1, "abcde", 2, 4, 7); test("abcdefghij", 9, 1, "abcde", 4, 0, 1); test("abcdefghij", 9, 1, "abcde", 4, 1, 5); test("abcdefghij", 9, 1, "abcde", 4, 2, 5); test("abcdefghij", 9, 1, "abcde", 5, 0, 1); test("abcdefghij", 9, 1, "abcde", 5, 1, 1); test("abcdefghij", 9, 1, "abcde", 6, 0, 0); test("abcdefghij", 9, 1, "abcdefghij", 0, 0, 1); test("abcdefghij", 9, 1, "abcdefghij", 0, 1, 9); test("abcdefghij", 9, 1, "abcdefghij", 0, 5, 9); test("abcdefghij", 9, 1, "abcdefghij", 0, 9, 9); test("abcdefghij", 9, 1, "abcdefghij", 0, 10, 9); test("abcdefghij", 9, 1, "abcdefghij", 0, 11, 9); test("abcdefghij", 9, 1, "abcdefghij", 1, 0, 1); test("abcdefghij", 9, 1, "abcdefghij", 1, 1, 8); test("abcdefghij", 9, 1, "abcdefghij", 1, 4, 8); test("abcdefghij", 9, 1, "abcdefghij", 1, 8, 8); test("abcdefghij", 9, 1, "abcdefghij", 1, 9, 8); test("abcdefghij", 9, 1, "abcdefghij", 1, 10, 8); test("abcdefghij", 9, 1, "abcdefghij", 5, 0, 1); test("abcdefghij", 9, 1, "abcdefghij", 5, 1, 4); test("abcdefghij", 9, 1, "abcdefghij", 5, 2, 4); test("abcdefghij", 9, 1, "abcdefghij", 5, 4, 4); test("abcdefghij", 9, 1, "abcdefghij", 5, 5, 4); test("abcdefghij", 9, 1, "abcdefghij", 5, 6, 4); test("abcdefghij", 9, 1, "abcdefghij", 9, 0, 1); test("abcdefghij", 9, 1, "abcdefghij", 9, 1, 0); test("abcdefghij", 9, 1, "abcdefghij", 9, 2, 0); test("abcdefghij", 9, 1, "abcdefghij", 10, 0, 1); test("abcdefghij", 9, 1, "abcdefghij", 10, 1, 1); test("abcdefghij", 9, 1, "abcdefghij", 11, 0, 0); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 0, 0, 1); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 0, 1, 9); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 0, 10, 9); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 0, 19, 9); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 0, 20, 9); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 0, 21, 9); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 1, 0, 1); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 1, 1, 8); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 1, 9, 8); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 1, 18, 8); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 1, 19, 8); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 1, 20, 8); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 10, 0, 1); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 10, 5, -1); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 10, 9, -1); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 10, 10, -1); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 10, 11, -1); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 19, 0, 1); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 19, 1, -10); } void test34() { test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 19, 2, -10); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 20, 0, 1); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 20, 1, 1); test("abcdefghij", 9, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 9, 2, "", 0, 0, 1); test("abcdefghij", 9, 2, "", 0, 1, 1); test("abcdefghij", 9, 2, "", 1, 0, 0); test("abcdefghij", 9, 2, "abcde", 0, 0, 1); test("abcdefghij", 9, 2, "abcde", 0, 1, 9); test("abcdefghij", 9, 2, "abcde", 0, 2, 9); test("abcdefghij", 9, 2, "abcde", 0, 4, 9); test("abcdefghij", 9, 2, "abcde", 0, 5, 9); test("abcdefghij", 9, 2, "abcde", 0, 6, 9); test("abcdefghij", 9, 2, "abcde", 1, 0, 1); test("abcdefghij", 9, 2, "abcde", 1, 1, 8); test("abcdefghij", 9, 2, "abcde", 1, 2, 8); test("abcdefghij", 9, 2, "abcde", 1, 3, 8); test("abcdefghij", 9, 2, "abcde", 1, 4, 8); test("abcdefghij", 9, 2, "abcde", 1, 5, 8); test("abcdefghij", 9, 2, "abcde", 2, 0, 1); test("abcdefghij", 9, 2, "abcde", 2, 1, 7); test("abcdefghij", 9, 2, "abcde", 2, 2, 7); test("abcdefghij", 9, 2, "abcde", 2, 3, 7); test("abcdefghij", 9, 2, "abcde", 2, 4, 7); test("abcdefghij", 9, 2, "abcde", 4, 0, 1); test("abcdefghij", 9, 2, "abcde", 4, 1, 5); test("abcdefghij", 9, 2, "abcde", 4, 2, 5); test("abcdefghij", 9, 2, "abcde", 5, 0, 1); test("abcdefghij", 9, 2, "abcde", 5, 1, 1); test("abcdefghij", 9, 2, "abcde", 6, 0, 0); test("abcdefghij", 9, 2, "abcdefghij", 0, 0, 1); test("abcdefghij", 9, 2, "abcdefghij", 0, 1, 9); test("abcdefghij", 9, 2, "abcdefghij", 0, 5, 9); test("abcdefghij", 9, 2, "abcdefghij", 0, 9, 9); test("abcdefghij", 9, 2, "abcdefghij", 0, 10, 9); test("abcdefghij", 9, 2, "abcdefghij", 0, 11, 9); test("abcdefghij", 9, 2, "abcdefghij", 1, 0, 1); test("abcdefghij", 9, 2, "abcdefghij", 1, 1, 8); test("abcdefghij", 9, 2, "abcdefghij", 1, 4, 8); test("abcdefghij", 9, 2, "abcdefghij", 1, 8, 8); test("abcdefghij", 9, 2, "abcdefghij", 1, 9, 8); test("abcdefghij", 9, 2, "abcdefghij", 1, 10, 8); test("abcdefghij", 9, 2, "abcdefghij", 5, 0, 1); test("abcdefghij", 9, 2, "abcdefghij", 5, 1, 4); test("abcdefghij", 9, 2, "abcdefghij", 5, 2, 4); test("abcdefghij", 9, 2, "abcdefghij", 5, 4, 4); test("abcdefghij", 9, 2, "abcdefghij", 5, 5, 4); test("abcdefghij", 9, 2, "abcdefghij", 5, 6, 4); test("abcdefghij", 9, 2, "abcdefghij", 9, 0, 1); test("abcdefghij", 9, 2, "abcdefghij", 9, 1, 0); test("abcdefghij", 9, 2, "abcdefghij", 9, 2, 0); test("abcdefghij", 9, 2, "abcdefghij", 10, 0, 1); test("abcdefghij", 9, 2, "abcdefghij", 10, 1, 1); test("abcdefghij", 9, 2, "abcdefghij", 11, 0, 0); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 0, 0, 1); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 0, 1, 9); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 0, 10, 9); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 0, 19, 9); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 0, 20, 9); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 0, 21, 9); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 1, 0, 1); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 1, 1, 8); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 1, 9, 8); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 1, 18, 8); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 1, 19, 8); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 1, 20, 8); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 10, 0, 1); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 10, 5, -1); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 10, 9, -1); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 10, 10, -1); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 10, 11, -1); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 19, 0, 1); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 19, 1, -10); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 19, 2, -10); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 20, 0, 1); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 20, 1, 1); test("abcdefghij", 9, 2, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 10, 0, "", 0, 0, 0); test("abcdefghij", 10, 0, "", 0, 1, 0); test("abcdefghij", 10, 0, "", 1, 0, 0); test("abcdefghij", 10, 0, "abcde", 0, 0, 0); test("abcdefghij", 10, 0, "abcde", 0, 1, -1); test("abcdefghij", 10, 0, "abcde", 0, 2, -2); test("abcdefghij", 10, 0, "abcde", 0, 4, -4); test("abcdefghij", 10, 0, "abcde", 0, 5, -5); test("abcdefghij", 10, 0, "abcde", 0, 6, -5); test("abcdefghij", 10, 0, "abcde", 1, 0, 0); test("abcdefghij", 10, 0, "abcde", 1, 1, -1); test("abcdefghij", 10, 0, "abcde", 1, 2, -2); test("abcdefghij", 10, 0, "abcde", 1, 3, -3); test("abcdefghij", 10, 0, "abcde", 1, 4, -4); test("abcdefghij", 10, 0, "abcde", 1, 5, -4); test("abcdefghij", 10, 0, "abcde", 2, 0, 0); test("abcdefghij", 10, 0, "abcde", 2, 1, -1); test("abcdefghij", 10, 0, "abcde", 2, 2, -2); test("abcdefghij", 10, 0, "abcde", 2, 3, -3); test("abcdefghij", 10, 0, "abcde", 2, 4, -3); test("abcdefghij", 10, 0, "abcde", 4, 0, 0); test("abcdefghij", 10, 0, "abcde", 4, 1, -1); } void test35() { test("abcdefghij", 10, 0, "abcde", 4, 2, -1); test("abcdefghij", 10, 0, "abcde", 5, 0, 0); test("abcdefghij", 10, 0, "abcde", 5, 1, 0); test("abcdefghij", 10, 0, "abcde", 6, 0, 0); test("abcdefghij", 10, 0, "abcdefghij", 0, 0, 0); test("abcdefghij", 10, 0, "abcdefghij", 0, 1, -1); test("abcdefghij", 10, 0, "abcdefghij", 0, 5, -5); test("abcdefghij", 10, 0, "abcdefghij", 0, 9, -9); test("abcdefghij", 10, 0, "abcdefghij", 0, 10, -10); test("abcdefghij", 10, 0, "abcdefghij", 0, 11, -10); test("abcdefghij", 10, 0, "abcdefghij", 1, 0, 0); test("abcdefghij", 10, 0, "abcdefghij", 1, 1, -1); test("abcdefghij", 10, 0, "abcdefghij", 1, 4, -4); test("abcdefghij", 10, 0, "abcdefghij", 1, 8, -8); test("abcdefghij", 10, 0, "abcdefghij", 1, 9, -9); test("abcdefghij", 10, 0, "abcdefghij", 1, 10, -9); test("abcdefghij", 10, 0, "abcdefghij", 5, 0, 0); test("abcdefghij", 10, 0, "abcdefghij", 5, 1, -1); test("abcdefghij", 10, 0, "abcdefghij", 5, 2, -2); test("abcdefghij", 10, 0, "abcdefghij", 5, 4, -4); test("abcdefghij", 10, 0, "abcdefghij", 5, 5, -5); test("abcdefghij", 10, 0, "abcdefghij", 5, 6, -5); test("abcdefghij", 10, 0, "abcdefghij", 9, 0, 0); test("abcdefghij", 10, 0, "abcdefghij", 9, 1, -1); test("abcdefghij", 10, 0, "abcdefghij", 9, 2, -1); test("abcdefghij", 10, 0, "abcdefghij", 10, 0, 0); test("abcdefghij", 10, 0, "abcdefghij", 10, 1, 0); test("abcdefghij", 10, 0, "abcdefghij", 11, 0, 0); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghij", 10, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 10, 1, "", 0, 0, 0); test("abcdefghij", 10, 1, "", 0, 1, 0); test("abcdefghij", 10, 1, "", 1, 0, 0); test("abcdefghij", 10, 1, "abcde", 0, 0, 0); test("abcdefghij", 10, 1, "abcde", 0, 1, -1); test("abcdefghij", 10, 1, "abcde", 0, 2, -2); test("abcdefghij", 10, 1, "abcde", 0, 4, -4); test("abcdefghij", 10, 1, "abcde", 0, 5, -5); test("abcdefghij", 10, 1, "abcde", 0, 6, -5); test("abcdefghij", 10, 1, "abcde", 1, 0, 0); test("abcdefghij", 10, 1, "abcde", 1, 1, -1); test("abcdefghij", 10, 1, "abcde", 1, 2, -2); test("abcdefghij", 10, 1, "abcde", 1, 3, -3); test("abcdefghij", 10, 1, "abcde", 1, 4, -4); test("abcdefghij", 10, 1, "abcde", 1, 5, -4); test("abcdefghij", 10, 1, "abcde", 2, 0, 0); test("abcdefghij", 10, 1, "abcde", 2, 1, -1); test("abcdefghij", 10, 1, "abcde", 2, 2, -2); test("abcdefghij", 10, 1, "abcde", 2, 3, -3); test("abcdefghij", 10, 1, "abcde", 2, 4, -3); test("abcdefghij", 10, 1, "abcde", 4, 0, 0); test("abcdefghij", 10, 1, "abcde", 4, 1, -1); test("abcdefghij", 10, 1, "abcde", 4, 2, -1); test("abcdefghij", 10, 1, "abcde", 5, 0, 0); test("abcdefghij", 10, 1, "abcde", 5, 1, 0); test("abcdefghij", 10, 1, "abcde", 6, 0, 0); test("abcdefghij", 10, 1, "abcdefghij", 0, 0, 0); test("abcdefghij", 10, 1, "abcdefghij", 0, 1, -1); test("abcdefghij", 10, 1, "abcdefghij", 0, 5, -5); test("abcdefghij", 10, 1, "abcdefghij", 0, 9, -9); test("abcdefghij", 10, 1, "abcdefghij", 0, 10, -10); test("abcdefghij", 10, 1, "abcdefghij", 0, 11, -10); test("abcdefghij", 10, 1, "abcdefghij", 1, 0, 0); test("abcdefghij", 10, 1, "abcdefghij", 1, 1, -1); test("abcdefghij", 10, 1, "abcdefghij", 1, 4, -4); test("abcdefghij", 10, 1, "abcdefghij", 1, 8, -8); test("abcdefghij", 10, 1, "abcdefghij", 1, 9, -9); test("abcdefghij", 10, 1, "abcdefghij", 1, 10, -9); test("abcdefghij", 10, 1, "abcdefghij", 5, 0, 0); test("abcdefghij", 10, 1, "abcdefghij", 5, 1, -1); test("abcdefghij", 10, 1, "abcdefghij", 5, 2, -2); test("abcdefghij", 10, 1, "abcdefghij", 5, 4, -4); test("abcdefghij", 10, 1, "abcdefghij", 5, 5, -5); test("abcdefghij", 10, 1, "abcdefghij", 5, 6, -5); test("abcdefghij", 10, 1, "abcdefghij", 9, 0, 0); test("abcdefghij", 10, 1, "abcdefghij", 9, 1, -1); test("abcdefghij", 10, 1, "abcdefghij", 9, 2, -1); test("abcdefghij", 10, 1, "abcdefghij", 10, 0, 0); } void test36() { test("abcdefghij", 10, 1, "abcdefghij", 10, 1, 0); test("abcdefghij", 10, 1, "abcdefghij", 11, 0, 0); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 0, 1, -1); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 0, 10, -10); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 0, 19, -19); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 0, 20, -20); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 0, 21, -20); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 1, 9, -9); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 1, 18, -18); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 1, 19, -19); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 1, 20, -19); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 19, 1, -1); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 19, 2, -1); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 20, 0, 0); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghij", 10, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghij", 11, 0, "", 0, 0, 0); test("abcdefghij", 11, 0, "", 0, 1, 0); test("abcdefghij", 11, 0, "", 1, 0, 0); test("abcdefghij", 11, 0, "abcde", 0, 0, 0); test("abcdefghij", 11, 0, "abcde", 0, 1, 0); test("abcdefghij", 11, 0, "abcde", 0, 2, 0); test("abcdefghij", 11, 0, "abcde", 0, 4, 0); test("abcdefghij", 11, 0, "abcde", 0, 5, 0); test("abcdefghij", 11, 0, "abcde", 0, 6, 0); test("abcdefghij", 11, 0, "abcde", 1, 0, 0); test("abcdefghij", 11, 0, "abcde", 1, 1, 0); test("abcdefghij", 11, 0, "abcde", 1, 2, 0); test("abcdefghij", 11, 0, "abcde", 1, 3, 0); test("abcdefghij", 11, 0, "abcde", 1, 4, 0); test("abcdefghij", 11, 0, "abcde", 1, 5, 0); test("abcdefghij", 11, 0, "abcde", 2, 0, 0); test("abcdefghij", 11, 0, "abcde", 2, 1, 0); test("abcdefghij", 11, 0, "abcde", 2, 2, 0); test("abcdefghij", 11, 0, "abcde", 2, 3, 0); test("abcdefghij", 11, 0, "abcde", 2, 4, 0); test("abcdefghij", 11, 0, "abcde", 4, 0, 0); test("abcdefghij", 11, 0, "abcde", 4, 1, 0); test("abcdefghij", 11, 0, "abcde", 4, 2, 0); test("abcdefghij", 11, 0, "abcde", 5, 0, 0); test("abcdefghij", 11, 0, "abcde", 5, 1, 0); test("abcdefghij", 11, 0, "abcde", 6, 0, 0); test("abcdefghij", 11, 0, "abcdefghij", 0, 0, 0); test("abcdefghij", 11, 0, "abcdefghij", 0, 1, 0); test("abcdefghij", 11, 0, "abcdefghij", 0, 5, 0); test("abcdefghij", 11, 0, "abcdefghij", 0, 9, 0); test("abcdefghij", 11, 0, "abcdefghij", 0, 10, 0); test("abcdefghij", 11, 0, "abcdefghij", 0, 11, 0); test("abcdefghij", 11, 0, "abcdefghij", 1, 0, 0); test("abcdefghij", 11, 0, "abcdefghij", 1, 1, 0); test("abcdefghij", 11, 0, "abcdefghij", 1, 4, 0); test("abcdefghij", 11, 0, "abcdefghij", 1, 8, 0); test("abcdefghij", 11, 0, "abcdefghij", 1, 9, 0); test("abcdefghij", 11, 0, "abcdefghij", 1, 10, 0); test("abcdefghij", 11, 0, "abcdefghij", 5, 0, 0); test("abcdefghij", 11, 0, "abcdefghij", 5, 1, 0); test("abcdefghij", 11, 0, "abcdefghij", 5, 2, 0); test("abcdefghij", 11, 0, "abcdefghij", 5, 4, 0); test("abcdefghij", 11, 0, "abcdefghij", 5, 5, 0); test("abcdefghij", 11, 0, "abcdefghij", 5, 6, 0); test("abcdefghij", 11, 0, "abcdefghij", 9, 0, 0); test("abcdefghij", 11, 0, "abcdefghij", 9, 1, 0); test("abcdefghij", 11, 0, "abcdefghij", 9, 2, 0); test("abcdefghij", 11, 0, "abcdefghij", 10, 0, 0); test("abcdefghij", 11, 0, "abcdefghij", 10, 1, 0); test("abcdefghij", 11, 0, "abcdefghij", 11, 0, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 0, 1, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 0, 10, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 0, 19, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 0, 20, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 0, 21, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 1, 1, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 1, 9, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 1, 18, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 1, 19, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 1, 20, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 10, 1, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 10, 5, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 10, 9, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 10, 10, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 10, 11, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 19, 1, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 19, 2, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghij", 11, 0, "abcdefghijklmnopqrst", 21, 0, 0); } void test37() { test("abcdefghijklmnopqrst", 0, 0, "", 0, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "", 0, 1, 0); test("abcdefghijklmnopqrst", 0, 0, "", 1, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcde", 0, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcde", 0, 1, -1); test("abcdefghijklmnopqrst", 0, 0, "abcde", 0, 2, -2); test("abcdefghijklmnopqrst", 0, 0, "abcde", 0, 4, -4); test("abcdefghijklmnopqrst", 0, 0, "abcde", 0, 5, -5); test("abcdefghijklmnopqrst", 0, 0, "abcde", 0, 6, -5); test("abcdefghijklmnopqrst", 0, 0, "abcde", 1, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcde", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 0, "abcde", 1, 2, -2); test("abcdefghijklmnopqrst", 0, 0, "abcde", 1, 3, -3); test("abcdefghijklmnopqrst", 0, 0, "abcde", 1, 4, -4); test("abcdefghijklmnopqrst", 0, 0, "abcde", 1, 5, -4); test("abcdefghijklmnopqrst", 0, 0, "abcde", 2, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcde", 2, 1, -1); test("abcdefghijklmnopqrst", 0, 0, "abcde", 2, 2, -2); test("abcdefghijklmnopqrst", 0, 0, "abcde", 2, 3, -3); test("abcdefghijklmnopqrst", 0, 0, "abcde", 2, 4, -3); test("abcdefghijklmnopqrst", 0, 0, "abcde", 4, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcde", 4, 1, -1); test("abcdefghijklmnopqrst", 0, 0, "abcde", 4, 2, -1); test("abcdefghijklmnopqrst", 0, 0, "abcde", 5, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcde", 5, 1, 0); test("abcdefghijklmnopqrst", 0, 0, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 0, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 0, 1, -1); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 0, 5, -5); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 0, 9, -9); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 0, 10, -10); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 0, 11, -10); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 1, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 1, 4, -4); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 1, 8, -8); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 1, 9, -9); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 1, 10, -9); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 5, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 5, 1, -1); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 5, 2, -2); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 5, 4, -4); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 5, 5, -5); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 5, 6, -5); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 9, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 9, 1, -1); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 9, 2, -1); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 10, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 10, 1, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghijklmnopqrst", 0, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 0, 1, "", 0, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "", 0, 1, 1); test("abcdefghijklmnopqrst", 0, 1, "", 1, 0, 0); test("abcdefghijklmnopqrst", 0, 1, "abcde", 0, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcde", 0, 1, 0); test("abcdefghijklmnopqrst", 0, 1, "abcde", 0, 2, -1); test("abcdefghijklmnopqrst", 0, 1, "abcde", 0, 4, -3); test("abcdefghijklmnopqrst", 0, 1, "abcde", 0, 5, -4); test("abcdefghijklmnopqrst", 0, 1, "abcde", 0, 6, -4); test("abcdefghijklmnopqrst", 0, 1, "abcde", 1, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcde", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 1, "abcde", 1, 2, -1); test("abcdefghijklmnopqrst", 0, 1, "abcde", 1, 3, -1); test("abcdefghijklmnopqrst", 0, 1, "abcde", 1, 4, -1); test("abcdefghijklmnopqrst", 0, 1, "abcde", 1, 5, -1); test("abcdefghijklmnopqrst", 0, 1, "abcde", 2, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcde", 2, 1, -2); test("abcdefghijklmnopqrst", 0, 1, "abcde", 2, 2, -2); test("abcdefghijklmnopqrst", 0, 1, "abcde", 2, 3, -2); test("abcdefghijklmnopqrst", 0, 1, "abcde", 2, 4, -2); test("abcdefghijklmnopqrst", 0, 1, "abcde", 4, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcde", 4, 1, -4); test("abcdefghijklmnopqrst", 0, 1, "abcde", 4, 2, -4); test("abcdefghijklmnopqrst", 0, 1, "abcde", 5, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcde", 5, 1, 1); test("abcdefghijklmnopqrst", 0, 1, "abcde", 6, 0, 0); } void test38() { test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 0, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 0, 1, 0); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 0, 5, -4); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 0, 9, -8); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 0, 10, -9); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 0, 11, -9); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 1, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 1, 4, -1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 1, 8, -1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 1, 9, -1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 1, 10, -1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 5, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 5, 1, -5); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 5, 2, -5); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 5, 4, -5); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 5, 5, -5); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 5, 6, -5); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 9, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 9, 1, -9); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 9, 2, -9); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 10, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 10, 1, 1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 0, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 0, 1, 0); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 0, 10, -9); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 0, 19, -18); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 0, 20, -19); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 0, 21, -19); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 1, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 1, 9, -1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 1, 18, -1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 1, 19, -1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 1, 20, -1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 10, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 10, 1, -10); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 10, 5, -10); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 10, 9, -10); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 19, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 19, 1, -19); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 19, 2, -19); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 20, 0, 1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 20, 1, 1); test("abcdefghijklmnopqrst", 0, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 0, 10, "", 0, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "", 0, 1, 10); test("abcdefghijklmnopqrst", 0, 10, "", 1, 0, 0); test("abcdefghijklmnopqrst", 0, 10, "abcde", 0, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcde", 0, 1, 9); test("abcdefghijklmnopqrst", 0, 10, "abcde", 0, 2, 8); test("abcdefghijklmnopqrst", 0, 10, "abcde", 0, 4, 6); test("abcdefghijklmnopqrst", 0, 10, "abcde", 0, 5, 5); test("abcdefghijklmnopqrst", 0, 10, "abcde", 0, 6, 5); test("abcdefghijklmnopqrst", 0, 10, "abcde", 1, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcde", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 10, "abcde", 1, 2, -1); test("abcdefghijklmnopqrst", 0, 10, "abcde", 1, 3, -1); test("abcdefghijklmnopqrst", 0, 10, "abcde", 1, 4, -1); test("abcdefghijklmnopqrst", 0, 10, "abcde", 1, 5, -1); test("abcdefghijklmnopqrst", 0, 10, "abcde", 2, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcde", 2, 1, -2); test("abcdefghijklmnopqrst", 0, 10, "abcde", 2, 2, -2); test("abcdefghijklmnopqrst", 0, 10, "abcde", 2, 3, -2); test("abcdefghijklmnopqrst", 0, 10, "abcde", 2, 4, -2); test("abcdefghijklmnopqrst", 0, 10, "abcde", 4, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcde", 4, 1, -4); test("abcdefghijklmnopqrst", 0, 10, "abcde", 4, 2, -4); test("abcdefghijklmnopqrst", 0, 10, "abcde", 5, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcde", 5, 1, 10); test("abcdefghijklmnopqrst", 0, 10, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 0, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 0, 1, 9); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 0, 5, 5); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 0, 9, 1); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 0, 10, 0); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 0, 11, 0); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 1, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 1, 4, -1); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 1, 8, -1); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 1, 9, -1); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 1, 10, -1); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 5, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 5, 1, -5); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 5, 2, -5); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 5, 4, -5); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 5, 5, -5); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 5, 6, -5); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 9, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 9, 1, -9); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 9, 2, -9); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 10, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 10, 1, 10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 0, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 0, 1, 9); } void test39() { test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 0, 10, 0); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 0, 19, -9); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 0, 20, -10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 0, 21, -10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 1, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 1, 9, -1); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 1, 18, -1); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 1, 19, -1); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 1, 20, -1); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 10, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 10, 1, -10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 10, 5, -10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 10, 9, -10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 19, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 19, 1, -19); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 19, 2, -19); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 20, 0, 10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 20, 1, 10); test("abcdefghijklmnopqrst", 0, 10, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 0, 19, "", 0, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "", 0, 1, 19); test("abcdefghijklmnopqrst", 0, 19, "", 1, 0, 0); test("abcdefghijklmnopqrst", 0, 19, "abcde", 0, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcde", 0, 1, 18); test("abcdefghijklmnopqrst", 0, 19, "abcde", 0, 2, 17); test("abcdefghijklmnopqrst", 0, 19, "abcde", 0, 4, 15); test("abcdefghijklmnopqrst", 0, 19, "abcde", 0, 5, 14); test("abcdefghijklmnopqrst", 0, 19, "abcde", 0, 6, 14); test("abcdefghijklmnopqrst", 0, 19, "abcde", 1, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcde", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 19, "abcde", 1, 2, -1); test("abcdefghijklmnopqrst", 0, 19, "abcde", 1, 3, -1); test("abcdefghijklmnopqrst", 0, 19, "abcde", 1, 4, -1); test("abcdefghijklmnopqrst", 0, 19, "abcde", 1, 5, -1); test("abcdefghijklmnopqrst", 0, 19, "abcde", 2, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcde", 2, 1, -2); test("abcdefghijklmnopqrst", 0, 19, "abcde", 2, 2, -2); test("abcdefghijklmnopqrst", 0, 19, "abcde", 2, 3, -2); test("abcdefghijklmnopqrst", 0, 19, "abcde", 2, 4, -2); test("abcdefghijklmnopqrst", 0, 19, "abcde", 4, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcde", 4, 1, -4); test("abcdefghijklmnopqrst", 0, 19, "abcde", 4, 2, -4); test("abcdefghijklmnopqrst", 0, 19, "abcde", 5, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcde", 5, 1, 19); test("abcdefghijklmnopqrst", 0, 19, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 0, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 0, 1, 18); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 0, 5, 14); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 0, 9, 10); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 0, 10, 9); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 0, 11, 9); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 1, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 1, 4, -1); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 1, 8, -1); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 1, 9, -1); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 1, 10, -1); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 5, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 5, 1, -5); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 5, 2, -5); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 5, 4, -5); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 5, 5, -5); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 5, 6, -5); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 9, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 9, 1, -9); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 9, 2, -9); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 10, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 10, 1, 19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 0, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 0, 1, 18); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 0, 10, 9); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 0, 19, 0); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 0, 20, -1); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 0, 21, -1); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 1, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 1, 9, -1); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 1, 18, -1); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 1, 19, -1); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 1, 20, -1); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 10, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 10, 1, -10); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 10, 5, -10); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 10, 9, -10); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 19, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 19, 1, -19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 19, 2, -19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 20, 0, 19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 20, 1, 19); test("abcdefghijklmnopqrst", 0, 19, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 0, 20, "", 0, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "", 0, 1, 20); test("abcdefghijklmnopqrst", 0, 20, "", 1, 0, 0); test("abcdefghijklmnopqrst", 0, 20, "abcde", 0, 0, 20); } void test40() { test("abcdefghijklmnopqrst", 0, 20, "abcde", 0, 1, 19); test("abcdefghijklmnopqrst", 0, 20, "abcde", 0, 2, 18); test("abcdefghijklmnopqrst", 0, 20, "abcde", 0, 4, 16); test("abcdefghijklmnopqrst", 0, 20, "abcde", 0, 5, 15); test("abcdefghijklmnopqrst", 0, 20, "abcde", 0, 6, 15); test("abcdefghijklmnopqrst", 0, 20, "abcde", 1, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcde", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 20, "abcde", 1, 2, -1); test("abcdefghijklmnopqrst", 0, 20, "abcde", 1, 3, -1); test("abcdefghijklmnopqrst", 0, 20, "abcde", 1, 4, -1); test("abcdefghijklmnopqrst", 0, 20, "abcde", 1, 5, -1); test("abcdefghijklmnopqrst", 0, 20, "abcde", 2, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcde", 2, 1, -2); test("abcdefghijklmnopqrst", 0, 20, "abcde", 2, 2, -2); test("abcdefghijklmnopqrst", 0, 20, "abcde", 2, 3, -2); test("abcdefghijklmnopqrst", 0, 20, "abcde", 2, 4, -2); test("abcdefghijklmnopqrst", 0, 20, "abcde", 4, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcde", 4, 1, -4); test("abcdefghijklmnopqrst", 0, 20, "abcde", 4, 2, -4); test("abcdefghijklmnopqrst", 0, 20, "abcde", 5, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcde", 5, 1, 20); test("abcdefghijklmnopqrst", 0, 20, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 0, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 0, 1, 19); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 0, 5, 15); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 0, 9, 11); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 0, 10, 10); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 0, 11, 10); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 1, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 1, 4, -1); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 1, 8, -1); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 1, 9, -1); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 1, 10, -1); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 5, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 5, 1, -5); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 5, 2, -5); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 5, 4, -5); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 5, 5, -5); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 5, 6, -5); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 9, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 9, 1, -9); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 9, 2, -9); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 10, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 10, 1, 20); test("abcdefghijklmnopqrst", 0, 20, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 0, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 0, 1, 19); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 0, 10, 10); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 0, 19, 1); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 0, 20, 0); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 0, 21, 0); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 1, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 1, 9, -1); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 1, 18, -1); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 1, 19, -1); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 1, 20, -1); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 10, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 10, 1, -10); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 10, 5, -10); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 10, 9, -10); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 19, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 19, 1, -19); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 19, 2, -19); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 20, 0, 20); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 20, 1, 20); test("abcdefghijklmnopqrst", 0, 20, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 0, 21, "", 0, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "", 0, 1, 20); test("abcdefghijklmnopqrst", 0, 21, "", 1, 0, 0); test("abcdefghijklmnopqrst", 0, 21, "abcde", 0, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcde", 0, 1, 19); test("abcdefghijklmnopqrst", 0, 21, "abcde", 0, 2, 18); test("abcdefghijklmnopqrst", 0, 21, "abcde", 0, 4, 16); test("abcdefghijklmnopqrst", 0, 21, "abcde", 0, 5, 15); test("abcdefghijklmnopqrst", 0, 21, "abcde", 0, 6, 15); test("abcdefghijklmnopqrst", 0, 21, "abcde", 1, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcde", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 21, "abcde", 1, 2, -1); test("abcdefghijklmnopqrst", 0, 21, "abcde", 1, 3, -1); test("abcdefghijklmnopqrst", 0, 21, "abcde", 1, 4, -1); test("abcdefghijklmnopqrst", 0, 21, "abcde", 1, 5, -1); test("abcdefghijklmnopqrst", 0, 21, "abcde", 2, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcde", 2, 1, -2); test("abcdefghijklmnopqrst", 0, 21, "abcde", 2, 2, -2); test("abcdefghijklmnopqrst", 0, 21, "abcde", 2, 3, -2); test("abcdefghijklmnopqrst", 0, 21, "abcde", 2, 4, -2); test("abcdefghijklmnopqrst", 0, 21, "abcde", 4, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcde", 4, 1, -4); test("abcdefghijklmnopqrst", 0, 21, "abcde", 4, 2, -4); test("abcdefghijklmnopqrst", 0, 21, "abcde", 5, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcde", 5, 1, 20); test("abcdefghijklmnopqrst", 0, 21, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 0, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 0, 1, 19); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 0, 5, 15); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 0, 9, 11); } void test41() { test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 0, 10, 10); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 0, 11, 10); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 1, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 1, 4, -1); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 1, 8, -1); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 1, 9, -1); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 1, 10, -1); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 5, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 5, 1, -5); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 5, 2, -5); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 5, 4, -5); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 5, 5, -5); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 5, 6, -5); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 9, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 9, 1, -9); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 9, 2, -9); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 10, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 10, 1, 20); test("abcdefghijklmnopqrst", 0, 21, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 0, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 0, 1, 19); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 0, 10, 10); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 0, 19, 1); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 0, 20, 0); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 0, 21, 0); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 1, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 1, 9, -1); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 1, 18, -1); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 1, 19, -1); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 1, 20, -1); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 10, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 10, 1, -10); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 10, 5, -10); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 10, 9, -10); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 19, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 19, 1, -19); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 19, 2, -19); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 20, 0, 20); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 20, 1, 20); test("abcdefghijklmnopqrst", 0, 21, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "", 0, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "", 0, 1, 0); test("abcdefghijklmnopqrst", 1, 0, "", 1, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcde", 0, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcde", 0, 1, -1); test("abcdefghijklmnopqrst", 1, 0, "abcde", 0, 2, -2); test("abcdefghijklmnopqrst", 1, 0, "abcde", 0, 4, -4); test("abcdefghijklmnopqrst", 1, 0, "abcde", 0, 5, -5); test("abcdefghijklmnopqrst", 1, 0, "abcde", 0, 6, -5); test("abcdefghijklmnopqrst", 1, 0, "abcde", 1, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcde", 1, 1, -1); test("abcdefghijklmnopqrst", 1, 0, "abcde", 1, 2, -2); test("abcdefghijklmnopqrst", 1, 0, "abcde", 1, 3, -3); test("abcdefghijklmnopqrst", 1, 0, "abcde", 1, 4, -4); test("abcdefghijklmnopqrst", 1, 0, "abcde", 1, 5, -4); test("abcdefghijklmnopqrst", 1, 0, "abcde", 2, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcde", 2, 1, -1); test("abcdefghijklmnopqrst", 1, 0, "abcde", 2, 2, -2); test("abcdefghijklmnopqrst", 1, 0, "abcde", 2, 3, -3); test("abcdefghijklmnopqrst", 1, 0, "abcde", 2, 4, -3); test("abcdefghijklmnopqrst", 1, 0, "abcde", 4, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcde", 4, 1, -1); test("abcdefghijklmnopqrst", 1, 0, "abcde", 4, 2, -1); test("abcdefghijklmnopqrst", 1, 0, "abcde", 5, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcde", 5, 1, 0); test("abcdefghijklmnopqrst", 1, 0, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 0, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 0, 1, -1); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 0, 5, -5); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 0, 9, -9); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 0, 10, -10); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 0, 11, -10); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 1, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 1, 1, -1); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 1, 4, -4); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 1, 8, -8); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 1, 9, -9); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 1, 10, -9); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 5, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 5, 1, -1); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 5, 2, -2); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 5, 4, -4); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 5, 5, -5); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 5, 6, -5); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 9, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 9, 1, -1); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 9, 2, -1); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 10, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 10, 1, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 0, 21, -20); } void test42() { test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghijklmnopqrst", 1, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 1, 1, "", 0, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 1, "", 1, 0, 0); test("abcdefghijklmnopqrst", 1, 1, "abcde", 0, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 0, 2, 1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 0, 4, 1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 0, 5, 1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 0, 6, 1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 1, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 1, 1, 0); test("abcdefghijklmnopqrst", 1, 1, "abcde", 1, 2, -1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 1, 3, -2); test("abcdefghijklmnopqrst", 1, 1, "abcde", 1, 4, -3); test("abcdefghijklmnopqrst", 1, 1, "abcde", 1, 5, -3); test("abcdefghijklmnopqrst", 1, 1, "abcde", 2, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 2, 1, -1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 2, 2, -1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 2, 3, -1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 2, 4, -1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 4, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 4, 1, -3); test("abcdefghijklmnopqrst", 1, 1, "abcde", 4, 2, -3); test("abcdefghijklmnopqrst", 1, 1, "abcde", 5, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 5, 1, 1); test("abcdefghijklmnopqrst", 1, 1, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 0, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 0, 5, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 0, 9, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 0, 10, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 0, 11, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 1, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 1, 1, 0); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 1, 4, -3); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 1, 8, -7); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 1, 9, -8); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 1, 10, -8); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 5, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 5, 1, -4); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 5, 2, -4); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 5, 4, -4); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 5, 5, -4); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 5, 6, -4); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 9, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 9, 1, -8); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 9, 2, -8); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 10, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 10, 1, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 0, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 0, 10, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 0, 19, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 0, 20, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 0, 21, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 1, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 1, 1, 0); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 1, 9, -8); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 1, 18, -17); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 1, 19, -18); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 1, 20, -18); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 10, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 10, 1, -9); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 10, 5, -9); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 10, 10, -9); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 10, 11, -9); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 19, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 19, 1, -18); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 19, 2, -18); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 20, 0, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 20, 1, 1); test("abcdefghijklmnopqrst", 1, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 1, 9, "", 0, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "", 0, 1, 9); test("abcdefghijklmnopqrst", 1, 9, "", 1, 0, 0); test("abcdefghijklmnopqrst", 1, 9, "abcde", 0, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcde", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 9, "abcde", 0, 2, 1); test("abcdefghijklmnopqrst", 1, 9, "abcde", 0, 4, 1); test("abcdefghijklmnopqrst", 1, 9, "abcde", 0, 5, 1); } void test43() { test("abcdefghijklmnopqrst", 1, 9, "abcde", 0, 6, 1); test("abcdefghijklmnopqrst", 1, 9, "abcde", 1, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcde", 1, 1, 8); test("abcdefghijklmnopqrst", 1, 9, "abcde", 1, 2, 7); test("abcdefghijklmnopqrst", 1, 9, "abcde", 1, 3, 6); test("abcdefghijklmnopqrst", 1, 9, "abcde", 1, 4, 5); test("abcdefghijklmnopqrst", 1, 9, "abcde", 1, 5, 5); test("abcdefghijklmnopqrst", 1, 9, "abcde", 2, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcde", 2, 1, -1); test("abcdefghijklmnopqrst", 1, 9, "abcde", 2, 2, -1); test("abcdefghijklmnopqrst", 1, 9, "abcde", 2, 3, -1); test("abcdefghijklmnopqrst", 1, 9, "abcde", 2, 4, -1); test("abcdefghijklmnopqrst", 1, 9, "abcde", 4, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcde", 4, 1, -3); test("abcdefghijklmnopqrst", 1, 9, "abcde", 4, 2, -3); test("abcdefghijklmnopqrst", 1, 9, "abcde", 5, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcde", 5, 1, 9); test("abcdefghijklmnopqrst", 1, 9, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 0, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 0, 5, 1); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 0, 9, 1); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 0, 10, 1); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 0, 11, 1); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 1, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 1, 1, 8); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 1, 4, 5); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 1, 8, 1); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 1, 9, 0); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 1, 10, 0); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 5, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 5, 1, -4); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 5, 2, -4); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 5, 4, -4); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 5, 5, -4); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 5, 6, -4); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 9, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 9, 1, -8); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 9, 2, -8); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 10, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 10, 1, 9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 0, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 0, 10, 1); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 0, 19, 1); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 0, 20, 1); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 0, 21, 1); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 1, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 1, 1, 8); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 1, 9, 0); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 1, 18, -9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 1, 19, -10); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 1, 20, -10); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 10, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 10, 1, -9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 10, 5, -9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 10, 10, -9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 10, 11, -9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 19, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 19, 1, -18); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 19, 2, -18); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 20, 0, 9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 20, 1, 9); test("abcdefghijklmnopqrst", 1, 9, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 1, 18, "", 0, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "", 0, 1, 18); test("abcdefghijklmnopqrst", 1, 18, "", 1, 0, 0); test("abcdefghijklmnopqrst", 1, 18, "abcde", 0, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcde", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 18, "abcde", 0, 2, 1); test("abcdefghijklmnopqrst", 1, 18, "abcde", 0, 4, 1); test("abcdefghijklmnopqrst", 1, 18, "abcde", 0, 5, 1); test("abcdefghijklmnopqrst", 1, 18, "abcde", 0, 6, 1); test("abcdefghijklmnopqrst", 1, 18, "abcde", 1, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcde", 1, 1, 17); test("abcdefghijklmnopqrst", 1, 18, "abcde", 1, 2, 16); test("abcdefghijklmnopqrst", 1, 18, "abcde", 1, 3, 15); test("abcdefghijklmnopqrst", 1, 18, "abcde", 1, 4, 14); test("abcdefghijklmnopqrst", 1, 18, "abcde", 1, 5, 14); test("abcdefghijklmnopqrst", 1, 18, "abcde", 2, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcde", 2, 1, -1); test("abcdefghijklmnopqrst", 1, 18, "abcde", 2, 2, -1); test("abcdefghijklmnopqrst", 1, 18, "abcde", 2, 3, -1); test("abcdefghijklmnopqrst", 1, 18, "abcde", 2, 4, -1); test("abcdefghijklmnopqrst", 1, 18, "abcde", 4, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcde", 4, 1, -3); test("abcdefghijklmnopqrst", 1, 18, "abcde", 4, 2, -3); test("abcdefghijklmnopqrst", 1, 18, "abcde", 5, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcde", 5, 1, 18); test("abcdefghijklmnopqrst", 1, 18, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 0, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 0, 5, 1); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 0, 9, 1); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 0, 10, 1); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 0, 11, 1); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 1, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 1, 1, 17); } void test44() { test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 1, 4, 14); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 1, 8, 10); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 1, 9, 9); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 1, 10, 9); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 5, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 5, 1, -4); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 5, 2, -4); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 5, 4, -4); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 5, 5, -4); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 5, 6, -4); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 9, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 9, 1, -8); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 9, 2, -8); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 10, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 10, 1, 18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 0, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 0, 10, 1); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 0, 19, 1); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 0, 20, 1); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 0, 21, 1); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 1, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 1, 1, 17); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 1, 9, 9); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 1, 18, 0); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 1, 19, -1); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 1, 20, -1); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 10, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 10, 1, -9); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 10, 5, -9); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 10, 10, -9); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 10, 11, -9); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 19, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 19, 1, -18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 19, 2, -18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 20, 0, 18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 20, 1, 18); test("abcdefghijklmnopqrst", 1, 18, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 1, 19, "", 0, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "", 0, 1, 19); test("abcdefghijklmnopqrst", 1, 19, "", 1, 0, 0); test("abcdefghijklmnopqrst", 1, 19, "abcde", 0, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcde", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 19, "abcde", 0, 2, 1); test("abcdefghijklmnopqrst", 1, 19, "abcde", 0, 4, 1); test("abcdefghijklmnopqrst", 1, 19, "abcde", 0, 5, 1); test("abcdefghijklmnopqrst", 1, 19, "abcde", 0, 6, 1); test("abcdefghijklmnopqrst", 1, 19, "abcde", 1, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcde", 1, 1, 18); test("abcdefghijklmnopqrst", 1, 19, "abcde", 1, 2, 17); test("abcdefghijklmnopqrst", 1, 19, "abcde", 1, 3, 16); test("abcdefghijklmnopqrst", 1, 19, "abcde", 1, 4, 15); test("abcdefghijklmnopqrst", 1, 19, "abcde", 1, 5, 15); test("abcdefghijklmnopqrst", 1, 19, "abcde", 2, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcde", 2, 1, -1); test("abcdefghijklmnopqrst", 1, 19, "abcde", 2, 2, -1); test("abcdefghijklmnopqrst", 1, 19, "abcde", 2, 3, -1); test("abcdefghijklmnopqrst", 1, 19, "abcde", 2, 4, -1); test("abcdefghijklmnopqrst", 1, 19, "abcde", 4, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcde", 4, 1, -3); test("abcdefghijklmnopqrst", 1, 19, "abcde", 4, 2, -3); test("abcdefghijklmnopqrst", 1, 19, "abcde", 5, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcde", 5, 1, 19); test("abcdefghijklmnopqrst", 1, 19, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 0, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 0, 5, 1); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 0, 9, 1); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 0, 10, 1); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 0, 11, 1); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 1, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 1, 1, 18); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 1, 4, 15); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 1, 8, 11); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 1, 9, 10); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 1, 10, 10); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 5, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 5, 1, -4); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 5, 2, -4); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 5, 4, -4); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 5, 5, -4); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 5, 6, -4); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 9, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 9, 1, -8); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 9, 2, -8); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 10, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 10, 1, 19); test("abcdefghijklmnopqrst", 1, 19, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 0, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 0, 10, 1); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 0, 19, 1); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 0, 20, 1); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 0, 21, 1); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 1, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 1, 1, 18); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 1, 9, 10); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 1, 18, 1); } void test45() { test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 1, 19, 0); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 1, 20, 0); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 10, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 10, 1, -9); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 10, 5, -9); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 10, 10, -9); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 10, 11, -9); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 19, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 19, 1, -18); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 19, 2, -18); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 20, 0, 19); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 20, 1, 19); test("abcdefghijklmnopqrst", 1, 19, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 1, 20, "", 0, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "", 0, 1, 19); test("abcdefghijklmnopqrst", 1, 20, "", 1, 0, 0); test("abcdefghijklmnopqrst", 1, 20, "abcde", 0, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcde", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 20, "abcde", 0, 2, 1); test("abcdefghijklmnopqrst", 1, 20, "abcde", 0, 4, 1); test("abcdefghijklmnopqrst", 1, 20, "abcde", 0, 5, 1); test("abcdefghijklmnopqrst", 1, 20, "abcde", 0, 6, 1); test("abcdefghijklmnopqrst", 1, 20, "abcde", 1, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcde", 1, 1, 18); test("abcdefghijklmnopqrst", 1, 20, "abcde", 1, 2, 17); test("abcdefghijklmnopqrst", 1, 20, "abcde", 1, 3, 16); test("abcdefghijklmnopqrst", 1, 20, "abcde", 1, 4, 15); test("abcdefghijklmnopqrst", 1, 20, "abcde", 1, 5, 15); test("abcdefghijklmnopqrst", 1, 20, "abcde", 2, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcde", 2, 1, -1); test("abcdefghijklmnopqrst", 1, 20, "abcde", 2, 2, -1); test("abcdefghijklmnopqrst", 1, 20, "abcde", 2, 3, -1); test("abcdefghijklmnopqrst", 1, 20, "abcde", 2, 4, -1); test("abcdefghijklmnopqrst", 1, 20, "abcde", 4, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcde", 4, 1, -3); test("abcdefghijklmnopqrst", 1, 20, "abcde", 4, 2, -3); test("abcdefghijklmnopqrst", 1, 20, "abcde", 5, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcde", 5, 1, 19); test("abcdefghijklmnopqrst", 1, 20, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 0, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 0, 5, 1); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 0, 9, 1); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 0, 10, 1); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 0, 11, 1); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 1, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 1, 1, 18); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 1, 4, 15); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 1, 8, 11); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 1, 9, 10); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 1, 10, 10); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 5, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 5, 1, -4); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 5, 2, -4); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 5, 4, -4); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 5, 5, -4); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 5, 6, -4); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 9, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 9, 1, -8); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 9, 2, -8); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 10, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 10, 1, 19); test("abcdefghijklmnopqrst", 1, 20, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 0, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 0, 1, 1); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 0, 10, 1); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 0, 19, 1); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 0, 20, 1); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 0, 21, 1); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 1, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 1, 1, 18); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 1, 9, 10); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 1, 18, 1); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 1, 19, 0); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 1, 20, 0); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 10, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 10, 1, -9); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 10, 5, -9); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 10, 10, -9); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 10, 11, -9); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 19, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 19, 1, -18); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 19, 2, -18); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 20, 0, 19); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 20, 1, 19); test("abcdefghijklmnopqrst", 1, 20, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "", 0, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "", 0, 1, 0); test("abcdefghijklmnopqrst", 10, 0, "", 1, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcde", 0, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcde", 0, 1, -1); test("abcdefghijklmnopqrst", 10, 0, "abcde", 0, 2, -2); test("abcdefghijklmnopqrst", 10, 0, "abcde", 0, 4, -4); test("abcdefghijklmnopqrst", 10, 0, "abcde", 0, 5, -5); test("abcdefghijklmnopqrst", 10, 0, "abcde", 0, 6, -5); test("abcdefghijklmnopqrst", 10, 0, "abcde", 1, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcde", 1, 1, -1); test("abcdefghijklmnopqrst", 10, 0, "abcde", 1, 2, -2); } void test46() { test("abcdefghijklmnopqrst", 10, 0, "abcde", 1, 3, -3); test("abcdefghijklmnopqrst", 10, 0, "abcde", 1, 4, -4); test("abcdefghijklmnopqrst", 10, 0, "abcde", 1, 5, -4); test("abcdefghijklmnopqrst", 10, 0, "abcde", 2, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcde", 2, 1, -1); test("abcdefghijklmnopqrst", 10, 0, "abcde", 2, 2, -2); test("abcdefghijklmnopqrst", 10, 0, "abcde", 2, 3, -3); test("abcdefghijklmnopqrst", 10, 0, "abcde", 2, 4, -3); test("abcdefghijklmnopqrst", 10, 0, "abcde", 4, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcde", 4, 1, -1); test("abcdefghijklmnopqrst", 10, 0, "abcde", 4, 2, -1); test("abcdefghijklmnopqrst", 10, 0, "abcde", 5, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcde", 5, 1, 0); test("abcdefghijklmnopqrst", 10, 0, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 0, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 0, 1, -1); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 0, 5, -5); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 0, 9, -9); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 0, 10, -10); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 0, 11, -10); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 1, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 1, 1, -1); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 1, 4, -4); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 1, 8, -8); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 1, 9, -9); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 1, 10, -9); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 5, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 5, 1, -1); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 5, 2, -2); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 5, 4, -4); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 5, 5, -5); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 5, 6, -5); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 9, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 9, 1, -1); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 9, 2, -1); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 10, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 10, 1, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghijklmnopqrst", 10, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 10, 1, "", 0, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "", 0, 1, 1); test("abcdefghijklmnopqrst", 10, 1, "", 1, 0, 0); test("abcdefghijklmnopqrst", 10, 1, "abcde", 0, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcde", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 1, "abcde", 0, 2, 10); test("abcdefghijklmnopqrst", 10, 1, "abcde", 0, 4, 10); test("abcdefghijklmnopqrst", 10, 1, "abcde", 0, 5, 10); test("abcdefghijklmnopqrst", 10, 1, "abcde", 0, 6, 10); test("abcdefghijklmnopqrst", 10, 1, "abcde", 1, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcde", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 1, "abcde", 1, 2, 9); test("abcdefghijklmnopqrst", 10, 1, "abcde", 1, 3, 9); test("abcdefghijklmnopqrst", 10, 1, "abcde", 1, 4, 9); test("abcdefghijklmnopqrst", 10, 1, "abcde", 1, 5, 9); test("abcdefghijklmnopqrst", 10, 1, "abcde", 2, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcde", 2, 1, 8); test("abcdefghijklmnopqrst", 10, 1, "abcde", 2, 2, 8); test("abcdefghijklmnopqrst", 10, 1, "abcde", 2, 3, 8); test("abcdefghijklmnopqrst", 10, 1, "abcde", 2, 4, 8); test("abcdefghijklmnopqrst", 10, 1, "abcde", 4, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcde", 4, 1, 6); test("abcdefghijklmnopqrst", 10, 1, "abcde", 4, 2, 6); test("abcdefghijklmnopqrst", 10, 1, "abcde", 5, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcde", 5, 1, 1); test("abcdefghijklmnopqrst", 10, 1, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 0, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 0, 5, 10); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 0, 9, 10); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 0, 10, 10); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 0, 11, 10); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 1, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 1, 4, 9); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 1, 8, 9); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 1, 9, 9); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 1, 10, 9); } void test47() { test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 5, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 5, 1, 5); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 5, 2, 5); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 5, 4, 5); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 5, 5, 5); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 5, 6, 5); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 9, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 9, 1, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 9, 2, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 10, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 10, 1, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 0, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 0, 10, 10); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 0, 19, 10); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 0, 20, 10); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 0, 21, 10); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 1, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 1, 9, 9); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 1, 18, 9); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 1, 19, 9); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 1, 20, 9); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 10, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 10, 1, 0); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 10, 5, -4); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 10, 9, -8); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 10, 10, -9); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 10, 11, -9); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 19, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 19, 1, -9); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 19, 2, -9); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 20, 0, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 20, 1, 1); test("abcdefghijklmnopqrst", 10, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 10, 5, "", 0, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "", 0, 1, 5); test("abcdefghijklmnopqrst", 10, 5, "", 1, 0, 0); test("abcdefghijklmnopqrst", 10, 5, "abcde", 0, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcde", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 5, "abcde", 0, 2, 10); test("abcdefghijklmnopqrst", 10, 5, "abcde", 0, 4, 10); test("abcdefghijklmnopqrst", 10, 5, "abcde", 0, 5, 10); test("abcdefghijklmnopqrst", 10, 5, "abcde", 0, 6, 10); test("abcdefghijklmnopqrst", 10, 5, "abcde", 1, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcde", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 5, "abcde", 1, 2, 9); test("abcdefghijklmnopqrst", 10, 5, "abcde", 1, 3, 9); test("abcdefghijklmnopqrst", 10, 5, "abcde", 1, 4, 9); test("abcdefghijklmnopqrst", 10, 5, "abcde", 1, 5, 9); test("abcdefghijklmnopqrst", 10, 5, "abcde", 2, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcde", 2, 1, 8); test("abcdefghijklmnopqrst", 10, 5, "abcde", 2, 2, 8); test("abcdefghijklmnopqrst", 10, 5, "abcde", 2, 3, 8); test("abcdefghijklmnopqrst", 10, 5, "abcde", 2, 4, 8); test("abcdefghijklmnopqrst", 10, 5, "abcde", 4, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcde", 4, 1, 6); test("abcdefghijklmnopqrst", 10, 5, "abcde", 4, 2, 6); test("abcdefghijklmnopqrst", 10, 5, "abcde", 5, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcde", 5, 1, 5); test("abcdefghijklmnopqrst", 10, 5, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 0, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 0, 5, 10); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 0, 9, 10); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 0, 10, 10); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 0, 11, 10); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 1, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 1, 4, 9); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 1, 8, 9); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 1, 9, 9); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 1, 10, 9); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 5, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 5, 1, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 5, 2, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 5, 4, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 5, 5, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 5, 6, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 9, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 9, 1, 1); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 9, 2, 1); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 10, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 10, 1, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 0, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 0, 10, 10); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 0, 19, 10); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 0, 20, 10); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 0, 21, 10); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 1, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 1, 9, 9); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 1, 18, 9); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 1, 19, 9); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 1, 20, 9); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 10, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 10, 1, 4); } void test48() { test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 10, 5, 0); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 10, 9, -4); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 10, 10, -5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 10, 11, -5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 19, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 19, 1, -9); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 19, 2, -9); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 20, 0, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 20, 1, 5); test("abcdefghijklmnopqrst", 10, 5, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 10, 9, "", 0, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "", 0, 1, 9); test("abcdefghijklmnopqrst", 10, 9, "", 1, 0, 0); test("abcdefghijklmnopqrst", 10, 9, "abcde", 0, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcde", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 9, "abcde", 0, 2, 10); test("abcdefghijklmnopqrst", 10, 9, "abcde", 0, 4, 10); test("abcdefghijklmnopqrst", 10, 9, "abcde", 0, 5, 10); test("abcdefghijklmnopqrst", 10, 9, "abcde", 0, 6, 10); test("abcdefghijklmnopqrst", 10, 9, "abcde", 1, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcde", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 9, "abcde", 1, 2, 9); test("abcdefghijklmnopqrst", 10, 9, "abcde", 1, 3, 9); test("abcdefghijklmnopqrst", 10, 9, "abcde", 1, 4, 9); test("abcdefghijklmnopqrst", 10, 9, "abcde", 1, 5, 9); test("abcdefghijklmnopqrst", 10, 9, "abcde", 2, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcde", 2, 1, 8); test("abcdefghijklmnopqrst", 10, 9, "abcde", 2, 2, 8); test("abcdefghijklmnopqrst", 10, 9, "abcde", 2, 3, 8); test("abcdefghijklmnopqrst", 10, 9, "abcde", 2, 4, 8); test("abcdefghijklmnopqrst", 10, 9, "abcde", 4, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcde", 4, 1, 6); test("abcdefghijklmnopqrst", 10, 9, "abcde", 4, 2, 6); test("abcdefghijklmnopqrst", 10, 9, "abcde", 5, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcde", 5, 1, 9); test("abcdefghijklmnopqrst", 10, 9, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 0, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 0, 5, 10); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 0, 9, 10); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 0, 10, 10); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 0, 11, 10); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 1, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 1, 4, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 1, 8, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 1, 9, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 1, 10, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 5, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 5, 1, 5); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 5, 2, 5); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 5, 4, 5); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 5, 5, 5); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 5, 6, 5); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 9, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 9, 1, 1); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 9, 2, 1); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 10, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 10, 1, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 0, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 0, 10, 10); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 0, 19, 10); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 0, 20, 10); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 0, 21, 10); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 1, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 1, 9, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 1, 18, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 1, 19, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 1, 20, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 10, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 10, 1, 8); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 10, 5, 4); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 10, 9, 0); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 10, 10, -1); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 10, 11, -1); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 19, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 19, 1, -9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 19, 2, -9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 20, 0, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 20, 1, 9); test("abcdefghijklmnopqrst", 10, 9, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 10, 10, "", 0, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 10, "", 1, 0, 0); test("abcdefghijklmnopqrst", 10, 10, "abcde", 0, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcde", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 10, "abcde", 0, 2, 10); test("abcdefghijklmnopqrst", 10, 10, "abcde", 0, 4, 10); test("abcdefghijklmnopqrst", 10, 10, "abcde", 0, 5, 10); test("abcdefghijklmnopqrst", 10, 10, "abcde", 0, 6, 10); test("abcdefghijklmnopqrst", 10, 10, "abcde", 1, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcde", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 10, "abcde", 1, 2, 9); test("abcdefghijklmnopqrst", 10, 10, "abcde", 1, 3, 9); test("abcdefghijklmnopqrst", 10, 10, "abcde", 1, 4, 9); test("abcdefghijklmnopqrst", 10, 10, "abcde", 1, 5, 9); test("abcdefghijklmnopqrst", 10, 10, "abcde", 2, 0, 10); } void test49() { test("abcdefghijklmnopqrst", 10, 10, "abcde", 2, 1, 8); test("abcdefghijklmnopqrst", 10, 10, "abcde", 2, 2, 8); test("abcdefghijklmnopqrst", 10, 10, "abcde", 2, 3, 8); test("abcdefghijklmnopqrst", 10, 10, "abcde", 2, 4, 8); test("abcdefghijklmnopqrst", 10, 10, "abcde", 4, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcde", 4, 1, 6); test("abcdefghijklmnopqrst", 10, 10, "abcde", 4, 2, 6); test("abcdefghijklmnopqrst", 10, 10, "abcde", 5, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcde", 5, 1, 10); test("abcdefghijklmnopqrst", 10, 10, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 0, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 0, 5, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 0, 9, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 0, 10, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 0, 11, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 1, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 1, 4, 9); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 1, 8, 9); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 1, 9, 9); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 1, 10, 9); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 5, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 5, 1, 5); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 5, 2, 5); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 5, 4, 5); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 5, 5, 5); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 5, 6, 5); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 9, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 9, 1, 1); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 9, 2, 1); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 10, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 10, 1, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 0, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 0, 10, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 0, 19, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 0, 20, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 0, 21, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 1, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 1, 9, 9); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 1, 18, 9); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 1, 19, 9); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 1, 20, 9); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 10, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 10, 1, 9); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 10, 5, 5); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 10, 9, 1); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 10, 10, 0); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 10, 11, 0); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 19, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 19, 1, -9); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 19, 2, -9); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 20, 0, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 20, 1, 10); test("abcdefghijklmnopqrst", 10, 10, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 10, 11, "", 0, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 11, "", 1, 0, 0); test("abcdefghijklmnopqrst", 10, 11, "abcde", 0, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcde", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 11, "abcde", 0, 2, 10); test("abcdefghijklmnopqrst", 10, 11, "abcde", 0, 4, 10); test("abcdefghijklmnopqrst", 10, 11, "abcde", 0, 5, 10); test("abcdefghijklmnopqrst", 10, 11, "abcde", 0, 6, 10); test("abcdefghijklmnopqrst", 10, 11, "abcde", 1, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcde", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 11, "abcde", 1, 2, 9); test("abcdefghijklmnopqrst", 10, 11, "abcde", 1, 3, 9); test("abcdefghijklmnopqrst", 10, 11, "abcde", 1, 4, 9); test("abcdefghijklmnopqrst", 10, 11, "abcde", 1, 5, 9); test("abcdefghijklmnopqrst", 10, 11, "abcde", 2, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcde", 2, 1, 8); test("abcdefghijklmnopqrst", 10, 11, "abcde", 2, 2, 8); test("abcdefghijklmnopqrst", 10, 11, "abcde", 2, 3, 8); test("abcdefghijklmnopqrst", 10, 11, "abcde", 2, 4, 8); test("abcdefghijklmnopqrst", 10, 11, "abcde", 4, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcde", 4, 1, 6); test("abcdefghijklmnopqrst", 10, 11, "abcde", 4, 2, 6); test("abcdefghijklmnopqrst", 10, 11, "abcde", 5, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcde", 5, 1, 10); test("abcdefghijklmnopqrst", 10, 11, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 0, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 0, 5, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 0, 9, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 0, 10, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 0, 11, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 1, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 1, 4, 9); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 1, 8, 9); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 1, 9, 9); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 1, 10, 9); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 5, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 5, 1, 5); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 5, 2, 5); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 5, 4, 5); } void test50() { test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 5, 5, 5); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 5, 6, 5); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 9, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 9, 1, 1); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 9, 2, 1); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 10, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 10, 1, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 0, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 0, 1, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 0, 10, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 0, 19, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 0, 20, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 0, 21, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 1, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 1, 1, 9); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 1, 9, 9); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 1, 18, 9); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 1, 19, 9); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 1, 20, 9); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 10, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 10, 1, 9); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 10, 5, 5); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 10, 9, 1); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 10, 10, 0); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 10, 11, 0); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 19, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 19, 1, -9); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 19, 2, -9); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 20, 0, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 20, 1, 10); test("abcdefghijklmnopqrst", 10, 11, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "", 0, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "", 0, 1, 0); test("abcdefghijklmnopqrst", 19, 0, "", 1, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcde", 0, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcde", 0, 1, -1); test("abcdefghijklmnopqrst", 19, 0, "abcde", 0, 2, -2); test("abcdefghijklmnopqrst", 19, 0, "abcde", 0, 4, -4); test("abcdefghijklmnopqrst", 19, 0, "abcde", 0, 5, -5); test("abcdefghijklmnopqrst", 19, 0, "abcde", 0, 6, -5); test("abcdefghijklmnopqrst", 19, 0, "abcde", 1, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcde", 1, 1, -1); test("abcdefghijklmnopqrst", 19, 0, "abcde", 1, 2, -2); test("abcdefghijklmnopqrst", 19, 0, "abcde", 1, 3, -3); test("abcdefghijklmnopqrst", 19, 0, "abcde", 1, 4, -4); test("abcdefghijklmnopqrst", 19, 0, "abcde", 1, 5, -4); test("abcdefghijklmnopqrst", 19, 0, "abcde", 2, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcde", 2, 1, -1); test("abcdefghijklmnopqrst", 19, 0, "abcde", 2, 2, -2); test("abcdefghijklmnopqrst", 19, 0, "abcde", 2, 3, -3); test("abcdefghijklmnopqrst", 19, 0, "abcde", 2, 4, -3); test("abcdefghijklmnopqrst", 19, 0, "abcde", 4, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcde", 4, 1, -1); test("abcdefghijklmnopqrst", 19, 0, "abcde", 4, 2, -1); test("abcdefghijklmnopqrst", 19, 0, "abcde", 5, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcde", 5, 1, 0); test("abcdefghijklmnopqrst", 19, 0, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 0, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 0, 1, -1); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 0, 5, -5); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 0, 9, -9); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 0, 10, -10); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 0, 11, -10); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 1, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 1, 1, -1); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 1, 4, -4); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 1, 8, -8); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 1, 9, -9); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 1, 10, -9); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 5, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 5, 1, -1); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 5, 2, -2); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 5, 4, -4); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 5, 5, -5); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 5, 6, -5); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 9, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 9, 1, -1); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 9, 2, -1); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 10, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 10, 1, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 10, 11, -10); } void test51() { test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghijklmnopqrst", 19, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 19, 1, "", 0, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "", 0, 1, 1); test("abcdefghijklmnopqrst", 19, 1, "", 1, 0, 0); test("abcdefghijklmnopqrst", 19, 1, "abcde", 0, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcde", 0, 1, 19); test("abcdefghijklmnopqrst", 19, 1, "abcde", 0, 2, 19); test("abcdefghijklmnopqrst", 19, 1, "abcde", 0, 4, 19); test("abcdefghijklmnopqrst", 19, 1, "abcde", 0, 5, 19); test("abcdefghijklmnopqrst", 19, 1, "abcde", 0, 6, 19); test("abcdefghijklmnopqrst", 19, 1, "abcde", 1, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcde", 1, 1, 18); test("abcdefghijklmnopqrst", 19, 1, "abcde", 1, 2, 18); test("abcdefghijklmnopqrst", 19, 1, "abcde", 1, 3, 18); test("abcdefghijklmnopqrst", 19, 1, "abcde", 1, 4, 18); test("abcdefghijklmnopqrst", 19, 1, "abcde", 1, 5, 18); test("abcdefghijklmnopqrst", 19, 1, "abcde", 2, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcde", 2, 1, 17); test("abcdefghijklmnopqrst", 19, 1, "abcde", 2, 2, 17); test("abcdefghijklmnopqrst", 19, 1, "abcde", 2, 3, 17); test("abcdefghijklmnopqrst", 19, 1, "abcde", 2, 4, 17); test("abcdefghijklmnopqrst", 19, 1, "abcde", 4, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcde", 4, 1, 15); test("abcdefghijklmnopqrst", 19, 1, "abcde", 4, 2, 15); test("abcdefghijklmnopqrst", 19, 1, "abcde", 5, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcde", 5, 1, 1); test("abcdefghijklmnopqrst", 19, 1, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 0, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 0, 1, 19); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 0, 5, 19); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 0, 9, 19); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 0, 10, 19); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 0, 11, 19); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 1, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 1, 1, 18); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 1, 4, 18); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 1, 8, 18); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 1, 9, 18); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 1, 10, 18); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 5, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 5, 1, 14); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 5, 2, 14); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 5, 4, 14); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 5, 5, 14); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 5, 6, 14); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 9, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 9, 1, 10); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 9, 2, 10); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 10, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 10, 1, 1); test("abcdefghijklmnopqrst", 19, 1, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 0, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 0, 1, 19); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 0, 10, 19); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 0, 19, 19); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 0, 20, 19); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 0, 21, 19); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 1, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 1, 1, 18); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 1, 9, 18); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 1, 18, 18); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 1, 19, 18); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 1, 20, 18); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 10, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 10, 1, 9); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 10, 5, 9); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 10, 9, 9); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 10, 10, 9); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 10, 11, 9); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 19, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 19, 1, 0); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 19, 2, 0); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 20, 0, 1); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 20, 1, 1); test("abcdefghijklmnopqrst", 19, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 19, 2, "", 0, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "", 0, 1, 1); test("abcdefghijklmnopqrst", 19, 2, "", 1, 0, 0); test("abcdefghijklmnopqrst", 19, 2, "abcde", 0, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcde", 0, 1, 19); test("abcdefghijklmnopqrst", 19, 2, "abcde", 0, 2, 19); test("abcdefghijklmnopqrst", 19, 2, "abcde", 0, 4, 19); test("abcdefghijklmnopqrst", 19, 2, "abcde", 0, 5, 19); test("abcdefghijklmnopqrst", 19, 2, "abcde", 0, 6, 19); test("abcdefghijklmnopqrst", 19, 2, "abcde", 1, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcde", 1, 1, 18); test("abcdefghijklmnopqrst", 19, 2, "abcde", 1, 2, 18); test("abcdefghijklmnopqrst", 19, 2, "abcde", 1, 3, 18); test("abcdefghijklmnopqrst", 19, 2, "abcde", 1, 4, 18); test("abcdefghijklmnopqrst", 19, 2, "abcde", 1, 5, 18); test("abcdefghijklmnopqrst", 19, 2, "abcde", 2, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcde", 2, 1, 17); test("abcdefghijklmnopqrst", 19, 2, "abcde", 2, 2, 17); test("abcdefghijklmnopqrst", 19, 2, "abcde", 2, 3, 17); test("abcdefghijklmnopqrst", 19, 2, "abcde", 2, 4, 17); } void test52() { test("abcdefghijklmnopqrst", 19, 2, "abcde", 4, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcde", 4, 1, 15); test("abcdefghijklmnopqrst", 19, 2, "abcde", 4, 2, 15); test("abcdefghijklmnopqrst", 19, 2, "abcde", 5, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcde", 5, 1, 1); test("abcdefghijklmnopqrst", 19, 2, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 0, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 0, 1, 19); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 0, 5, 19); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 0, 9, 19); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 0, 10, 19); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 0, 11, 19); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 1, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 1, 1, 18); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 1, 4, 18); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 1, 8, 18); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 1, 9, 18); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 1, 10, 18); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 5, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 5, 1, 14); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 5, 2, 14); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 5, 4, 14); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 5, 5, 14); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 5, 6, 14); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 9, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 9, 1, 10); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 9, 2, 10); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 10, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 10, 1, 1); test("abcdefghijklmnopqrst", 19, 2, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 0, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 0, 1, 19); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 0, 10, 19); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 0, 19, 19); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 0, 20, 19); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 0, 21, 19); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 1, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 1, 1, 18); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 1, 9, 18); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 1, 18, 18); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 1, 19, 18); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 1, 20, 18); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 10, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 10, 1, 9); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 10, 5, 9); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 10, 9, 9); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 10, 10, 9); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 10, 11, 9); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 19, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 19, 1, 0); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 19, 2, 0); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 20, 0, 1); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 20, 1, 1); test("abcdefghijklmnopqrst", 19, 2, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "", 0, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "", 0, 1, 0); test("abcdefghijklmnopqrst", 20, 0, "", 1, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcde", 0, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcde", 0, 1, -1); test("abcdefghijklmnopqrst", 20, 0, "abcde", 0, 2, -2); test("abcdefghijklmnopqrst", 20, 0, "abcde", 0, 4, -4); test("abcdefghijklmnopqrst", 20, 0, "abcde", 0, 5, -5); test("abcdefghijklmnopqrst", 20, 0, "abcde", 0, 6, -5); test("abcdefghijklmnopqrst", 20, 0, "abcde", 1, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcde", 1, 1, -1); test("abcdefghijklmnopqrst", 20, 0, "abcde", 1, 2, -2); test("abcdefghijklmnopqrst", 20, 0, "abcde", 1, 3, -3); test("abcdefghijklmnopqrst", 20, 0, "abcde", 1, 4, -4); test("abcdefghijklmnopqrst", 20, 0, "abcde", 1, 5, -4); test("abcdefghijklmnopqrst", 20, 0, "abcde", 2, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcde", 2, 1, -1); test("abcdefghijklmnopqrst", 20, 0, "abcde", 2, 2, -2); test("abcdefghijklmnopqrst", 20, 0, "abcde", 2, 3, -3); test("abcdefghijklmnopqrst", 20, 0, "abcde", 2, 4, -3); test("abcdefghijklmnopqrst", 20, 0, "abcde", 4, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcde", 4, 1, -1); test("abcdefghijklmnopqrst", 20, 0, "abcde", 4, 2, -1); test("abcdefghijklmnopqrst", 20, 0, "abcde", 5, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcde", 5, 1, 0); test("abcdefghijklmnopqrst", 20, 0, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 0, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 0, 1, -1); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 0, 5, -5); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 0, 9, -9); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 0, 10, -10); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 0, 11, -10); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 1, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 1, 1, -1); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 1, 4, -4); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 1, 8, -8); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 1, 9, -9); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 1, 10, -9); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 5, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 5, 1, -1); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 5, 2, -2); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 5, 4, -4); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 5, 5, -5); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 5, 6, -5); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 9, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 9, 1, -1); } void test53() { test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 9, 2, -1); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 10, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 10, 1, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 0, 1, -1); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 0, 10, -10); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 0, 19, -19); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 0, 20, -20); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 0, 21, -20); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 1, 9, -9); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 1, 18, -18); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 1, 19, -19); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 1, 20, -19); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 19, 1, -1); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 19, 2, -1); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghijklmnopqrst", 20, 0, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "", 0, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "", 0, 1, 0); test("abcdefghijklmnopqrst", 20, 1, "", 1, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcde", 0, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcde", 0, 1, -1); test("abcdefghijklmnopqrst", 20, 1, "abcde", 0, 2, -2); test("abcdefghijklmnopqrst", 20, 1, "abcde", 0, 4, -4); test("abcdefghijklmnopqrst", 20, 1, "abcde", 0, 5, -5); test("abcdefghijklmnopqrst", 20, 1, "abcde", 0, 6, -5); test("abcdefghijklmnopqrst", 20, 1, "abcde", 1, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcde", 1, 1, -1); test("abcdefghijklmnopqrst", 20, 1, "abcde", 1, 2, -2); test("abcdefghijklmnopqrst", 20, 1, "abcde", 1, 3, -3); test("abcdefghijklmnopqrst", 20, 1, "abcde", 1, 4, -4); test("abcdefghijklmnopqrst", 20, 1, "abcde", 1, 5, -4); test("abcdefghijklmnopqrst", 20, 1, "abcde", 2, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcde", 2, 1, -1); test("abcdefghijklmnopqrst", 20, 1, "abcde", 2, 2, -2); test("abcdefghijklmnopqrst", 20, 1, "abcde", 2, 3, -3); test("abcdefghijklmnopqrst", 20, 1, "abcde", 2, 4, -3); test("abcdefghijklmnopqrst", 20, 1, "abcde", 4, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcde", 4, 1, -1); test("abcdefghijklmnopqrst", 20, 1, "abcde", 4, 2, -1); test("abcdefghijklmnopqrst", 20, 1, "abcde", 5, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcde", 5, 1, 0); test("abcdefghijklmnopqrst", 20, 1, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 0, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 0, 1, -1); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 0, 5, -5); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 0, 9, -9); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 0, 10, -10); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 0, 11, -10); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 1, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 1, 1, -1); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 1, 4, -4); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 1, 8, -8); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 1, 9, -9); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 1, 10, -9); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 5, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 5, 1, -1); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 5, 2, -2); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 5, 4, -4); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 5, 5, -5); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 5, 6, -5); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 9, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 9, 1, -1); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 9, 2, -1); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 10, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 10, 1, 0); test("abcdefghijklmnopqrst", 20, 1, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 0, 1, -1); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 0, 10, -10); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 0, 19, -19); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 0, 20, -20); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 0, 21, -20); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 1, 1, -1); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 1, 9, -9); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 1, 18, -18); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 1, 19, -19); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 1, 20, -19); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 10, 1, -1); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 10, 5, -5); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 10, 9, -9); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 10, 10, -10); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 10, 11, -10); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 19, 1, -1); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 19, 2, -1); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 20, 0, 0); } void test54() { test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghijklmnopqrst", 20, 1, "abcdefghijklmnopqrst", 21, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "", 0, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "", 0, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "", 1, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 0, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 0, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 0, 2, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 0, 4, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 0, 5, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 0, 6, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 1, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 1, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 1, 2, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 1, 3, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 1, 4, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 1, 5, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 2, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 2, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 2, 2, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 2, 3, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 2, 4, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 4, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 4, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 4, 2, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 5, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 5, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcde", 6, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 0, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 0, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 0, 5, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 0, 9, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 0, 10, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 0, 11, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 1, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 1, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 1, 4, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 1, 8, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 1, 9, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 1, 10, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 5, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 5, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 5, 2, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 5, 4, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 5, 5, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 5, 6, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 9, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 9, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 9, 2, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 10, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 10, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghij", 11, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 0, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 0, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 0, 10, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 0, 19, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 0, 20, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 0, 21, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 1, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 1, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 1, 9, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 1, 18, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 1, 19, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 1, 20, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 10, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 10, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 10, 5, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 10, 9, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 10, 10, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 10, 11, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 19, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 19, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 19, 2, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 20, 0, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 20, 1, 0); test("abcdefghijklmnopqrst", 21, 0, "abcdefghijklmnopqrst", 21, 0, 0); } int main () { test0(); test1(); test2(); test3(); test4(); test5(); test6(); test7(); test8(); test9(); test10(); test11(); test12(); test13(); test14(); test15(); test16(); test17(); test18(); test19(); test20(); test21(); test22(); test23(); test24(); test25(); test26(); test27(); test28(); test29(); test30(); test31(); test32(); test33(); test34(); test35(); test36(); test37(); test38(); test39(); test40(); test41(); test42(); test43(); test44(); test45(); test46(); test47(); test48(); test49(); test50(); test51(); test52(); test53(); test54(); { test("abcde", 5, 1, "", 0, 0, 0); test("abcde", 2, 4, "", 0, 0, 3); test("abcde", 2, 4, "abcde", 3, 4, -2); test("ABCde", 2, 4, "abcde", 2, 4, -1); } { test(L"abcde", 5, 1, L"", 0, 0, 0); test(L"abcde", 2, 4, L"", 0, 0, 3); test(L"abcde", 2, 4, L"abcde", 3, 4, -2); test(L"ABCde", 2, 4, L"abcde", 2, 4, -1); } #if __cplusplus >= 201103L { test(u"abcde", 5, 1, u"", 0, 0, 0); test(u"abcde", 2, 4, u"", 0, 0, 3); test(u"abcde", 2, 4, u"abcde", 3, 4, -2); test(u"ABCde", 2, 4, u"abcde", 2, 4, -1); } { test(U"abcde", 5, 1, U"", 0, 0, 0); test(U"abcde", 2, 4, U"", 0, 0, 3); test(U"abcde", 2, 4, U"abcde", 3, 4, -2); test(U"ABCde", 2, 4, U"abcde", 2, 4, -1); } #endif #if _LIBCPP_STD_VER > 11 { typedef std::experimental::basic_string_view<char, constexpr_char_traits<char>> SV; constexpr SV sv1 { "abcde", 5 }; static_assert ( sv1.compare(5, 1, "", 0, 0) == 0, "" ); static_assert ( sv1.compare(2, 4, "", 0, 0) == 1, "" ); static_assert ( sv1.compare(2, 4, "abcde", 3, 4) == -1, "" ); } #endif }
54.04295
88
0.569888
georgix
3340a84f5d1d80057b6bed08cf898648910a7d4e
1,415
cpp
C++
src/game/shared/tf2/tf_gamemovement_pyro.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/shared/tf2/tf_gamemovement_pyro.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/shared/tf2/tf_gamemovement_pyro.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Auto Repair // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "tf_gamemovement_pyro.h" #include "tf_movedata.h" CTFGameMovementPyro::CTFGameMovementPyro() { m_pPyroData = NULL; m_vStandMins = PYROCLASS_HULL_STAND_MIN; m_vStandMaxs = PYROCLASS_HULL_STAND_MAX; m_vStandViewOffset = PYROCLASS_VIEWOFFSET_STAND; m_vDuckMins = PYROCLASS_HULL_DUCK_MIN; m_vDuckMaxs = PYROCLASS_HULL_DUCK_MAX; m_vDuckViewOffset = PYROCLASS_VIEWOFFSET_DUCK; } void CTFGameMovementPyro::ProcessClassMovement( CBaseTFPlayer *pPlayer, CTFMoveData *pTFMoveData ) { // Get the class specific data from the TFMoveData structure Assert( PlayerClassPyroData_t::PLAYERCLASS_ID == pTFMoveData->m_nClassID ); m_pPyroData = &pTFMoveData->PyroData(); // to test pass it through!! BaseClass::ProcessMovement( (CBasePlayer *)pPlayer, static_cast<CMoveData*>( pTFMoveData ) ); } const Vector &CTFGameMovementPyro::GetPlayerMins( bool bDucked ) const { return bDucked ? m_vDuckMins : m_vStandMins; } const Vector &CTFGameMovementPyro::GetPlayerMaxs( bool bDucked ) const { return bDucked ? m_vDuckMaxs : m_vStandMaxs; } const Vector &CTFGameMovementPyro::GetPlayerViewOffset( bool bDucked ) const { return bDucked ? m_vDuckViewOffset : m_vStandViewOffset; }
28.877551
98
0.727208
cstom4994
3351218184d4e3d0f5a0b4c6048198aedf0c67bd
798
hpp
C++
src/duke/streams/SingleFileStream.hpp
hradec/duke
efacf7139cd1d7c2cd2f5127079721bd263dda50
[ "MIT" ]
51
2015-01-07T18:36:39.000Z
2021-11-30T15:24:44.000Z
src/duke/streams/SingleFileStream.hpp
virneo/duke
efacf7139cd1d7c2cd2f5127079721bd263dda50
[ "MIT" ]
1
2015-01-08T10:48:43.000Z
2015-02-11T19:32:14.000Z
src/duke/streams/SingleFileStream.hpp
virneo/duke
efacf7139cd1d7c2cd2f5127079721bd263dda50
[ "MIT" ]
18
2015-05-11T12:43:37.000Z
2019-11-29T11:15:41.000Z
#pragma once #include "IMediaStream.hpp" #include "duke/attributes/Attributes.hpp" #include "duke/io/IO.hpp" #include <mutex> namespace sequence { struct Item; } namespace duke { class SingleFileStream final : public duke::IMediaStream { public: SingleFileStream(const sequence::Item& item); ~SingleFileStream() override {} const ReadFrameResult& openContainer() const override; // This function can be called from different threads. ReadFrameResult process(const size_t frame) const override; // True if this stream is a movie bool isForwardOnly() const override; const attribute::Attributes& getState() const override { return m_State; } private: mutable std::mutex m_Mutex; ReadFrameResult m_OpenResult; attribute::Attributes m_State; }; } // namespace duke
21
76
0.749373
hradec
3352b3882b2ab38b5ac7ca00f367c4ecdbb57303
6,503
cpp
C++
legacy/project/src/common/GraphicsData.cpp
gunnbr/lime
87cd4b2dbb4b32d7cbe8a03895e0d2a35f8662cc
[ "MIT" ]
6
2015-03-21T10:20:55.000Z
2019-03-10T14:04:43.000Z
legacy/project/src/common/GraphicsData.cpp
gunnbr/lime
87cd4b2dbb4b32d7cbe8a03895e0d2a35f8662cc
[ "MIT" ]
1
2020-07-04T23:48:49.000Z
2020-07-04T23:48:49.000Z
legacy/project/src/common/GraphicsData.cpp
gunnbr/lime
87cd4b2dbb4b32d7cbe8a03895e0d2a35f8662cc
[ "MIT" ]
2
2016-01-24T20:01:59.000Z
2019-10-26T22:52:43.000Z
#include <Graphics.h> namespace nme { // --- GraphicsPath ------------------------------------------ void GraphicsPath::initPosition(const UserPoint &inPoint) { commands.push_back(pcBeginAt); data.push_back(inPoint.x); data.push_back(inPoint.y); } void GraphicsPath::clear() { commands.resize(0); data.resize(0); } void GraphicsPath::curveTo(float controlX, float controlY, float anchorX, float anchorY) { commands.push_back(pcCurveTo); data.push_back(controlX); data.push_back(controlY); data.push_back(anchorX); data.push_back(anchorY); } void GraphicsPath::arcTo(float controlX, float controlY, float anchorX, float anchorY) { commands.push_back(pcArcTo); data.push_back(controlX); data.push_back(controlY); data.push_back(anchorX); data.push_back(anchorY); } void GraphicsPath::elementBlendMode(int inMode) { switch(inMode) { case bmAdd: commands.push_back(pcBlendModeAdd); break; case bmMultiply: commands.push_back(pcBlendModeMultiply); break; case bmScreen: commands.push_back(pcBlendModeScreen); break; } } void GraphicsPath::lineTo(float x, float y) { commands.push_back(pcLineTo); data.push_back(x); data.push_back(y); } void GraphicsPath::moveTo(float x, float y) { commands.push_back(pcMoveTo); data.push_back(x); data.push_back(y); } void GraphicsPath::wideLineTo(float x, float y) { commands.push_back(pcLineTo); data.push_back(x); data.push_back(y); } void GraphicsPath::wideMoveTo(float x, float y) { commands.push_back(pcMoveTo); data.push_back(x); data.push_back(y); } void GraphicsPath::tile(float x, float y, const Rect &inTileRect,float *inTrans,float *inRGBA) { data.push_back(x); data.push_back(y); data.push_back(inTileRect.x); data.push_back(inTileRect.y); data.push_back(inTileRect.w); data.push_back(inTileRect.h); int command = pcTile; if (inTrans) { command |= pcTile_Trans_Bit; data.push_back(inTrans[0]); data.push_back(inTrans[1]); data.push_back(inTrans[2]); data.push_back(inTrans[3]); } if (inRGBA) { command |= pcTile_Col_Bit; data.push_back(inRGBA[0]); data.push_back(inRGBA[1]); data.push_back(inRGBA[2]); data.push_back(inRGBA[3]); } commands.push_back((PathCommand)command); } void GraphicsPath::closeLine(int inCommand0, int inData0) { float *point = &data[inData0]; float *move = 0; for(int c=inCommand0; c<commands.size(); c++) { switch(commands[c]) { case pcWideMoveTo: point+=2; case pcBeginAt: case pcMoveTo: move = point; break; case pcWideLineTo: case pcCurveTo: point+=2; case pcLineTo: if (move && move[0]==point[0] && move[1]==point[1]) { // Closed loop detected - no need to close. move = 0; } break; } point+=2; } if (move) lineTo(move[0], move[1]); } void GraphicsPath::drawPoints(QuickVec<float> inXYs, QuickVec<int> inRGBAs) { int n = inXYs.size()/2; int d0 = data.size(); if (inRGBAs.size()==n) { commands.push_back(pcPointsXYRGBA); data.resize(d0 + n*3); memcpy(&data[d0], &inXYs[0], n*2*sizeof(float)); d0+=n*2; memcpy(&data[d0], &inRGBAs[0], n*sizeof(int)); } else { commands.push_back(pcPointsXY); data.resize(d0 + n*2); memcpy(&data[d0], &inXYs[0], n*sizeof(float)); } } // -- GraphicsTrianglePath --------------------------------------------------------- GraphicsTrianglePath::GraphicsTrianglePath( const QuickVec<float> &inXYs, const QuickVec<int> &inIndices, const QuickVec<float> &inUVT, int inCull, const QuickVec<int> &inColours, int inBlendMode) { UserPoint *v = (UserPoint *) &inXYs[0]; uint32 *c = (uint32 *) &inColours[0]; if(inColours.empty()) c=NULL; int v_count = inXYs.size()/2; int uv_parts = inUVT.size()==v_count*2 ? 2 : inUVT.size()==v_count*3 ? 3 : 0; const float *uvt = &inUVT[0]; mBlendMode = inBlendMode; if (inIndices.empty()) { int t_count = v_count/3; if (inCull==tcNone) { mVertices.resize(6*t_count); memcpy(&mVertices[0],v,3*sizeof(UserPoint)); if (uv_parts) { mUVT.resize(uv_parts*3*t_count); memcpy(&mUVT[0],&inUVT[0],uv_parts*sizeof(UserPoint)); } } else { for(int i=0;i<t_count;i++) { UserPoint p0 = *v++; UserPoint p1 = *v++; UserPoint p2 = *v++; if ( (p1-p0).Cross(p2-p0)*inCull > 0) { mTriangleCount++; mVertices.push_back(p0); mVertices.push_back(p1); mVertices.push_back(p2); for(int i=0;i<uv_parts*3;i++) mUVT.push_back( *uvt++ ); } else uvt += uv_parts; } } } else { const int *idx = &inIndices[0]; int t_count = inIndices.size()/3; for(int i=0;i<t_count;i++) { int i0 = *idx++; int i1 = *idx++; int i2 = *idx++; if (i0>=0 && i1>=0 && i2>=0 && i0<v_count && i1<v_count && i2<v_count) { UserPoint p0 = v[i0]; UserPoint p1 = v[i1]; UserPoint p2 = v[i2]; if ( (p1-p0).Cross(p2-p0)*inCull >= 0) { mVertices.push_back(p0); mVertices.push_back(p1); mVertices.push_back(p2); if(c) { uint32 co0 = c[i0]; uint32 co1 = c[i1]; uint32 co2 = c[i2]; co0 = ((co0 >> 24) & 0xFF) << 24 | (co0 & 0xFF) << 16 | ((co0 >> 8) & 0xFF) << 8 | ((co0 >> 16) & 0xFF); co1 = ((co1 >> 24) & 0xFF) << 24 | (co1 & 0xFF) << 16 | ((co1 >> 8) & 0xFF) << 8 | ((co1 >> 16) & 0xFF); co2 = ((co2 >> 24) & 0xFF) << 24 | (co2 & 0xFF) << 16 | ((co2 >> 8) & 0xFF) << 8 | ((co2 >> 16) & 0xFF); mColours.push_back(co0); mColours.push_back(co1); mColours.push_back(co2); } if (uv_parts) { const float *f = uvt + uv_parts*i0; for(int i=0;i<uv_parts;i++) mUVT.push_back( *f++ ); f = uvt + uv_parts*i1; for(int i=0;i<uv_parts;i++) mUVT.push_back( *f++ ); f = uvt + uv_parts*i2; for(int i=0;i<uv_parts;i++) mUVT.push_back( *f++ ); } } } } } mTriangleCount = mVertices.size()/3; mType = uv_parts==2 ? vtVertexUV : uv_parts==3? vtVertexUVT : vtVertex; } } // end namespace nme
23.733577
114
0.565893
gunnbr
3352ee924a53250514f942069e6b96ba72d835fe
76,306
cpp
C++
automated-tests/src/dali/utc-Dali-CameraActor.cpp
Coquinho/dali-core
97a968a80ad681b1cbbc219fa6729f2344672476
[ "Apache-2.0", "BSD-3-Clause" ]
21
2016-11-18T10:26:40.000Z
2021-11-02T09:46:15.000Z
automated-tests/src/dali/utc-Dali-CameraActor.cpp
Coquinho/dali-core
97a968a80ad681b1cbbc219fa6729f2344672476
[ "Apache-2.0", "BSD-3-Clause" ]
7
2016-10-18T17:39:12.000Z
2020-12-01T11:45:36.000Z
automated-tests/src/dali/utc-Dali-CameraActor.cpp
expertisesolutions/dali-core
444ee3f60f12a23aca07059c5e1109f26613e44e
[ "Apache-2.0", "BSD-3-Clause" ]
16
2017-03-08T15:50:32.000Z
2021-05-24T06:58:10.000Z
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. * * 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 <dali/public-api/dali-core.h> #include <dali/devel-api/actors/actor-devel.h> #include <dali/devel-api/actors/camera-actor-devel.h> #include <stdlib.h> #include <cmath> #include <iostream> #include "dali-test-suite-utils/dali-test-suite-utils.h" using namespace Dali; void camera_actor_test_startup(void) { test_return_value = TET_UNDEF; } void camera_actor_test_cleanup(void) { test_return_value = TET_PASS; } namespace { const float FLOAT_EPSILON = 0.001f; const float TEST_ASPECT_RATIO = 0.123f; const float TEST_FIELD_OF_VIEW = Radian(Degree(40.0f)); const float TEST_NEAR_PLANE_DISTANCE = 0.23f; const float TEST_FAR_PLANE_DISTANCE = 0.973f; const std::string SHADER_LIGHT_CAMERA_PROJECTION_MATRIX_PROPERTY_NAME("uLightCameraProjectionMatrix"); const std::string SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME("uLightCameraViewMatrix"); const char* const RENDER_SHADOW_VERTEX_SOURCE = " uniform mediump mat4 uLightCameraProjectionMatrix;\n" " uniform mediump mat4 uLightCameraViewMatrix;\n" "\n" "void main()\n" "{\n" " gl_Position = uProjection * uModelView * vec4(aPosition,1.0);\n" " vec4 textureCoords = uLightCameraProjectionMatrix * uLightCameraViewMatrix * uModelMatrix * vec4(aPosition,1.0);\n" " vTexCoord = 0.5 + 0.5 * (textureCoords.xy/textureCoords.w);\n" "}\n"; const char* const RENDER_SHADOW_FRAGMENT_SOURCE = "uniform lowp vec4 uShadowColor;\n" "void main()\n" "{\n" " lowp float alpha;\n" " alpha = texture2D(sTexture, vec2(vTexCoord.x, vTexCoord.y)).a;\n" " gl_FragColor = vec4(uShadowColor.rgb, uShadowColor.a * alpha);\n" "}\n"; struct PropertyDetails { std::string name; ///< The name of the property. Property::Type type; ///< The property type. bool writable; ///< Whether the property is writable bool animatable; ///< Whether the property is animatable. bool constraintInput; ///< Whether the property can be used as an input to a constraint. Property::Index enumIndex; ///< Used to check the index is correct within a debug build. }; } // Anonymous namespace int UtcDaliCameraActorConstructorP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::CameraActor()"); CameraActor actor; DALI_TEST_CHECK(!actor); END_TEST; } // Note: No negative test for UtcDaliCameraActorConstructor. int UtcDaliCameraActorDestructorP(void) { TestApplication application; tet_infoline("Testing Dali::~CameraActor (P)"); CameraActor* actor = new CameraActor(); delete actor; actor = NULL; DALI_TEST_CHECK(true); END_TEST; } // Note: No negative test for UtcDaliCameraActorDestructor. int UtcDaliCameraActorCopyConstructorP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Copy Constructor (P)"); CameraActor actor = CameraActor::New(); CameraActor copyActor(actor); DALI_TEST_CHECK(copyActor); DALI_TEST_CHECK(copyActor == actor); END_TEST; } int UtcDaliCameraActorCopyConstructorN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Copy Constructor (N)"); CameraActor actor; CameraActor copyActor(actor); DALI_TEST_CHECK(!copyActor); END_TEST; } int UtcDaliCameraActorAssignmentOperatorP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Assignment Operator (P)"); const CameraActor actor = CameraActor::New(); CameraActor copyActor = actor; DALI_TEST_CHECK(copyActor); DALI_TEST_CHECK(copyActor == actor); END_TEST; } int UtcDaliCameraActorAssignmentOperatorN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor = (N)"); CameraActor actor; CameraActor copyActor = actor; DALI_TEST_CHECK(!copyActor); END_TEST; } int UtcDaliCameraActorNewP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::New (P)"); CameraActor actor = CameraActor::New(); DALI_TEST_CHECK(actor); actor.Reset(); DALI_TEST_CHECK(!actor); END_TEST; } int UtcDaliCameraActorNewDefaultPerspectiveProjection(void) { TestApplication application; tet_infoline("Test the perspective projection of a camera actor is set appropriately when not passing in a size"); CameraActor actor = CameraActor::New(); DALI_TEST_CHECK(actor); // All the properties should still be the default values // Defaults taken from scene-graph-camera.cpp DALI_TEST_EQUALS(4.0f / 3.0f, actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(45.0f * (Math::PI / 180.0f), actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(800.0f, actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(3.0f * 800.0f, actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(0.0f, actor.GetProperty(Actor::Property::POSITION_Z).Get<float>(), TEST_LOCATION); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::PERSPECTIVE_PROJECTION, TEST_LOCATION); // Add it to the stage, then the values should be updated to reflect a 480.0f by 800.0f scene (default stage size) application.GetScene().Add(actor); DALI_TEST_EQUALS(0.6f, actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(0.489957f, actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(800.0f, actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(4895.0f, actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(1600.0f, actor.GetProperty(Actor::Property::POSITION_Z).Get<float>(), TEST_LOCATION); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::PERSPECTIVE_PROJECTION, TEST_LOCATION); // Ensure the values stay the same after update/render application.SendNotification(); application.Render(); DALI_TEST_EQUALS(0.6f, actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(0.489957f, actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(800.0f, actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(4895.0f, actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(1600.0f, actor.GetProperty(Actor::Property::POSITION_Z).Get<float>(), TEST_LOCATION); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::PERSPECTIVE_PROJECTION, TEST_LOCATION); END_TEST; } // Note: No negative test for UtcDaliCameraActorNew. int UtcDaliCameraActorDownCastP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::DownCast (P)"); CameraActor camera = CameraActor::New(); Actor anActor = Actor::New(); anActor.Add(camera); Actor child = anActor.GetChildAt(0); CameraActor cameraActor = CameraActor::DownCast(child); DALI_TEST_CHECK(cameraActor); cameraActor.Reset(); DALI_TEST_CHECK(!cameraActor); cameraActor = DownCast<CameraActor>(child); DALI_TEST_CHECK(cameraActor); END_TEST; } int UtcDaliCameraActorDownCastN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::DownCast (N)"); Actor actor1 = Actor::New(); Actor anActor = Actor::New(); anActor.Add(actor1); Actor child = anActor.GetChildAt(0); CameraActor cameraActor = CameraActor::DownCast(child); DALI_TEST_CHECK(!cameraActor); Actor unInitialzedActor; cameraActor = CameraActor::DownCast(unInitialzedActor); DALI_TEST_CHECK(!cameraActor); cameraActor = DownCast<CameraActor>(unInitialzedActor); DALI_TEST_CHECK(!cameraActor); END_TEST; } // Note: SetType and GetType are tested within the same test cases. int UtcDaliCameraActorSetGetTypeP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor GetType (P)"); CameraActor actor = CameraActor::New(); DALI_TEST_EQUALS(actor.GetType(), Dali::Camera::FREE_LOOK, TEST_LOCATION); actor.SetType(Dali::Camera::LOOK_AT_TARGET); DALI_TEST_EQUALS(actor.GetType(), Dali::Camera::LOOK_AT_TARGET, TEST_LOCATION); DALI_TEST_EQUALS("LOOK_AT_TARGET", actor.GetProperty<std::string>(CameraActor::Property::TYPE), TEST_LOCATION); DALI_TEST_EQUALS("LOOK_AT_TARGET", actor.GetCurrentProperty<std::string>(CameraActor::Property::TYPE), TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetGetTypeN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor GetType (N)"); CameraActor actor; Dali::Camera::Type cameraType = Dali::Camera::FREE_LOOK; try { cameraType = actor.GetType(); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera", TEST_LOCATION); } const CameraActor aConstActor; try { cameraType = aConstActor.GetType(); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera", TEST_LOCATION); } DALI_TEST_EQUALS(cameraType, Dali::Camera::FREE_LOOK, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetFieldOfViewP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Set Field of view (P)"); CameraActor defaultCamera = CameraActor::New(Size(TestApplication::DEFAULT_SURFACE_WIDTH, TestApplication::DEFAULT_SURFACE_HEIGHT)); const float defaultFieldOfView = defaultCamera.GetFieldOfView(); CameraActor actor = CameraActor::New(Size(TestApplication::DEFAULT_SURFACE_WIDTH, TestApplication::DEFAULT_SURFACE_HEIGHT)); DALI_TEST_EQUALS(actor.GetFieldOfView(), defaultFieldOfView, TEST_LOCATION); float fieldOfView = Math::PI / 3.0f; actor.SetFieldOfView(fieldOfView); DALI_TEST_EQUALS(actor.GetFieldOfView(), fieldOfView, TEST_LOCATION); float value; actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get(value); DALI_TEST_EQUALS(fieldOfView, value, FLOAT_EPSILON, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetFieldOfViewN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Set Field of view (N)"); CameraActor defaultCamera = CameraActor::New(Size(TestApplication::DEFAULT_SURFACE_WIDTH, TestApplication::DEFAULT_SURFACE_HEIGHT)); const float defaultFieldOfView = defaultCamera.GetFieldOfView(); CameraActor actor = CameraActor::New(Size(TestApplication::DEFAULT_SURFACE_WIDTH, TestApplication::DEFAULT_SURFACE_HEIGHT)); DALI_TEST_EQUALS(actor.GetFieldOfView(), defaultFieldOfView, TEST_LOCATION); float fieldOfView = Math::PI / 3.0f; actor.SetFieldOfView(fieldOfView); DALI_TEST_EQUALS(actor.GetFieldOfView(), fieldOfView, TEST_LOCATION); float value; actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get(value); DALI_TEST_EQUALS(fieldOfView, value, FLOAT_EPSILON, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorGetFieldOfViewP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Get Field of view (P)"); const Vector2 size(TestApplication::DEFAULT_SURFACE_WIDTH, TestApplication::DEFAULT_SURFACE_HEIGHT); CameraActor defaultCamera = CameraActor::New(size); const float cameraZ = 2.0f * std::max(size.width, size.height); const float expectedFieldOfView = 2.0f * std::atan(size.height * 0.5f / cameraZ); CameraActor actor = CameraActor::New(size); DALI_TEST_EQUALS(actor.GetFieldOfView(), expectedFieldOfView, TEST_LOCATION); float value; actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get(value); DALI_TEST_EQUALS(expectedFieldOfView, value, FLOAT_EPSILON, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorGetFieldOfViewN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Get Field of view (N)"); CameraActor defaultCamera = CameraActor::New(); bool asserted = true; try { defaultCamera.GetFieldOfView(); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorSetAspectRatioP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Set Aspect Ratio (P)"); CameraActor actor = CameraActor::New(Size(TestApplication::DEFAULT_SURFACE_WIDTH, TestApplication::DEFAULT_SURFACE_HEIGHT)); DALI_TEST_EQUALS(actor.GetAspectRatio(), static_cast<float>(TestApplication::DEFAULT_SURFACE_WIDTH) / static_cast<float>(TestApplication::DEFAULT_SURFACE_HEIGHT), TEST_LOCATION); // Set an initial value to confirm a further set changes it. float aspect = 4.0f / 3.0f; actor.SetAspectRatio(aspect); DALI_TEST_EQUALS(actor.GetAspectRatio(), aspect, TEST_LOCATION); aspect = 16.0f / 9.0f; actor.SetAspectRatio(aspect); DALI_TEST_EQUALS(actor.GetAspectRatio(), aspect, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetAspectRatioN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Set Aspect Ratio (N)"); CameraActor actor; bool asserted = true; try { actor.SetAspectRatio(16.0f / 9.0f); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorGetAspectRatioP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Get Aspect Ratio"); CameraActor actor = CameraActor::New(Size(TestApplication::DEFAULT_SURFACE_WIDTH, TestApplication::DEFAULT_SURFACE_HEIGHT)); float defaultAspect = static_cast<float>(TestApplication::DEFAULT_SURFACE_WIDTH) / static_cast<float>(TestApplication::DEFAULT_SURFACE_HEIGHT); DALI_TEST_EQUALS(actor.GetAspectRatio(), defaultAspect, TEST_LOCATION); float value = 0.0f; actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get(value); DALI_TEST_EQUALS(defaultAspect, value, FLOAT_EPSILON, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorGetAspectRatioN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Get Aspect Ratio (N)"); CameraActor actor; bool asserted = true; try { actor.GetAspectRatio(); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorSetNearClippingPlaneP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Set Near clipping plane (P)"); CameraActor actor = CameraActor::New(); // Set a value so we are not relying on a particular default for this test case. actor.SetNearClippingPlane(200.0f); DALI_TEST_EQUALS(actor.GetNearClippingPlane(), 200.0f, TEST_LOCATION); actor.SetNearClippingPlane(400.0f); DALI_TEST_EQUALS(actor.GetNearClippingPlane(), 400.0f, TEST_LOCATION); // Check setting the property. actor.SetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE, Property::Value(300.0f)); DALI_TEST_EQUALS(actor.GetNearClippingPlane(), 300.0f, FLOAT_EPSILON, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetNearClippingPlaneN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Set Near clipping plane (N)"); CameraActor actor; bool asserted = true; try { actor.SetNearClippingPlane(200.0f); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorGetNearClippingPlaneP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Get Near clipping plane (P)"); // Check the default value. CameraActor actor = CameraActor::New(); float defaultValue = 800.0f; DALI_TEST_EQUALS(actor.GetNearClippingPlane(), defaultValue, TEST_LOCATION); // Check getting the property. float value; actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(defaultValue, value, FLOAT_EPSILON, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorGetNearClippingPlaneN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Get Near clipping plane (N)"); CameraActor actor; bool asserted = true; try { actor.GetNearClippingPlane(); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorSetFarClippingPlaneP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Set Far clipping plane (P)"); CameraActor actor = CameraActor::New(); // Set a value so we are not relying on a particular default for this test case. actor.SetFarClippingPlane(2000.0f); DALI_TEST_EQUALS(actor.GetFarClippingPlane(), 2000.0f, TEST_LOCATION); actor.SetFarClippingPlane(4000.0f); DALI_TEST_EQUALS(actor.GetFarClippingPlane(), 4000.0f, TEST_LOCATION); // Check setting the property. actor.SetProperty(CameraActor::Property::FAR_PLANE_DISTANCE, 2000.0f); DALI_TEST_EQUALS(actor.GetFarClippingPlane(), 2000.0f, FLOAT_EPSILON, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetFarClippingPlaneN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Set Far clipping plane (N)"); CameraActor actor; bool asserted = true; try { actor.SetFarClippingPlane(2000.0f); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorGetFarClippingPlaneP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Get Far clipping plane (P)"); CameraActor actor = CameraActor::New(Size(TestApplication::DEFAULT_SURFACE_WIDTH, TestApplication::DEFAULT_SURFACE_HEIGHT)); float defaultValue = 800.0f + (0xFFFF >> 4); DALI_TEST_EQUALS(actor.GetFarClippingPlane(), defaultValue, TEST_LOCATION); // Check getting the property. float value; actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(defaultValue, value, FLOAT_EPSILON, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorGetFarClippingPlaneN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Get Far clipping plane (N)"); CameraActor actor; bool asserted = true; try { actor.GetFarClippingPlane(); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorSetTargetPositionP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Set Target Position (P)"); CameraActor actor = CameraActor::New(); Vector3 target1(10.0f, 20.0f, 30.0f); Vector3 target2(15.0f, 25.0f, 35.0f); // Set a value so we are not relying on a particular default for this test case. actor.SetTargetPosition(target1); DALI_TEST_EQUALS(actor.GetTargetPosition(), target1, TEST_LOCATION); actor.SetTargetPosition(target2); DALI_TEST_EQUALS(actor.GetTargetPosition(), target2, TEST_LOCATION); // Check setting the property. actor.SetProperty(CameraActor::Property::TARGET_POSITION, target1); DALI_TEST_EQUALS(actor.GetTargetPosition(), target1, FLOAT_EPSILON, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetTargetPositionN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Set Target Position (N)"); CameraActor actor; bool asserted = true; try { actor.SetTargetPosition(Vector3(10.0f, 20.0f, 30.0f)); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorGetTargetPositionP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Get Target Position (P)"); CameraActor actor = CameraActor::New(); Vector3 defaultValue(Vector3::ZERO); DALI_TEST_EQUALS(actor.GetTargetPosition(), defaultValue, TEST_LOCATION); // Check getting the property. Vector3 value; actor.GetProperty(CameraActor::Property::TARGET_POSITION).Get(value); DALI_TEST_EQUALS(defaultValue, value, FLOAT_EPSILON, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorGetTargetPositionN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Get Target Position (N)"); CameraActor actor; bool asserted = true; try { actor.GetTargetPosition(); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorSetInvertYAxisP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Set InvertYAxis (P)"); CameraActor actor = CameraActor::New(); // Set a value so we are not relying on a particular default for this test case. actor.SetInvertYAxis(false); DALI_TEST_EQUALS(actor.GetInvertYAxis(), false, TEST_LOCATION); actor.SetInvertYAxis(true); DALI_TEST_EQUALS(actor.GetInvertYAxis(), true, TEST_LOCATION); actor.SetProperty(CameraActor::Property::INVERT_Y_AXIS, false); DALI_TEST_EQUALS(actor.GetInvertYAxis(), false, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetInvertYAxisN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Set InvertYAxis (N)"); CameraActor actor; bool asserted = true; try { actor.SetInvertYAxis(false); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorGetInvertYAxisP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Get InvertYAxis (P)"); // Check the default value. CameraActor actor = CameraActor::New(); DALI_TEST_EQUALS(actor.GetInvertYAxis(), false, TEST_LOCATION); // Check getting the property. bool bValue; actor.GetProperty(CameraActor::Property::INVERT_Y_AXIS).Get(bValue); DALI_TEST_EQUALS(false, bValue, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorGetInvertYAxisN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Get InvertYAxis (N)"); CameraActor actor; bool asserted = true; try { actor.GetInvertYAxis(); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorSetPerspectiveProjectionP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::SetPerspectiveProjection (P)"); CameraActor actor = CameraActor::New(); actor.SetPerspectiveProjection(Size(100.f, 150.f)); DALI_TEST_CHECK(actor); float value; actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get(value); DALI_TEST_EQUALS(0.666666f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get(value); DALI_TEST_EQUALS(0.489957f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(150.f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(4245.f, value, FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::PERSPECTIVE_PROJECTION, TEST_LOCATION); // Ensure these values persist after adding to the stage and an update/render pass application.GetScene().Add(actor); application.SendNotification(); application.Render(); actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get(value); DALI_TEST_EQUALS(0.666666f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get(value); DALI_TEST_EQUALS(0.489957f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(150.f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(4245.f, value, FLOAT_EPSILON, TEST_LOCATION); // Call method with a ZERO size, this should reset the perspective projection using the size of the scene we've been added to actor.SetPerspectiveProjection(Vector2::ZERO); DALI_TEST_EQUALS(0.6f, actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(0.489957f, actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(800.0f, actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(4895.0f, actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get<float>(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(1600.0f, actor.GetProperty(Actor::Property::POSITION_Z).Get<float>(), TEST_LOCATION); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::PERSPECTIVE_PROJECTION, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetPerspectiveProjectionN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::SetPerspectiveProjection (N)"); CameraActor actor = CameraActor::New(); // Check that setting perspective projection without a size does not do anything. actor.SetPerspectiveProjection(Size::ZERO); // So the default values should be the same as defined in CameraActor float nearClippingPlane = 800.0f; float farClippingPlane = nearClippingPlane + 2.0f * nearClippingPlane; DALI_TEST_EQUALS(nearClippingPlane, actor.GetNearClippingPlane(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(farClippingPlane, actor.GetFarClippingPlane(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::PERSPECTIVE_PROJECTION, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetOrthographicProjectionP1(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::SetOrthographicProjection (P,1)"); CameraActor actor = CameraActor::New(Size(1080.0f, 1920.0f)); DALI_TEST_CHECK(actor); application.GetScene().Add(actor); actor.SetOrthographicProjection(Size(1080.0f, 1920.0f)); application.SendNotification(); application.Render(0); application.Render(); application.SendNotification(); float defaultAspectRatio; float defaultFieldOfView; float defaultNearPlaneDistance; float defaultFarPlaneDistance; actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get(defaultAspectRatio); actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get(defaultFieldOfView); actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get(defaultNearPlaneDistance); actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get(defaultFarPlaneDistance); Vector3 defaultPos = actor.GetCurrentProperty<Vector3>(Actor::Property::POSITION); actor.SetOrthographicProjection(Size(1080.0f, 1920.0f)); application.SendNotification(); application.Render(0); application.Render(); application.SendNotification(); float value; actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get(value); DALI_TEST_EQUALS(defaultAspectRatio, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get(value); DALI_TEST_EQUALS(defaultFieldOfView, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(defaultNearPlaneDistance, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(defaultFarPlaneDistance, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::LEFT_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(-540.0f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::RIGHT_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(540.0f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::TOP_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(960.0f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::BOTTOM_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(-960.0f, value, FLOAT_EPSILON, TEST_LOCATION); Vector3 pos = actor.GetCurrentProperty<Vector3>(Actor::Property::POSITION); DALI_TEST_EQUALS(defaultPos.z, pos.z, 0.001f, TEST_LOCATION); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::ORTHOGRAPHIC_PROJECTION, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetOrthographicProjectionN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::SetOrthographicProjection (N)"); CameraActor actor; bool asserted = true; try { actor.GetProjectionMode(); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorSetOrthographicProjectionP2(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::SetOrthographicProjection (P,2)"); CameraActor actor = CameraActor::New(); DALI_TEST_CHECK(actor); float defaultAspectRatio; float defaultFieldOfView; float defaultNearPlaneDistance; float defaultFarPlaneDistance; actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get(defaultAspectRatio); actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get(defaultFieldOfView); actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get(defaultNearPlaneDistance); actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get(defaultFarPlaneDistance); // Check setting with specific near and far plane distances. actor.SetOrthographicProjection(-100.0f, 200.0f, -300.0f, 500.0f, 400.0f, 4000.0f); float value; actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get(value); DALI_TEST_EQUALS(defaultAspectRatio, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get(value); DALI_TEST_EQUALS(defaultFieldOfView, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(400.0f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(4000.0f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::LEFT_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(-100.0f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::RIGHT_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(200.0f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::TOP_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(-300.0f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::BOTTOM_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(500.0f, value, FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::ORTHOGRAPHIC_PROJECTION, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetOrthographicProjectionP3(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::SetOrthographicProjection (P,3)"); CameraActor actor = CameraActor::New(); DALI_TEST_CHECK(actor); float defaultAspectRatio; float defaultFieldOfView; float defaultNearPlaneDistance; float defaultFarPlaneDistance; actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get(defaultAspectRatio); actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get(defaultFieldOfView); actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get(defaultNearPlaneDistance); actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get(defaultFarPlaneDistance); actor.SetProjectionMode(Dali::Camera::ORTHOGRAPHIC_PROJECTION); actor.SetProperty(CameraActor::Property::LEFT_PLANE_DISTANCE, -100.0f); actor.SetProperty(CameraActor::Property::RIGHT_PLANE_DISTANCE, 200.0f); actor.SetProperty(CameraActor::Property::TOP_PLANE_DISTANCE, -300.0f); actor.SetProperty(CameraActor::Property::BOTTOM_PLANE_DISTANCE, 500.0f); actor.SetNearClippingPlane(400.0f); actor.SetFarClippingPlane(4000.0f); float value; actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get(value); DALI_TEST_EQUALS(defaultAspectRatio, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get(value); DALI_TEST_EQUALS(defaultFieldOfView, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(400.0f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(4000.0f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::LEFT_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(-100.0f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::RIGHT_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(200.0f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::TOP_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(-300.0f, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::BOTTOM_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(500.0f, value, FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::ORTHOGRAPHIC_PROJECTION, TEST_LOCATION); std::string stringValue; actor.GetProperty(CameraActor::Property::PROJECTION_MODE).Get(stringValue); DALI_TEST_EQUALS(stringValue, "ORTHOGRAPHIC_PROJECTION", TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetProjectionModeP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::SetProjectionModeP (P)"); CameraActor actor = CameraActor::New(); // Check that changing the projection mode alone does not alter other presets. actor.SetNearClippingPlane(200.0f); actor.SetFarClippingPlane(400.0f); actor.SetProjectionMode(Dali::Camera::PERSPECTIVE_PROJECTION); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::PERSPECTIVE_PROJECTION, TEST_LOCATION); DALI_TEST_EQUALS(actor.GetNearClippingPlane(), 200.0f, FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(actor.GetFarClippingPlane(), 400.0f, FLOAT_EPSILON, TEST_LOCATION); actor.SetProjectionMode(Dali::Camera::ORTHOGRAPHIC_PROJECTION); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::ORTHOGRAPHIC_PROJECTION, TEST_LOCATION); DALI_TEST_EQUALS(actor.GetNearClippingPlane(), 200.0f, FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(actor.GetFarClippingPlane(), 400.0f, FLOAT_EPSILON, TEST_LOCATION); // Check setting the property. Property::Value setValue = "PERSPECTIVE_PROJECTION"; actor.SetProperty(CameraActor::Property::PROJECTION_MODE, setValue); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::PERSPECTIVE_PROJECTION, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetProjectionModeN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::SetProjectionModeP (N)"); CameraActor actor; bool asserted = true; try { actor.SetProjectionMode(Dali::Camera::PERSPECTIVE_PROJECTION); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorGetProjectionModeP(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::GetPerspectiveProjection (P)"); CameraActor actor = CameraActor::New(); actor.SetOrthographicProjection(Size::ONE); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::ORTHOGRAPHIC_PROJECTION, TEST_LOCATION); actor.SetPerspectiveProjection(Size(100.f, 150.f)); DALI_TEST_EQUALS(actor.GetProjectionMode(), Dali::Camera::PERSPECTIVE_PROJECTION, TEST_LOCATION); // Check getting the property. std::string stringValue; actor.GetProperty(CameraActor::Property::PROJECTION_MODE).Get(stringValue); DALI_TEST_EQUALS(stringValue, "PERSPECTIVE_PROJECTION", TEST_LOCATION); END_TEST; } int UtcDaliCameraActorGetProjectionModeN(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::GetProjectionMode (N)"); CameraActor actor; bool asserted = true; try { actor.GetProjectionMode(); } catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT(e); DALI_TEST_ASSERT(e, "camera && \"Camera handle is empty\"", TEST_LOCATION); asserted = true; } DALI_TEST_CHECK(asserted); END_TEST; } int UtcDaliCameraActorSetCameraOffScene(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::SetCamera()"); CameraActor actor = CameraActor::New(); actor.SetType(Camera::FREE_LOOK); actor.SetFieldOfView(TEST_FIELD_OF_VIEW); actor.SetAspectRatio(TEST_ASPECT_RATIO); actor.SetNearClippingPlane(TEST_NEAR_PLANE_DISTANCE); actor.SetFarClippingPlane(TEST_FAR_PLANE_DISTANCE); actor.SetProjectionMode(Camera::PERSPECTIVE_PROJECTION); actor.SetInvertYAxis(false); DALI_TEST_EQUALS(TEST_ASPECT_RATIO, actor.GetAspectRatio(), FLOAT_EPSILON, TEST_LOCATION); //change to machine epsilon DALI_TEST_EQUALS(TEST_FIELD_OF_VIEW, actor.GetFieldOfView(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(TEST_NEAR_PLANE_DISTANCE, actor.GetNearClippingPlane(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(TEST_FAR_PLANE_DISTANCE, actor.GetFarClippingPlane(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(Camera::PERSPECTIVE_PROJECTION, actor.GetProjectionMode(), TEST_LOCATION); DALI_TEST_EQUALS(false, actor.GetInvertYAxis(), TEST_LOCATION); float value; std::string sValue; actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get(value); DALI_TEST_EQUALS(TEST_ASPECT_RATIO, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get(value); DALI_TEST_EQUALS(TEST_FIELD_OF_VIEW, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(TEST_NEAR_PLANE_DISTANCE, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(TEST_FAR_PLANE_DISTANCE, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::PROJECTION_MODE).Get(sValue); DALI_TEST_EQUALS("PERSPECTIVE_PROJECTION", sValue, TEST_LOCATION); bool bValue; actor.GetProperty(CameraActor::Property::INVERT_Y_AXIS).Get(bValue); DALI_TEST_EQUALS(false, bValue, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorSetCameraOnScene(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::SetCamera()"); CameraActor actor = CameraActor::New(); application.GetScene().Add(actor); application.Render(0); application.SendNotification(); actor.SetType(Camera::LOOK_AT_TARGET); actor.SetFieldOfView(TEST_FIELD_OF_VIEW); actor.SetAspectRatio(TEST_ASPECT_RATIO); actor.SetNearClippingPlane(TEST_NEAR_PLANE_DISTANCE); actor.SetFarClippingPlane(TEST_FAR_PLANE_DISTANCE); actor.SetInvertYAxis(false); DALI_TEST_EQUALS(false, actor.GetInvertYAxis(), TEST_LOCATION); // Will need 2 frames to ensure both buffers are set to same values: application.Render(); application.SendNotification(); application.Render(); application.SendNotification(); DALI_TEST_EQUALS(TEST_ASPECT_RATIO, actor.GetAspectRatio(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(TEST_FIELD_OF_VIEW, actor.GetFieldOfView(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(TEST_NEAR_PLANE_DISTANCE, actor.GetNearClippingPlane(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(TEST_FAR_PLANE_DISTANCE, actor.GetFarClippingPlane(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(false, actor.GetInvertYAxis(), TEST_LOCATION); std::string sValue; actor.GetProperty(CameraActor::Property::TYPE).Get(sValue); DALI_TEST_EQUALS(sValue, "LOOK_AT_TARGET", TEST_LOCATION); float value; actor.GetProperty(CameraActor::Property::ASPECT_RATIO).Get(value); DALI_TEST_EQUALS(TEST_ASPECT_RATIO, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FIELD_OF_VIEW).Get(value); DALI_TEST_EQUALS(TEST_FIELD_OF_VIEW, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(TEST_NEAR_PLANE_DISTANCE, value, FLOAT_EPSILON, TEST_LOCATION); actor.GetProperty(CameraActor::Property::FAR_PLANE_DISTANCE).Get(value); DALI_TEST_EQUALS(TEST_FAR_PLANE_DISTANCE, value, FLOAT_EPSILON, TEST_LOCATION); bool bValue; actor.GetProperty(CameraActor::Property::INVERT_Y_AXIS).Get(bValue); DALI_TEST_EQUALS(false, bValue, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorGetCamera(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::GetCamera()"); CameraActor actor = CameraActor::New(); actor.SetAspectRatio(TEST_ASPECT_RATIO); DALI_TEST_EQUALS(actor.GetAspectRatio(), TEST_ASPECT_RATIO, FLOAT_EPSILON, TEST_LOCATION); actor.SetProperty(CameraActor::Property::TYPE, "FREE_LOOK"); actor.SetProperty(CameraActor::Property::ASPECT_RATIO, TEST_ASPECT_RATIO); actor.SetProperty(CameraActor::Property::FIELD_OF_VIEW, TEST_FIELD_OF_VIEW); actor.SetProperty(CameraActor::Property::NEAR_PLANE_DISTANCE, TEST_NEAR_PLANE_DISTANCE); actor.SetProperty(CameraActor::Property::FAR_PLANE_DISTANCE, TEST_FAR_PLANE_DISTANCE); DALI_TEST_EQUALS(Camera::FREE_LOOK, actor.GetType(), TEST_LOCATION); DALI_TEST_EQUALS(TEST_ASPECT_RATIO, actor.GetAspectRatio(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(TEST_FIELD_OF_VIEW, actor.GetFieldOfView(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(TEST_NEAR_PLANE_DISTANCE, actor.GetNearClippingPlane(), FLOAT_EPSILON, TEST_LOCATION); DALI_TEST_EQUALS(TEST_FAR_PLANE_DISTANCE, actor.GetFarClippingPlane(), FLOAT_EPSILON, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorDefaultProperties(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor DefaultProperties"); CameraActor actor = CameraActor::New(); Integration::Scene stage = application.GetScene(); stage.Add(actor); stage.GetRenderTaskList().GetTask(0).SetCameraActor(actor); actor.SetAspectRatio(TEST_ASPECT_RATIO); application.GetScene().Add(actor); application.Render(0); application.SendNotification(); bool bValue; actor.GetProperty(CameraActor::Property::INVERT_Y_AXIS).Get(bValue); DALI_TEST_EQUALS(false, bValue, TEST_LOCATION); std::vector<Property::Index> indices; indices.push_back(CameraActor::Property::TYPE); indices.push_back(CameraActor::Property::PROJECTION_MODE); indices.push_back(CameraActor::Property::FIELD_OF_VIEW); indices.push_back(CameraActor::Property::ASPECT_RATIO); indices.push_back(CameraActor::Property::NEAR_PLANE_DISTANCE); indices.push_back(CameraActor::Property::FAR_PLANE_DISTANCE); indices.push_back(CameraActor::Property::LEFT_PLANE_DISTANCE); indices.push_back(CameraActor::Property::RIGHT_PLANE_DISTANCE); indices.push_back(CameraActor::Property::TOP_PLANE_DISTANCE); indices.push_back(CameraActor::Property::BOTTOM_PLANE_DISTANCE); indices.push_back(CameraActor::Property::TARGET_POSITION); indices.push_back(CameraActor::Property::PROJECTION_MATRIX); indices.push_back(CameraActor::Property::VIEW_MATRIX); indices.push_back(CameraActor::Property::INVERT_Y_AXIS); DALI_TEST_CHECK(actor.GetPropertyCount() == (Actor::New().GetPropertyCount() + indices.size())); for(std::vector<Property::Index>::iterator iter = indices.begin(); iter != indices.end(); ++iter) { DALI_TEST_EQUALS(*iter, actor.GetPropertyIndex(actor.GetPropertyName(*iter)), TEST_LOCATION); DALI_TEST_CHECK(!actor.IsPropertyAnimatable(*iter)); if((*iter == CameraActor::Property::PROJECTION_MATRIX) || (*iter == CameraActor::Property::VIEW_MATRIX)) { DALI_TEST_CHECK(!actor.IsPropertyWritable(*iter)); } else { DALI_TEST_CHECK(actor.IsPropertyWritable(*iter)); } DALI_TEST_CHECK(actor.GetPropertyType(*iter) == actor.GetPropertyType(*iter)); // just checking call succeeds } // Set/Get one of them. const float newAspect = TEST_ASPECT_RATIO * 2.0f; actor.SetProperty(CameraActor::Property::ASPECT_RATIO, Property::Value(newAspect)); application.Render(); application.SendNotification(); application.Render(); application.SendNotification(); DALI_TEST_EQUALS(actor.GetAspectRatio(), newAspect, TEST_LOCATION); END_TEST; } template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8> void TEST_CAMERA_PROPERTY(P1 camera, P2 stringName, P3 type, P4 isWriteable, P5 isAnimateable, P6 isConstraintInput, P7 enumName, P8 LOCATION) { DALI_TEST_EQUALS(camera.GetPropertyName(enumName), stringName, LOCATION); DALI_TEST_EQUALS(camera.GetPropertyIndex(stringName), static_cast<Property::Index>(enumName), LOCATION); DALI_TEST_EQUALS(camera.GetPropertyType(enumName), type, LOCATION); DALI_TEST_EQUALS(camera.IsPropertyWritable(enumName), isWriteable, LOCATION); DALI_TEST_EQUALS(camera.IsPropertyAnimatable(enumName), isAnimateable, LOCATION); DALI_TEST_EQUALS(camera.IsPropertyAConstraintInput(enumName), isConstraintInput, LOCATION); } int UtcDaliCameraActorDefaultPropertiesInherited(void) { TestApplication application; CameraActor actor = CameraActor::New(); Integration::Scene stage = application.GetScene(); stage.Add(actor); stage.GetRenderTaskList().GetTask(0).SetCameraActor(actor); application.GetScene().Add(actor); application.Render(0); application.SendNotification(); const PropertyDetails CAMERA_DEFAULT_PROPERTY[] = { // actor {"parentOrigin", Property::VECTOR3, true, false, true, Dali::Actor::Property::PARENT_ORIGIN}, {"parentOriginX", Property::FLOAT, true, false, true, Dali::Actor::Property::PARENT_ORIGIN_X}, {"parentOriginY", Property::FLOAT, true, false, true, Dali::Actor::Property::PARENT_ORIGIN_Y}, {"parentOriginZ", Property::FLOAT, true, false, true, Dali::Actor::Property::PARENT_ORIGIN_Z}, {"anchorPoint", Property::VECTOR3, true, false, true, Dali::Actor::Property::ANCHOR_POINT}, {"anchorPointX", Property::FLOAT, true, false, true, Dali::Actor::Property::ANCHOR_POINT_X}, {"anchorPointY", Property::FLOAT, true, false, true, Dali::Actor::Property::ANCHOR_POINT_Y}, {"anchorPointZ", Property::FLOAT, true, false, true, Dali::Actor::Property::ANCHOR_POINT_Z}, {"size", Property::VECTOR3, true, true, true, Dali::Actor::Property::SIZE}, {"sizeWidth", Property::FLOAT, true, true, true, Dali::Actor::Property::SIZE_WIDTH}, {"sizeHeight", Property::FLOAT, true, true, true, Dali::Actor::Property::SIZE_HEIGHT}, {"sizeDepth", Property::FLOAT, true, true, true, Dali::Actor::Property::SIZE_DEPTH}, {"position", Property::VECTOR3, true, true, true, Dali::Actor::Property::POSITION}, {"positionX", Property::FLOAT, true, true, true, Dali::Actor::Property::POSITION_X}, {"positionY", Property::FLOAT, true, true, true, Dali::Actor::Property::POSITION_Y}, {"positionZ", Property::FLOAT, true, true, true, Dali::Actor::Property::POSITION_Z}, {"worldPosition", Property::VECTOR3, false, false, true, Dali::Actor::Property::WORLD_POSITION}, {"worldPositionX", Property::FLOAT, false, false, true, Dali::Actor::Property::WORLD_POSITION_X}, {"worldPositionY", Property::FLOAT, false, false, true, Dali::Actor::Property::WORLD_POSITION_Y}, {"worldPositionZ", Property::FLOAT, false, false, true, Dali::Actor::Property::WORLD_POSITION_Z}, {"orientation", Property::ROTATION, true, true, true, Dali::Actor::Property::ORIENTATION}, {"worldOrientation", Property::ROTATION, false, false, true, Dali::Actor::Property::WORLD_ORIENTATION}, {"scale", Property::VECTOR3, true, true, true, Dali::Actor::Property::SCALE}, {"scaleX", Property::FLOAT, true, true, true, Dali::Actor::Property::SCALE_X}, {"scaleY", Property::FLOAT, true, true, true, Dali::Actor::Property::SCALE_Y}, {"scaleZ", Property::FLOAT, true, true, true, Dali::Actor::Property::SCALE_Z}, {"worldScale", Property::VECTOR3, false, false, true, Dali::Actor::Property::WORLD_SCALE}, {"visible", Property::BOOLEAN, true, true, true, Dali::Actor::Property::VISIBLE}, {"color", Property::VECTOR4, true, true, true, Dali::Actor::Property::COLOR}, {"colorRed", Property::FLOAT, true, true, true, Dali::Actor::Property::COLOR_RED}, {"colorGreen", Property::FLOAT, true, true, true, Dali::Actor::Property::COLOR_GREEN}, {"colorBlue", Property::FLOAT, true, true, true, Dali::Actor::Property::COLOR_BLUE}, {"colorAlpha", Property::FLOAT, true, true, true, Dali::Actor::Property::COLOR_ALPHA}, {"worldColor", Property::VECTOR4, false, false, true, Dali::Actor::Property::WORLD_COLOR}, {"worldMatrix", Property::MATRIX, false, false, true, Dali::Actor::Property::WORLD_MATRIX}, {"name", Property::STRING, true, false, false, Dali::Actor::Property::NAME}, {"sensitive", Property::BOOLEAN, true, false, false, Dali::Actor::Property::SENSITIVE}, {"leaveRequired", Property::BOOLEAN, true, false, false, Dali::Actor::Property::LEAVE_REQUIRED}, {"inheritOrientation", Property::BOOLEAN, true, false, false, Dali::Actor::Property::INHERIT_ORIENTATION}, {"inheritScale", Property::BOOLEAN, true, false, false, Dali::Actor::Property::INHERIT_SCALE}, {"colorMode", Property::INTEGER, true, false, false, Dali::Actor::Property::COLOR_MODE}, {"drawMode", Property::INTEGER, true, false, false, Dali::Actor::Property::DRAW_MODE}, {"sizeModeFactor", Property::VECTOR3, true, false, false, Dali::Actor::Property::SIZE_MODE_FACTOR}, {"widthResizePolicy", Property::STRING, true, false, false, Dali::Actor::Property::WIDTH_RESIZE_POLICY}, {"heightResizePolicy", Property::STRING, true, false, false, Dali::Actor::Property::HEIGHT_RESIZE_POLICY}, {"sizeScalePolicy", Property::INTEGER, true, false, false, Dali::Actor::Property::SIZE_SCALE_POLICY}, {"widthForHeight", Property::BOOLEAN, true, false, false, Dali::Actor::Property::WIDTH_FOR_HEIGHT}, {"heightForWidth", Property::BOOLEAN, true, false, false, Dali::Actor::Property::HEIGHT_FOR_WIDTH}, {"padding", Property::VECTOR4, true, false, false, Dali::Actor::Property::PADDING}, {"minimumSize", Property::VECTOR2, true, false, false, Dali::Actor::Property::MINIMUM_SIZE}, {"maximumSize", Property::VECTOR2, true, false, false, Dali::Actor::Property::MAXIMUM_SIZE}, {"inheritPosition", Property::BOOLEAN, true, false, false, Dali::Actor::Property::INHERIT_POSITION}, {"clippingMode", Property::STRING, true, false, false, Dali::Actor::Property::CLIPPING_MODE}, {"layoutDirection", Property::STRING, true, false, false, Dali::Actor::Property::LAYOUT_DIRECTION}, {"inheritLayoutDirection", Property::BOOLEAN, true, false, false, Dali::Actor::Property::INHERIT_LAYOUT_DIRECTION}, {"opacity", Property::FLOAT, true, true, true, Dali::Actor::Property::OPACITY}, {"screenPosition", Property::VECTOR2, false, false, false, Dali::Actor::Property::SCREEN_POSITION}, {"positionUsesAnchorPoint", Property::BOOLEAN, true, false, false, Dali::Actor::Property::POSITION_USES_ANCHOR_POINT}, {"culled", Property::BOOLEAN, false, false, true, Dali::Actor::Property::CULLED}, {"id", Property::INTEGER, false, false, false, Dali::Actor::Property::ID}, {"hierarchyDepth", Property::INTEGER, false, false, false, Dali::Actor::Property::HIERARCHY_DEPTH}, {"isRoot", Property::BOOLEAN, false, false, false, Dali::Actor::Property::IS_ROOT}, {"isLayer", Property::BOOLEAN, false, false, false, Dali::Actor::Property::IS_LAYER}, {"connectedToScene", Property::BOOLEAN, false, false, false, Dali::Actor::Property::CONNECTED_TO_SCENE}, {"keyboardFocusable", Property::BOOLEAN, true, false, false, Dali::Actor::Property::KEYBOARD_FOCUSABLE}, {"siblingOrder", Property::INTEGER, true, false, false, Dali::DevelActor::Property::SIBLING_ORDER}, // camera own {"type", Property::STRING, true, false, true, Dali::CameraActor::Property::TYPE}, {"projectionMode", Property::STRING, true, false, true, Dali::CameraActor::Property::PROJECTION_MODE}, {"fieldOfView", Property::FLOAT, true, false, true, Dali::CameraActor::Property::FIELD_OF_VIEW}, {"aspectRatio", Property::FLOAT, true, false, true, Dali::CameraActor::Property::ASPECT_RATIO}, {"nearPlaneDistance", Property::FLOAT, true, false, true, Dali::CameraActor::Property::NEAR_PLANE_DISTANCE}, {"farPlaneDistance", Property::FLOAT, true, false, true, Dali::CameraActor::Property::FAR_PLANE_DISTANCE}, {"leftPlaneDistance", Property::FLOAT, true, false, true, Dali::CameraActor::Property::LEFT_PLANE_DISTANCE}, {"rightPlaneDistance", Property::FLOAT, true, false, true, Dali::CameraActor::Property::RIGHT_PLANE_DISTANCE}, {"topPlaneDistance", Property::FLOAT, true, false, true, Dali::CameraActor::Property::TOP_PLANE_DISTANCE}, {"bottomPlaneDistance", Property::FLOAT, true, false, true, Dali::CameraActor::Property::BOTTOM_PLANE_DISTANCE}, {"targetPosition", Property::VECTOR3, true, false, true, Dali::CameraActor::Property::TARGET_POSITION}, {"projectionMatrix", Property::MATRIX, false, false, true, Dali::CameraActor::Property::PROJECTION_MATRIX}, {"viewMatrix", Property::MATRIX, false, false, true, Dali::CameraActor::Property::VIEW_MATRIX}, {"invertYAxis", Property::BOOLEAN, true, false, true, Dali::CameraActor::Property::INVERT_Y_AXIS}}; for(uint32_t index = 0; index < (sizeof(CAMERA_DEFAULT_PROPERTY) / sizeof(PropertyDetails)); ++index) { TEST_CAMERA_PROPERTY(actor, CAMERA_DEFAULT_PROPERTY[index].name, CAMERA_DEFAULT_PROPERTY[index].type, CAMERA_DEFAULT_PROPERTY[index].writable, CAMERA_DEFAULT_PROPERTY[index].animatable, CAMERA_DEFAULT_PROPERTY[index].constraintInput, CAMERA_DEFAULT_PROPERTY[index].enumIndex, TEST_LOCATION); } END_TEST; } int UtcDaliCameraActorModelView(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor Test view application"); Actor actor = CreateRenderableActor(); actor.SetProperty(Actor::Property::SIZE, Vector2(100.0f, 100.0f)); actor.SetProperty(Actor::Property::POSITION, Vector3(20.0f, 30.0f, 40.0f)); actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); application.GetScene().Add(actor); application.SendNotification(); application.Render(0); application.Render(); application.SendNotification(); Matrix resultMatrix(true); resultMatrix.SetTransformComponents(Vector3::ONE, Quaternion::IDENTITY, actor.GetCurrentProperty<Vector3>(Actor::Property::POSITION)); RenderTask task = application.GetScene().GetRenderTaskList().GetTask(0); CameraActor cameraActor = task.GetCameraActor(); Matrix viewMatrix(false); cameraActor.GetProperty(CameraActor::Property::VIEW_MATRIX).Get(viewMatrix); Matrix::Multiply(resultMatrix, resultMatrix, viewMatrix); DALI_TEST_CHECK(application.GetGlAbstraction().CheckUniformValue("uModelView", resultMatrix)); END_TEST; } int UtcDaliCameraActorReadProjectionMatrix(void) { TestApplication application; tet_infoline("Testing Dali::CameraActor::ReadProjectionMatrix()"); CameraActor camera = application.GetScene().GetRenderTaskList().GetTask(0u).GetCameraActor(); application.SendNotification(); application.Render(0); application.Render(); application.SendNotification(); Texture image = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, 4u, 4u); Actor actor = CreateRenderableActor(image, RENDER_SHADOW_VERTEX_SOURCE, RENDER_SHADOW_FRAGMENT_SOURCE); actor.SetProperty(Actor::Property::SIZE, Vector2(100.0f, 100.0f)); application.GetScene().Add(actor); Matrix projectionMatrix; Matrix viewMatrix; camera.GetProperty(CameraActor::CameraActor::Property::PROJECTION_MATRIX).Get(projectionMatrix); camera.GetProperty(CameraActor::CameraActor::Property::VIEW_MATRIX).Get(viewMatrix); actor.RegisterProperty(SHADER_LIGHT_CAMERA_PROJECTION_MATRIX_PROPERTY_NAME, Matrix::IDENTITY); actor.RegisterProperty(SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME, Matrix::IDENTITY); Property::Index projectionMatrixPropertyIndex = actor.GetPropertyIndex(SHADER_LIGHT_CAMERA_PROJECTION_MATRIX_PROPERTY_NAME); Property::Index viewMatrixPropertyIndex = actor.GetPropertyIndex(SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME); Constraint projectionMatrixConstraint = Constraint::New<Dali::Matrix>(actor, projectionMatrixPropertyIndex, EqualToConstraint()); projectionMatrixConstraint.AddSource(Source(camera, CameraActor::Property::PROJECTION_MATRIX)); Constraint viewMatrixConstraint = Constraint::New<Dali::Matrix>(actor, viewMatrixPropertyIndex, EqualToConstraint()); viewMatrixConstraint.AddSource(Source(camera, CameraActor::Property::VIEW_MATRIX)); projectionMatrixConstraint.Apply(); viewMatrixConstraint.Apply(); application.SendNotification(); application.Render(); // Test effects of Constraint. DALI_TEST_CHECK(application.GetGlAbstraction().CheckUniformValue(SHADER_LIGHT_CAMERA_PROJECTION_MATRIX_PROPERTY_NAME.c_str(), projectionMatrix)); DALI_TEST_CHECK(application.GetGlAbstraction().CheckUniformValue(SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME.c_str(), viewMatrix)); END_TEST; } int UtcDaliCameraActorAnimatedProperties(void) { TestApplication application; tet_infoline("Testing Dali::Internal::CameraActor::GetSceneObjectAnimatableProperty()"); CameraActor camera = application.GetScene().GetRenderTaskList().GetTask(0u).GetCameraActor(); Actor actor = Actor::New(); actor.SetProperty(Actor::Property::SIZE, Vector2(100.0f, 100.0f)); application.GetScene().Add(actor); Constraint constraint = Constraint::New<Dali::Vector3>(actor, Actor::Property::POSITION, EqualToConstraint()); constraint.AddSource(Source(camera, Actor::Property::POSITION)); constraint.Apply(); camera.SetProperty(Actor::Property::POSITION, Vector3(100.0f, 200.0f, 300.0f)); application.SendNotification(); application.Render(); DALI_TEST_EQUALS(actor.GetCurrentProperty<Vector3>(Actor::Property::POSITION), Vector3(100.0f, 200.0f, 300.0f), TEST_LOCATION); END_TEST; } int UtcDaliCameraActorPropertyIndices(void) { TestApplication application; CameraActor camera = application.GetScene().GetRenderTaskList().GetTask(0u).GetCameraActor(); Actor basicActor = Actor::New(); Property::IndexContainer indices; camera.GetPropertyIndices(indices); DALI_TEST_CHECK(indices.Size() > basicActor.GetPropertyCount()); DALI_TEST_EQUALS(indices.Size(), camera.GetPropertyCount(), TEST_LOCATION); END_TEST; } int UtcDaliCameraActorCheckLookAtAndFreeLookViews01(void) { TestApplication application; Integration::Scene stage = application.GetScene(); Vector2 stageSize = stage.GetSize(); CameraActor freeLookCameraActor = CameraActor::New(stageSize); freeLookCameraActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); freeLookCameraActor.SetType(Camera::FREE_LOOK); Vector3 targetPosition(30.0f, 240.0f, -256.0f); Actor target = Actor::New(); target.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); target.SetProperty(Actor::Property::POSITION, targetPosition); Constraint cameraOrientationConstraint = Constraint::New<Quaternion>(freeLookCameraActor, Actor::Property::ORIENTATION, &LookAt); cameraOrientationConstraint.AddSource(Source(target, Actor::Property::WORLD_POSITION)); cameraOrientationConstraint.AddSource(Source(freeLookCameraActor, Actor::Property::WORLD_POSITION)); cameraOrientationConstraint.AddSource(Source(target, Actor::Property::WORLD_ORIENTATION)); cameraOrientationConstraint.Apply(); CameraActor lookAtCameraActor = CameraActor::New(stageSize); lookAtCameraActor.SetType(Camera::LOOK_AT_TARGET); lookAtCameraActor.SetTargetPosition(targetPosition); lookAtCameraActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); stage.Add(target); stage.Add(freeLookCameraActor); stage.Add(lookAtCameraActor); // Create an arbitrary vector for(float x = -1.0f; x <= 1.0f; x += 0.1f) { for(float y = -1.0f; y < 1.0f; y += 0.1f) { for(float z = -1.0f; z < 1.0f; z += 0.1f) { Vector3 position(x, y, z); position.Normalize(); position *= 200.0f; freeLookCameraActor.SetProperty(Actor::Property::POSITION, position); lookAtCameraActor.SetProperty(Actor::Property::POSITION, position); application.SendNotification(); application.Render(); application.SendNotification(); application.Render(); Matrix freeLookViewMatrix; Matrix lookAtViewMatrix; freeLookCameraActor.GetProperty(CameraActor::CameraActor::Property::VIEW_MATRIX).Get(freeLookViewMatrix); lookAtCameraActor.GetProperty(CameraActor::CameraActor::Property::VIEW_MATRIX).Get(lookAtViewMatrix); DALI_TEST_EQUALS(freeLookViewMatrix, lookAtViewMatrix, 0.01, TEST_LOCATION); } } } END_TEST; } int UtcDaliCameraActorCheckLookAtAndFreeLookViews02(void) { TestApplication application; Integration::Scene stage = application.GetScene(); Vector2 stageSize = stage.GetSize(); CameraActor freeLookCameraActor = CameraActor::New(stageSize); freeLookCameraActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); freeLookCameraActor.SetType(Camera::FREE_LOOK); Vector3 targetPosition(30.0f, 240.0f, -256.0f); Actor target = Actor::New(); target.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); target.SetProperty(Actor::Property::POSITION, targetPosition); Constraint cameraOrientationConstraint = Constraint::New<Quaternion>(freeLookCameraActor, Actor::Property::ORIENTATION, &LookAt); cameraOrientationConstraint.AddSource(Source(target, Actor::Property::WORLD_POSITION)); cameraOrientationConstraint.AddSource(Source(freeLookCameraActor, Actor::Property::WORLD_POSITION)); cameraOrientationConstraint.AddSource(Source(target, Actor::Property::WORLD_ORIENTATION)); cameraOrientationConstraint.Apply(); CameraActor lookAtCameraActor = CameraActor::New(stageSize); lookAtCameraActor.SetType(Camera::LOOK_AT_TARGET); lookAtCameraActor.SetTargetPosition(targetPosition); lookAtCameraActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); stage.Add(target); stage.Add(freeLookCameraActor); stage.Add(lookAtCameraActor); stage.GetRenderTaskList().GetTask(0).SetCameraActor(freeLookCameraActor); // Create an arbitrary vector for(float x = -1.0f; x <= 1.0f; x += 0.1f) { for(float y = -1.0f; y < 1.0f; y += 0.1f) { for(float z = -1.0f; z < 1.0f; z += 0.1f) { Vector3 position(x, y, z); position.Normalize(); position *= 200.0f; freeLookCameraActor.SetProperty(Actor::Property::POSITION, position); lookAtCameraActor.SetProperty(Actor::Property::POSITION, position); application.SendNotification(); application.Render(); application.SendNotification(); application.Render(); Matrix freeLookViewMatrix; freeLookCameraActor.GetProperty(CameraActor::CameraActor::Property::VIEW_MATRIX).Get(freeLookViewMatrix); Matrix freeLookWorld = freeLookCameraActor.GetCurrentProperty<Matrix>(Actor::Property::WORLD_MATRIX); Matrix freeLookTest(false); Matrix::Multiply(freeLookTest, freeLookViewMatrix, freeLookWorld); DALI_TEST_EQUALS(freeLookTest, Matrix::IDENTITY, 0.01f, TEST_LOCATION); } } } END_TEST; } int UtcDaliCameraActorCheckLookAtAndFreeLookViews03(void) { TestApplication application; Integration::Scene stage = application.GetScene(); Vector2 stageSize = stage.GetSize(); Vector3 targetPosition(Vector3::ZERO); Vector3 cameraOffset(0.0f, 0.0f, 100.0f); CameraActor freeLookCameraActor = CameraActor::New(stageSize); freeLookCameraActor.SetType(Camera::FREE_LOOK); freeLookCameraActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); Quaternion cameraOrientation(Radian(Degree(180.0f)), Vector3::YAXIS); freeLookCameraActor.SetProperty(Actor::Property::POSITION, cameraOffset); freeLookCameraActor.SetProperty(Actor::Property::ORIENTATION, cameraOrientation); Actor cameraAnchor = Actor::New(); cameraAnchor.Add(freeLookCameraActor); stage.Add(cameraAnchor); stage.GetRenderTaskList().GetTask(0).SetCameraActor(freeLookCameraActor); for(float angle = 1.0f; angle <= 180.0f; angle += 1.0f) { Quaternion rotation(Radian(Degree(angle)), Vector3::YAXIS); freeLookCameraActor.SetProperty(Actor::Property::POSITION, rotation.Rotate(cameraOffset)); cameraAnchor.SetProperty(Actor::Property::ORIENTATION, rotation); application.SendNotification(); application.Render(); application.SendNotification(); application.Render(); Matrix freeLookViewMatrix; freeLookCameraActor.GetProperty(CameraActor::CameraActor::Property::VIEW_MATRIX).Get(freeLookViewMatrix); Matrix freeLookWorld = freeLookCameraActor.GetCurrentProperty<Matrix>(Actor::Property::WORLD_MATRIX); Matrix freeLookTest(false); Matrix::Multiply(freeLookTest, freeLookViewMatrix, freeLookWorld); DALI_TEST_EQUALS(freeLookTest, Matrix::IDENTITY, 0.01f, TEST_LOCATION); } END_TEST; } int UtcDaliCameraActorReflectionByPlane(void) { TestApplication application; Integration::Scene stage = application.GetScene(); Vector3 targetPosition(Vector3::ZERO); Vector3 cameraOffset(0.0f, 100.0f, 100.0f); CameraActor freeLookCameraActor = stage.GetRenderTaskList().GetTask(0).GetCameraActor(); freeLookCameraActor.SetType(Camera::LOOK_AT_TARGET); freeLookCameraActor.SetTargetPosition(targetPosition); freeLookCameraActor.SetProperty(Actor::Property::POSITION, cameraOffset); stage.GetRootLayer().SetProperty(Actor::Property::POSITION, Vector2(1, 0)); application.SendNotification(); application.Render(); application.SendNotification(); application.Render(); Matrix matrixBefore, matrixAfter; freeLookCameraActor.GetProperty(CameraActor::CameraActor::Property::VIEW_MATRIX).Get(matrixBefore); freeLookCameraActor.SetProperty(Dali::DevelCameraActor::Property::REFLECTION_PLANE, Vector4(0.0f, 1.0f, 0.0f, 0.0f)); stage.GetRootLayer().SetProperty(Actor::Property::POSITION, Vector2(0, 0)); application.SendNotification(); application.Render(); application.SendNotification(); application.Render(); freeLookCameraActor.GetProperty(CameraActor::CameraActor::Property::VIEW_MATRIX).Get(matrixAfter); Vector3 position, scale; Quaternion rotation; matrixAfter.GetTransformComponents(position, rotation, scale); Quaternion reflected(0, 0, 1, 0); DALI_TEST_EQUALS(reflected, rotation, 0.01f, TEST_LOCATION); // Test Free Look camera freeLookCameraActor.SetType(Camera::FREE_LOOK); // Make sure the recalculation will take place freeLookCameraActor.SetProperty(Dali::DevelCameraActor::Property::REFLECTION_PLANE, Vector4(0.0f, 1.0f, 0.0f, 0.0f)); application.SendNotification(); application.Render(); application.SendNotification(); application.Render(); // Nothing should change despite of different camera type matrixAfter.GetTransformComponents(position, rotation, scale); DALI_TEST_EQUALS(reflected, rotation, 0.01f, TEST_LOCATION); END_TEST; } int UtcDaliCameraActorGetAspectRatioNegative(void) { TestApplication application; Dali::CameraActor instance; try { instance.GetAspectRatio(); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorGetFieldOfViewNegative(void) { TestApplication application; Dali::CameraActor instance; try { instance.GetFieldOfView(); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorGetInvertYAxisNegative(void) { TestApplication application; Dali::CameraActor instance; try { instance.GetInvertYAxis(); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorSetAspectRatioNegative(void) { TestApplication application; Dali::CameraActor instance; try { float arg1(0.0f); instance.SetAspectRatio(arg1); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorSetFieldOfViewNegative(void) { TestApplication application; Dali::CameraActor instance; try { float arg1(0.0f); instance.SetFieldOfView(arg1); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorSetInvertYAxisNegative(void) { TestApplication application; Dali::CameraActor instance; try { bool arg1(false); instance.SetInvertYAxis(arg1); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorSetProjectionModeNegative(void) { TestApplication application; Dali::CameraActor instance; try { Dali::Camera::ProjectionMode arg1(Camera::PERSPECTIVE_PROJECTION); instance.SetProjectionMode(arg1); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorSetTargetPositionNegative(void) { TestApplication application; Dali::CameraActor instance; try { Dali::Vector3 arg1; instance.SetTargetPosition(arg1); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorGetFarClippingPlaneNegative(void) { TestApplication application; Dali::CameraActor instance; try { instance.GetFarClippingPlane(); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorSetFarClippingPlaneNegative(void) { TestApplication application; Dali::CameraActor instance; try { float arg1(0.0f); instance.SetFarClippingPlane(arg1); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorGetNearClippingPlaneNegative(void) { TestApplication application; Dali::CameraActor instance; try { instance.GetNearClippingPlane(); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorSetNearClippingPlaneNegative(void) { TestApplication application; Dali::CameraActor instance; try { float arg1(0.0f); instance.SetNearClippingPlane(arg1); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorSetPerspectiveProjectionNegative(void) { TestApplication application; Dali::CameraActor instance; try { Dali::Vector2 arg1; instance.SetPerspectiveProjection(arg1); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorSetOrthographicProjectionNegative01(void) { TestApplication application; Dali::CameraActor instance; try { float arg1(0.0f); float arg2(0.0f); float arg3(0.0f); float arg4(0.0f); float arg5(0.0f); float arg6(0.0f); instance.SetOrthographicProjection(arg1, arg2, arg3, arg4, arg5, arg6); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorSetOrthographicProjectionNegative02(void) { TestApplication application; Dali::CameraActor instance; try { Dali::Vector2 arg1; instance.SetOrthographicProjection(arg1); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorSetTypeNegative(void) { TestApplication application; Dali::CameraActor instance; try { Dali::Camera::Type arg1(Camera::FREE_LOOK); instance.SetType(arg1); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorGetProjectionModeNegative(void) { TestApplication application; Dali::CameraActor instance; try { instance.GetProjectionMode(); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorGetTargetPositionNegative(void) { TestApplication application; Dali::CameraActor instance; try { instance.GetTargetPosition(); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; } int UtcDaliCameraActorGetTypeNegative(void) { TestApplication application; Dali::CameraActor instance; try { instance.GetType(); DALI_TEST_CHECK(false); // Should not get here } catch(...) { DALI_TEST_CHECK(true); // We expect an assert } END_TEST; }
35.976426
180
0.755091
Coquinho
33533c34088ba4131af99f6493e0c7c67909292b
25,711
cc
C++
self_test/poisson/tree_rotation_tests/tree_3d.cc
PuneetMatharu/oomph-lib
edd590cbb4f3ef9940b9738f18275ea2fb828c55
[ "RSA-MD" ]
null
null
null
self_test/poisson/tree_rotation_tests/tree_3d.cc
PuneetMatharu/oomph-lib
edd590cbb4f3ef9940b9738f18275ea2fb828c55
[ "RSA-MD" ]
1
2022-03-23T16:16:41.000Z
2022-03-23T16:16:41.000Z
self_test/poisson/tree_rotation_tests/tree_3d.cc
PuneetMatharu/oomph-lib
edd590cbb4f3ef9940b9738f18275ea2fb828c55
[ "RSA-MD" ]
null
null
null
//LIC// ==================================================================== //LIC// This file forms part of oomph-lib, the object-oriented, //LIC// multi-physics finite-element library, available //LIC// at http://www.oomph-lib.org. //LIC// //LIC// Copyright (C) 2006-2022 Matthias Heil and Andrew Hazel //LIC// //LIC// This library is free software; you can redistribute it and/or //LIC// modify it under the terms of the GNU Lesser General Public //LIC// License as published by the Free Software Foundation; either //LIC// version 2.1 of the License, or (at your option) any later version. //LIC// //LIC// This library is distributed in the hope that it will be useful, //LIC// but WITHOUT ANY WARRANTY; without even the implied warranty of //LIC// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //LIC// Lesser General Public License for more details. //LIC// //LIC// You should have received a copy of the GNU Lesser General Public //LIC// License along with this library; if not, write to the Free Software //LIC// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA //LIC// 02110-1301 USA. //LIC// //LIC// The authors may be contacted at oomph-lib@maths.man.ac.uk. //LIC// //LIC//==================================================================== //Driver for a simple 2D poisson problem with adaptive mesh refinement #include <typeinfo> //Generic routines #include "generic.h" // The Poisson equations #include "poisson.h" // The mesh #include "meshes/simple_cubic_mesh.h" using namespace oomph; using namespace std; //================================================================ /// Class for sorting the elements into lexicographic order based /// on the coordinate at the centre of the element. This is the only /// "rational" way to preserve the ordering given rotations of the elements. //================================================================ template<class ELEMENT> class CompareElementCoordinate { public: /// The actual comparison operator int operator() (GeneralisedElement* const &element1_pt, GeneralisedElement* const &element2_pt) { //Dynamic cast the elements ELEMENT* cast_element1_pt = dynamic_cast<ELEMENT*>(element1_pt); ELEMENT* cast_element2_pt = dynamic_cast<ELEMENT*>(element2_pt); //Check that we managed to successfully cast the elements #ifdef PARANOID if (cast_element1_pt==0) { std::ostringstream error_message; error_message << "Failed to cast element1_pt to an ELEMENT" << std::endl; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } if (cast_element2_pt==0) { std::ostringstream error_message; error_message << "Failed to cast element2_pt to an ELEMENT" << std::endl; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif //Find the dimension of the element unsigned dim = cast_element1_pt->dim(); //Check that the dimensions of bothelements are the same { unsigned dim2 = cast_element2_pt->dim(); if(dim != dim2) { std::ostringstream warn_message; warn_message << "Warning: Two elements do not have the same dimension" << dim << " and " << dim2 << ". They cannot be compared\n"; OomphLibWarning(warn_message.str(), "CompareElementCoordinate::()", OOMPH_EXCEPTION_LOCATION); } } //Find the positions of the centres of the elements Vector<double> x1(dim), x2(dim); //Not general, only works for quads or octs (centre 0,0,0) Vector<double> s(dim,0.0); cast_element1_pt->interpolated_x(s,x1); cast_element2_pt->interpolated_x(s,x2); //This is the Stroustrup-approved way to do lexicographical ordering //Loop over the components until they are not equal //to within a given tolerance { unsigned i=0; double tol = 1.0e-14; while(i!=dim && (std::abs(x1[i]-x2[i]) < tol)){ ++i;} //If we've reached the end, the coordinates are equal, return false if(i==dim) {return 0;} //Otherwise, return the ordering on the final component return x1[i] < x2[i]; } } }; //============================================================= /// Class the overloaded RefineablePoissonElements so that the /// elements that can be rotated about their centre //============================================================= template<class ELEMENT> class Rotateable : public ELEMENT { private: /// Integer to store the rotation angle unsigned Rotated; public: /// Constructor, initialise rotation to NULL (default) Rotateable() : RefineableElement(), ELEMENT(), Rotated(0) { } /// Overload the further build function to pass the rotate information /// to the sons void further_build() { ELEMENT::further_build(); this->Rotated = dynamic_cast<Rotateable<ELEMENT>*> (this->father_element_pt())->Rotated; } /// Rotate the element by a given angle: /// 0 (0), 1(90 degrees), 2(180 degrees), 3 (270 degrees) void rotate(const unsigned &angle) { Rotated = angle; //Get the nodes and make a copy unsigned n_node = this->nnode(); Vector<Node*> elemental_nodes_pt(n_node); for(unsigned n=0;n<n_node;n++) { elemental_nodes_pt[n] = this->node_pt(n); } //Face rotation four possibilities unsigned face_rot = angle%4; //We now merely permute the nodes unsigned n_p = this->nnode_1d(); //The permutation depends on the angle switch(face_rot) { //FIRST WE JUST ROTATE ABOUT THE Z-AXIS //No permutation case 0: break; //Rotation by 90 degrees (i and j are swapped and i is reversed) case 1: for(unsigned i=0;i<n_p;i++) { for(unsigned j=0;j<n_p;j++) { for(unsigned k=0;k<n_p;k++) { this->node_pt(i + j*n_p + k*n_p*n_p) = elemental_nodes_pt[j + n_p*(n_p-1-i) + k*n_p*n_p]; } } } break; //Rotation by 180 degrees (i and j are reversed) case 2: for(unsigned i=0;i<n_p;i++) { for(unsigned j=0;j<n_p;j++) { for(unsigned k=0;k<n_p;k++) { this->node_pt(i + j*n_p + k*n_p*n_p) = elemental_nodes_pt[(n_p-1-i) + n_p*(n_p-1-j) + k*n_p*n_p]; } } } break; //Rotation by 270 degrees (i and j are swapped and j is reversed) case 3: for(unsigned i=0;i<n_p;i++) { for(unsigned j=0;j<n_p;j++) { for(unsigned k=0;k<n_p;k++) { this->node_pt(i + j*n_p + k*n_p*n_p) = elemental_nodes_pt[(n_p-1-j) + n_p*i + k*n_p*n_p]; } } } break; } //Now get the nodes again, after the first rotation for(unsigned n=0;n<n_node;n++) { elemental_nodes_pt[n] = this->node_pt(n); } //We now perform the second rotation to move the face into position unsigned body_rot = angle/4; switch(body_rot) { //No permutation case 0: break; //ROTATE ABOUT X-AXIS //Rotation by 90 degrees (k and j are swapped and k is reversed) case 1: for(unsigned i=0;i<n_p;i++) { for(unsigned j=0;j<n_p;j++) { for(unsigned k=0;k<n_p;k++) { this->node_pt(i + j*n_p + k*n_p*n_p) = elemental_nodes_pt[i + n_p*(n_p-1-k) + j*n_p*n_p]; } } } break; //Rotation by 180 degrees (k and j are reversed) case 2: for(unsigned i=0;i<n_p;i++) { for(unsigned j=0;j<n_p;j++) { for(unsigned k=0;k<n_p;k++) { this->node_pt(i + j*n_p + k*n_p*n_p) = elemental_nodes_pt[i + n_p*(n_p-1-j) + (n_p-1-k)*n_p*n_p]; } } } break; //Rotation by 270 degrees (k and j are swapped and j is reversed) case 3: for(unsigned i=0;i<n_p;i++) { for(unsigned j=0;j<n_p;j++) { for(unsigned k=0;k<n_p;k++) { this->node_pt(i + j*n_p + k*n_p*n_p) = elemental_nodes_pt[i + n_p*k + (n_p-1-j)*n_p*n_p]; } } } break; //ROTATE ABOUT Y-AXIS //Rotation by 90 degrees (i and k are swapped and i is reversed) case 4: for(unsigned i=0;i<n_p;i++) { for(unsigned j=0;j<n_p;j++) { for(unsigned k=0;k<n_p;k++) { this->node_pt(i + j*n_p + k*n_p*n_p) = elemental_nodes_pt[k + n_p*j + (n_p-1-i)*n_p*n_p]; } } } break; //Rotation by 270 degrees (i and k are swapped and k is reversed) case 5: for(unsigned i=0;i<n_p;i++) { for(unsigned j=0;j<n_p;j++) { for(unsigned k=0;k<n_p;k++) { this->node_pt(i + j*n_p + k*n_p*n_p) = elemental_nodes_pt[(n_p-1-k) + n_p*j + i*n_p*n_p]; } } } break; } } /// Rotate the local coordinates so that that output is /// will be consistent, irrespective of the rotation of the element void rotate_local_coordinates(Vector<double> &s) { //Now rotate about the face Vector<double> s_rot(3); unsigned face_rot = Rotated%4; switch(face_rot) { case 0: s_rot[0] = s[0]; s_rot[1] = s[1]; s_rot[2] = s[2]; break; case 1: s_rot[0] = -s[1]; s_rot[1] = s[0]; s_rot[2] = s[2]; break; case 2: s_rot[0] = -s[0]; s_rot[1] = -s[1]; s_rot[2] = s[2]; break; case 3: s_rot[0] = s[1]; s_rot[1] = -s[0]; s_rot[2] = s[2]; break; } //Rotate the face into position unsigned body_rot = Rotated/4; Vector<double> s_rot2(3); switch(body_rot) { case 0: s_rot2[0] = s_rot[0]; s_rot2[1] = s_rot[1]; s_rot2[2] = s_rot[2]; break; case 1: s_rot2[0] = s_rot[0]; s_rot2[1] = s_rot[2]; s_rot2[2] = -s_rot[1]; break; case 2: s_rot2[0] = s_rot[0]; s_rot2[1] = -s_rot[1]; s_rot2[2] = -s_rot[2]; break; case 3: s_rot2[0] = s_rot[0]; s_rot2[1] = -s_rot[2]; s_rot2[2] = s_rot[1]; break; case 4: s_rot2[0] = -s_rot[2]; s_rot2[1] = s_rot[1]; s_rot2[2] = s_rot[0]; break; case 5: s_rot2[0] = s_rot[2]; s_rot2[1] = s_rot[1]; s_rot2[2] = -s_rot[0]; break; } //Set the input to the rotated coordinate s[0] = s_rot2[0]; s[1] = s_rot2[1]; s[2] = s_rot2[2]; } /// Output function overloaded to produce identical output /// under rotation void output(std::ostream &outfile, const unsigned &nplot) { //Vector of local coordinates Vector<double> s(3); // Tecplot header info outfile << this->tecplot_zone_string(nplot); // Loop over plot points unsigned num_plot_points = this->nplot_points(nplot); for (unsigned iplot=0;iplot<num_plot_points;iplot++) { // Get local coordinates of plot point this->get_s_plot(iplot,nplot,s); //Rotate the local coordinates this->rotate_local_coordinates(s); //Print the output for(unsigned i=0;i<3;i++) { outfile << this->interpolated_x(s,i) << " "; } outfile << this->interpolated_u_poisson(s) << std::endl; } // Write tecplot footer (e.g. FE connectivity lists) this->write_tecplot_zone_footer(outfile,nplot); } /// Output exact solution: Overloaded to produce identical /// output under rotation void output_fct(std::ostream &outfile, const unsigned &nplot, FiniteElement::SteadyExactSolutionFctPt exact_soln_pt) { //Vector of local coordinates Vector<double> s(3); // Vector for coordintes Vector<double> x(3); // Tecplot header info outfile << this->tecplot_zone_string(nplot); // Exact solution Vector (here a scalar) Vector<double> exact_soln(1); // Loop over plot points unsigned num_plot_points = this->nplot_points(nplot); for (unsigned iplot=0;iplot<num_plot_points;iplot++) { // Get local coordinates of plot point this->get_s_plot(iplot,nplot,s); //Rotate the local coordinates this->rotate_local_coordinates(s); // Get x position as Vector this->interpolated_x(s,x); // Get exact solution at this point (*exact_soln_pt)(x,exact_soln); //Output x,y,...,u_exact for(unsigned i=0;i<3;i++) { outfile << x[i] << " "; } outfile << exact_soln[0] << std::endl; } // Write tecplot footer (e.g. FE connectivity lists) this->write_tecplot_zone_footer(outfile,nplot); } /// Error computation stuff /// Overloaded to be identical under rotation void compute_error(std::ostream &outfile, FiniteElement::SteadyExactSolutionFctPt exact_soln_pt, double& error, double& norm) { // Initialise error=0.0; norm=0.0; //Vector of local coordinates Vector<double> s(3); // Vector for coordintes Vector<double> x(3); //Find out how many nodes there are in the element unsigned n_node = this->nnode(); Shape psi(n_node); //Set the value of n_intpt unsigned n_intpt = this->integral_pt()->nweight(); // Tecplot outfile << "ZONE" << std::endl; // Exact solution Vector (here a scalar) Vector<double> exact_soln(1); //Loop over the integration points for(unsigned ipt=0;ipt<n_intpt;ipt++) { //Assign values of s for(unsigned i=0;i<3;i++) { s[i] = this->integral_pt()->knot(ipt,i); } //Rotate the local coordinates this->rotate_local_coordinates(s); //Get the integral weight double w = this->integral_pt()->weight(ipt); // Get jacobian of mapping double J = this->J_eulerian(s); //Premultiply the weights and the Jacobian double W = w*J; // Get x position as Vector this->interpolated_x(s,x); // Get FE function value double u_fe = this->interpolated_u_poisson(s); // Get exact solution at this point (*exact_soln_pt)(x,exact_soln); //Output x,y,...,error for(unsigned i=0;i<3;i++) { outfile << x[i] << " "; } outfile << exact_soln[0] << " " << exact_soln[0]-u_fe << std::endl; // Add to error and norm norm+=exact_soln[0]*exact_soln[0]*W; error+=(exact_soln[0]-u_fe)*(exact_soln[0]-u_fe)*W; } } }; //==============================start_of_mesh====================== /// Refineable equivalent of the SimpleRectangularQuadMesh. /// Refinement is performed by the QuadTree-based procedures /// implemented in the RefineableQuadMesh base class. /// The base mesh is 3x3 and of size 1x1. We can then rotate /// the middle element to produce all possible variations of rotated /// QuadTrees. //================================================================= template<class ELEMENT> class TestRefineableCubicMesh : public virtual SimpleCubicMesh<ELEMENT>, public RefineableBrickMesh<ELEMENT> { public: /// Pass the angle of rotation and the timestepper to /// the Mesh. TestRefineableCubicMesh(const unsigned &angle, TimeStepper* time_stepper_pt= &Mesh::Default_TimeStepper) : SimpleCubicMesh<ELEMENT>(3,3,3,1.0,1.0,1.0,time_stepper_pt) { //To Check rotations, we shall rotate the central element dynamic_cast<ELEMENT*>(this->finite_element_pt(13))->rotate(angle); // Nodal positions etc. were created in constructor for // SimpleRectangularQuadMesh<...> --> We only need to set up // adaptivity information: Associate finite elements with their // QuadTrees and plant them in a QuadTreeForest: this->setup_octree_forest(); } // end of constructor /// Sort the elements into lexographical order void sort_elements() { std::sort(this->element_pt().begin(),this->element_pt().end(), CompareElementCoordinate<ELEMENT>()); } /// Destructor: Empty -- all cleanup gets handled in the base /// classes virtual ~TestRefineableCubicMesh() {} }; // end of mesh //=============start_of_namespace===================================== /// Namespace for exact solution for Poisson equation with sharp step //==================================================================== namespace TanhSolnForPoisson { /// Parameter for steepness of step double Alpha=50.0; /// Orientation (non-normalised x-component of unit vector in direction /// of step plane) double N_x=-1.0; /// Orientation (non-normalised y-component of unit vector in direction /// of step plane) double N_y=-1.0; /// Orientation (non-normalised z-component of unit vector in direction /// of step plane) double N_z=1.0; /// Orientation (x-coordinate of step plane) double X_0=0.0; /// Orientation (y-coordinate of step plane) double Y_0=0.0; /// Orientation (z-coordinate of step plane) double Z_0=0.0; // Exact solution as a Vector void get_exact_u(const Vector<double>& x, Vector<double>& u) { u[0] = tanh(Alpha*((x[0]-X_0)*N_x/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[1]-Y_0)* N_y/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[2]-Z_0)* N_z/sqrt(N_x*N_x+N_y*N_y+N_z*N_z))); } /// Exact solution as a scalar void get_exact_u(const Vector<double>& x, double& u) { u = tanh(Alpha*((x[0]-X_0)*N_x/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[1]-Y_0)* N_y/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[2]-Z_0)* N_z/sqrt(N_x*N_x+N_y*N_y+N_z*N_z))); } /// Source function to make it an exact solution void get_source(const Vector<double>& x, double& source) { double s1,s2,s3,s4; s1 = -2.0*tanh(Alpha*((x[0]-X_0)*N_x/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[1]- Y_0)*N_y/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[2]-Z_0)*N_z/sqrt(N_x*N_x+N_y*N_y+N_z* N_z)))*(1.0-pow(tanh(Alpha*((x[0]-X_0)*N_x/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[1]- Y_0)*N_y/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[2]-Z_0)*N_z/sqrt(N_x*N_x+N_y*N_y+N_z* N_z))),2.0))*Alpha*Alpha*N_x*N_x/(N_x*N_x+N_y*N_y+N_z*N_z); s3 = -2.0*tanh(Alpha*((x[0]-X_0)*N_x/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[1]- Y_0)*N_y/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[2]-Z_0)*N_z/sqrt(N_x*N_x+N_y*N_y+N_z* N_z)))*(1.0-pow(tanh(Alpha*((x[0]-X_0)*N_x/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[1]- Y_0)*N_y/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[2]-Z_0)*N_z/sqrt(N_x*N_x+N_y*N_y+N_z* N_z))),2.0))*Alpha*Alpha*N_y*N_y/(N_x*N_x+N_y*N_y+N_z*N_z); s4 = -2.0*tanh(Alpha*((x[0]-X_0)*N_x/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[1]- Y_0)*N_y/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[2]-Z_0)*N_z/sqrt(N_x*N_x+N_y*N_y+N_z* N_z)))*(1.0-pow(tanh(Alpha*((x[0]-X_0)*N_x/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[1]- Y_0)*N_y/sqrt(N_x*N_x+N_y*N_y+N_z*N_z)+(x[2]-Z_0)*N_z/sqrt(N_x*N_x+N_y*N_y+N_z* N_z))),2.0))*Alpha*Alpha*N_z*N_z/(N_x*N_x+N_y*N_y+N_z*N_z); s2 = s3+s4; source = s1+s2; } } // end of namespace /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// //=======start_of_class_definition==================================== /// Poisson problem in refineable eighth of a sphere mesh. //==================================================================== template<class ELEMENT> class TestPoissonProblem : public Problem { public: /// Constructor: Pass pointer to source function TestPoissonProblem(const unsigned &angle, PoissonEquations<3>::PoissonSourceFctPt source_fct_pt); /// Destructor: Empty ~TestPoissonProblem(){} /// Overload generic access function by one that returns /// a pointer to the specific mesh TestRefineableCubicMesh<ELEMENT>* mesh_pt() { return dynamic_cast<TestRefineableCubicMesh<ELEMENT>*>(Problem::mesh_pt()); } /// Update the problem specs after solve (empty) void actions_after_newton_solve() {} /// Update the problem specs before solve: /// Set Dirchlet boundary conditions from exact solution. void actions_before_newton_solve() { //Loop over the boundaries unsigned num_bound = mesh_pt()->nboundary(); for(unsigned ibound=0;ibound<num_bound;ibound++) { // Loop over the nodes on boundary unsigned num_nod=mesh_pt()->nboundary_node(ibound); for (unsigned inod=0;inod<num_nod;inod++) { Node* nod_pt=mesh_pt()->boundary_node_pt(ibound,inod); double u; Vector<double> x(3); x[0]=nod_pt->x(0); x[1]=nod_pt->x(1); x[2]=nod_pt->x(2); TanhSolnForPoisson::get_exact_u(x,u); nod_pt->set_value(0,u); } } } /// Doc the solution void doc_solution(DocInfo& doc_info); private: /// Pointer to source function PoissonEquations<3>::PoissonSourceFctPt Source_fct_pt; }; // end of class definition //====================start_of_constructor================================ /// Constructor for Poisson problem on eighth of a sphere mesh //======================================================================== template<class ELEMENT> TestPoissonProblem<ELEMENT>::TestPoissonProblem(const unsigned &angle, PoissonEquations<2>::PoissonSourceFctPt source_fct_pt) : Source_fct_pt(source_fct_pt) { //Create the mesh Problem::mesh_pt() = new TestRefineableCubicMesh<ELEMENT>(angle); // Set error estimator Z2ErrorEstimator* error_estimator_pt=new Z2ErrorEstimator; mesh_pt()->spatial_error_estimator_pt()=error_estimator_pt; //Default parmaters mesh_pt()->max_permitted_error()=0.01; mesh_pt()->min_permitted_error()=0.001; //Doc the mesh boundaries //ofstream some_file; //some_file.open("boundaries.dat"); //mesh_pt()->output_boundaries(some_file); //some_file.close(); // Set the boundary conditions for this problem: All nodes are // free by default -- just pin the ones that have Dirichlet conditions // here (all the nodes on the boundary) unsigned num_bound = mesh_pt()->nboundary(); for(unsigned ibound=0;ibound<num_bound;ibound++) { unsigned num_nod= mesh_pt()->nboundary_node(ibound); for (unsigned inod=0;inod<num_nod;inod++) { mesh_pt()->boundary_node_pt(ibound,inod)->pin(0); } } // end of pinning //Find number of elements in mesh unsigned n_element = mesh_pt()->nelement(); // Loop over the elements to set up element-specific // things that cannot be handled by constructor for(unsigned i=0;i<n_element;i++) { // Upcast from FiniteElement to the present element ELEMENT *el_pt = dynamic_cast<ELEMENT*>(mesh_pt()->element_pt(i)); //Set the source function pointer el_pt->source_fct_pt() = Source_fct_pt; } //Manually adapt the mesh to our solution Vector<unsigned> to_be_refined(10); to_be_refined[0] = 0; to_be_refined[1] = 1; to_be_refined[2] = 3; to_be_refined[3] = 9; to_be_refined[4] = 10; to_be_refined[5] = 12; to_be_refined[6] = 13; to_be_refined[7] = 18; to_be_refined[8] = 22; to_be_refined[9] = 26; mesh_pt()->refine_selected_elements(to_be_refined); // Setup equation numbering cout <<"Number of equations: " << assign_eqn_numbers() << std::endl; } // end of constructor //========================start_of_doc==================================== /// Doc the solution //======================================================================== template<class ELEMENT> void TestPoissonProblem<ELEMENT>::doc_solution(DocInfo& doc_info) { ofstream some_file; char filename[100]; // Number of plot points unsigned npts; npts=5; // Output solution //----------------- mesh_pt()->sort_elements(); sprintf(filename,"%s/soln%i.dat",doc_info.directory().c_str(), doc_info.number()); some_file.open(filename); mesh_pt()->output(some_file,npts); some_file.close(); // Output exact solution //---------------------- // sprintf(filename,"%s/exact_soln%i.dat",doc_info.directory().c_str(), // doc_info.number()); // some_file.open(filename); // mesh_pt()->output_fct(some_file,npts,TanhSolnForPoisson::get_exact_u); // some_file.close(); // // Doc error // //---------- // double error,norm; // sprintf(filename,"%s/error%i.dat",doc_info.directory().c_str(), // doc_info.number()); // some_file.open(filename); // mesh_pt()->compute_error(some_file,TanhSolnForPoisson::get_exact_u, // error,norm); // some_file.close(); // cout << "error: " << sqrt(error) << std::endl; // cout << "norm : " << sqrt(norm) << std::endl << std::endl; } // end of doc /// Global function that is used to run the rotation tests for /// different elements template<class ELEMENT> void run_test(const unsigned &i) { char dirname[100]; sprintf(dirname,"RESLT%i",i); // Create label for output //------------------------ DocInfo doc_info; // Set output directory doc_info.set_directory(dirname); // Step number doc_info.number()=0; //Set up the problem //------------------ for(unsigned i=0;i<24;i++) { //Create the problem with rotation i TestPoissonProblem<ELEMENT> problem(i,&TanhSolnForPoisson::get_source); // Solve the problem, performing up to 2 adaptive refinements problem.newton_solve(); //Output the solution problem.doc_solution(doc_info); doc_info.number()++; } } //===== start_of_main===================================================== /// Driver code for 2D Poisson problem //======================================================================== int main() { run_test<Rotateable<RefineableQPoissonElement<3,2> > >(1); run_test<Rotateable<RefineableQPoissonElement<3,3> > >(2); run_test<Rotateable<RefineableQSpectralPoissonElement<3,4> > >(3); } //end of main
28.007625
79
0.598071
PuneetMatharu
3353cb6ede5da5fd87ab26a7495727020406705d
2,162
cpp
C++
CsWeapon/Source/CsWp/Public/Projectile/Data/CsLibrary_Data_ProjectileWeapon.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsWeapon/Source/CsWp/Public/Projectile/Data/CsLibrary_Data_ProjectileWeapon.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsWeapon/Source/CsWp/Public/Projectile/Data/CsLibrary_Data_ProjectileWeapon.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved. #include "Projectile/Data/CsLibrary_Data_ProjectileWeapon.h" #include "CsWp.h" // Library #include "Library/CsLibrary_Valid.h" // Data #include "Projectile/Data/CsData_ProjectileWeapon.h" namespace NCsWeapon { namespace NProjectile { namespace NData { #define DataType NCsWeapon::NProjectile::NData::IData bool FLibrary::IsValidChecked(const FString& Context, const DataType* Data) { // Check Data is Valid CS_IS_PTR_NULL_CHECKED(Data) // Check MaxAmmo is a valid value if (!Data->HasInfiniteAmmo()) { CS_IS_INT_GREATER_THAN_CHECKED(Data->GetMaxAmmo(), 0) } // Check TimeBetweenShots > 0.0f CS_IS_FLOAT_GREATER_THAN_CHECKED(Data->GetTimeBetweenShots(), 0.0f) // Check ProjectilesPerShot >= 1 CS_IS_INT_GREATER_THAN_OR_EQUAL_CHECKED(Data->GetProjectilesPerShot(), 1) // Check TimeBetweenProjectilesPerShot is valid when ProjectilesPerShot > 1 if (Data->GetProjectilesPerShot() > 1) { checkf(Data->GetTimeBetweenProjectilesPerShot() > 0.0f, TEXT("%s: TimeBetweenProjectilesPerShot must be > 0.0f when ProjectilesPerShot > 1."), *Context); } return true; } bool FLibrary::IsValid(const FString& Context, const DataType* Data, void(*Log)(const FString&) /*=&NCsWeapon::FLog::Warning*/) { // Check Data is Valid CS_IS_PTR_NULL(Data) // Check MaxAmmo is a valid value if (!Data->HasInfiniteAmmo()) { CS_IS_INT_GREATER_THAN(Data->GetMaxAmmo(), 0) } // Check TimeBetweenShots > 0.0f CS_IS_FLOAT_GREATER_THAN(Data->GetTimeBetweenShots(), 0.0f) // Check ProjectilesPerShot >= 1 CS_IS_INT_GREATER_THAN_OR_EQUAL(Data->GetProjectilesPerShot(), 1) // Check TimeBetweenProjectilesPerShot is valid when ProjectilesPerShot > 1 if (Data->GetProjectilesPerShot() > 1) { if (Data->GetTimeBetweenProjectilesPerShot() <= 0.0f) { CS_CONDITIONAL_LOG(FString::Printf(TEXT("%s: TimeBetweenProjectilesPerShot must be > 0.0f when ProjectilesPerShot > 1."), *Context)); return false; } } return true; } #undef DataType } } }
32.268657
158
0.703515
closedsum
335429359dac1d5601556f4550f4270b20170e8a
10,227
cpp
C++
src/linux_platform.cpp
glitchheart/glitchheartengine
7adf14475f8feb6239e12a9ce2cfd9c005592443
[ "MIT" ]
3
2019-07-11T18:16:48.000Z
2019-07-18T11:53:34.000Z
src/linux_platform.cpp
glitchheart/glitchheartengine
7adf14475f8feb6239e12a9ce2cfd9c005592443
[ "MIT" ]
5
2019-07-19T07:16:53.000Z
2019-08-16T07:23:47.000Z
src/linux_platform.cpp
glitchheart/glitchheartengine
7adf14475f8feb6239e12a9ce2cfd9c005592443
[ "MIT" ]
null
null
null
#include <time.h> #include <errno.h> #include <sys/sendfile.h> #include <sys/mman.h> #include "unistd.h" #include <dirent.h> #include "dlfcn.h" #include "linux_threading.cpp" struct PlatformHandle { i32 handle; }; inline PLATFORM_FILE_EXISTS(linux_file_exists) { struct stat buffer; return (stat(file_path,&buffer) == 0); } inline PLATFORM_CREATE_DIRECTORY(linux_create_directory) { i32 result = mkdir(path, S_IRWXU); if(!result) { return false; } return true; } static b32 copy_file(const char* src, const char* dst, b32 dont_overwrite, MemoryArena* arena = nullptr, b32 binary = true) { FILE* in; FILE* out; if(linux_file_exists(dst) && dont_overwrite) { return false; } if(binary) { in = fopen(src, "rb"); } else { in = fopen(src, "r"); } if(in == NULL) { printf("Failed in\n"); printf("Src: %s\n", src); printf("Dst: %s\n", dst); return false; } if(binary) { out = fopen(dst, "wb"); } else { out = fopen(dst, "w"); } if(out == NULL) { fclose(in); printf("Failed out\n"); return false; } size_t n,m; unsigned char buff[8192]; do { n = fread(buff, 1, sizeof(buff), in); if(n) { m = fwrite(buff, 1, n, out); } else { m = 0; } } while ((n > 0) && (n == m)); if(m) { printf("COPY\n"); } fclose(out); fclose(in); if(binary) { // auto temp_mem = begin_temporary_memory(arena); // system(concat("chmod +xr ", dst, arena)); // end_temporary_memory(temp_mem); } return true; } static time_t get_last_write_time(const char* file_path) { struct stat result; if(stat(file_path, &result) == 0) { auto mod_time = result.st_mtime; return mod_time; } return 0; } // @Incomplete(Niels): Flags? PLATFORM_LOAD_LIBRARY(linux_load_library) { return dlopen(path, RTLD_LAZY); } PLATFORM_FREE_LIBRARY(linux_free_library) { dlclose(library); } PLATFORM_LOAD_SYMBOL(linux_load_symbol) { return dlsym(library, symbol); } PLATFORM_ALLOCATE_MEMORY(linux_allocate_memory) { #if defined(__i386__) assert(sizeof(MemoryBlock) == 56); #elif defined(__x86_64__) assert(sizeof(MemoryBlock) == 72); #endif umm page_size = 4096; //TODO: Not really always correct? umm total_size = size + sizeof(MemoryBlock); umm base_offset = sizeof(MemoryBlock); umm protect_offset = 0; if(flags & PM_UNDERFLOW_CHECK) { total_size = size + 2 * page_size; base_offset = 2 * page_size; protect_offset = page_size; } if(flags & PM_OVERFLOW_CHECK) { umm size_rounded_up = align_pow2(size, page_size); total_size = size_rounded_up + 2 * page_size; base_offset = page_size + size_rounded_up - size; protect_offset = page_size + size_rounded_up; } MemoryBlock* block = (MemoryBlock*)mmap(0, total_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); //memset(block, 0, total_size); assert(block); block->block.base = (u8*)block + base_offset; assert(block->block.used == 0); assert(block->block.prev == 0); // if(Flags & (PM_UnderflowCheck | PM_OverflowCheck)) // { // i32 Protected = mprotect((u8*)Block + ProtectOffset, PageSize, PROT_NONE); // assert(Protected); // } block->block.size = size; block->block.flags = flags; PlatformMemoryBlock* plat_block = &block->block; memory_state.blocks++; memory_state.size_allocated += total_size; return plat_block; } PLATFORM_DEALLOCATE_MEMORY(linux_deallocate_memory) { if(block) { memory_state.blocks--; memory_state.size_allocated -= (block->size + sizeof(MemoryBlock)); MemoryBlock *new_block = ((MemoryBlock*)block); munmap(new_block, block->size + sizeof(MemoryBlock)); } } static PLATFORM_OPEN_FILE(linux_open_file) { PlatformFile result = {}; result.handle = -1; auto flags = 0; if((open_flags & (POF_READ | POF_WRITE)) == (POF_READ | POF_WRITE)) { flags = O_RDWR; } else if(open_flags & POF_WRITE) { flags = O_WRONLY; } else { flags = O_RDONLY; } result.handle = open(path, flags); if(result.handle == -1) { log_error("ERROR in open file: %s", strerror(errno)); } return(result); } static PLATFORM_REMOVE_FILE(linux_remove_file) { i32 err = remove(path); if(err) { log_error("ERROR in open file: %s", strerror(errno)); return false; } return true; } static PLATFORM_CLOSE_FILE(linux_close_file) { i32 err = close(file.handle); if(err) { log_error("ERROR in open file: %s", strerror(errno)); } } static PLATFORM_WRITE_FILE(linux_write_file) { i32 err = write(file.handle, src, size_bytes * size); if(err) { log_error("ERROR in open file: %s", strerror(errno)); } } static PLATFORM_READ_FILE(linux_read_file) { read(file.handle, dst, size_bytes * size); } static PLATFORM_SEEK_FILE(linux_seek_file) { switch(seek_options) { case SO_END: { lseek(file.handle, offset, SEEK_END); } break; case SO_CUR: { lseek(file.handle, offset, SEEK_CUR); } break; case SO_SET: { lseek(file.handle, offset, SEEK_SET); } break; } } static PLATFORM_TELL_FILE(linux_tell_file) { return (i32)lseek(file.handle, 0, SEEK_CUR); } static PLATFORM_READ_LINE_FILE(linux_read_line_file) { assert(false); return nullptr; } static PLATFORM_PRINT_FILE(linux_print_file) { FILE* f = fdopen(file.handle, "wr"); if(f) { va_list args; va_start(args, format); fprintf(f, format, args); va_end(args); } return 0; } static PLATFORM_REMOVE_DIRECTORY(linux_remove_directory) { struct dirent *de; DIR *dr = opendir(path); if(dr == nullptr) { log_error("Could not open current directory"); return false; } de = readdir(dr); assert(strcmp(de->d_name, ".")); de = readdir(dr); assert(strcmp(de->d_name, "..")); de = readdir(dr); if(de == nullptr) { rmdir(path); return true; } else { log_error("Directory not empty"); return false; } } PLATFORM_GET_ALL_FILES_WITH_EXTENSION(linux_get_all_files_with_extension) { struct dirent *de; DIR *dr = opendir(directory_path); if(dr == nullptr) { log_error("Could not open current directory"); return; } while((de = readdir(dr)) != nullptr) { if(with_sub_directories && de->d_type == DT_DIR) { if(strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0) { char sub_path[2048]; sprintf(sub_path, "%s%s/", directory_path, de->d_name); linux_get_all_files_with_extension(sub_path, extension, directory_data, true); } } else if(de->d_type == DT_REG) { const char *ext = strrchr(de->d_name, '.'); if((ext) && (ext != de->d_name)) { if(strcmp((++ext), extension) == 0) { char sub_path[2048]; sprintf(sub_path, "%s%s", directory_path, de->d_name); char *file_name = strtok(de->d_name, "."); strcpy(directory_data->file_paths[directory_data->file_count], sub_path); strcpy(directory_data->file_names[directory_data->file_count], file_name); directory_data->file_count++; } } } } closedir(dr); } PLATFORM_GET_ALL_DIRECTORIES(linux_get_all_directories) { char ** dir_buf = nullptr; struct dirent *de; DIR *dr = opendir(path); if (dr == NULL) { printf("Could not open current directory" ); return nullptr; } while ((de = readdir(dr)) != NULL) { if(de->d_type & DT_DIR) { if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) continue; char *dir_name = (char *)malloc(strlen(de->d_name) + 1); strcpy(dir_name, de->d_name); buf_push(dir_buf, dir_name); } } closedir(dr); return dir_buf; } static PLATFORM_IS_EOL(linux_is_eol) { return c == '\n'; } static void init_platform(PlatformApi& platform_api) { platform_api.get_all_files_with_extension = linux_get_all_files_with_extension; platform_api.file_exists = linux_file_exists; platform_api.allocate_memory = linux_allocate_memory; platform_api.deallocate_memory = linux_deallocate_memory; platform_api.load_dynamic_library = linux_load_library; platform_api.free_dynamic_library = linux_free_library; platform_api.load_symbol = linux_load_symbol; platform_api.open_file = linux_open_file; platform_api.remove_file = linux_remove_file; platform_api.remove_directory = linux_remove_directory; platform_api.read_file = linux_read_file; platform_api.write_file = linux_write_file; platform_api.close_file = linux_close_file; platform_api.seek_file = linux_seek_file; platform_api.tell_file = linux_tell_file; platform_api.print_file = linux_print_file; platform_api.get_all_directories = linux_get_all_directories; platform_api.create_directory = linux_create_directory; platform_api.is_eol = linux_is_eol; // Threading platform_api.add_entry = add_entry; platform_api.complete_all_work = complete_all_work; platform_api.make_queue = make_queue; }
22.526432
123
0.582967
glitchheart
335653f54dd2f8c39bf3f44e2158859f4386ba2e
15,542
cpp
C++
src/modes/hip/device.cpp
luspi/occa
a6d9846fc67f35dea1c3af1ef3dc36bbe1fdd244
[ "MIT" ]
4
2020-02-26T19:33:16.000Z
2020-12-06T07:50:11.000Z
src/modes/hip/device.cpp
luspi/occa
a6d9846fc67f35dea1c3af1ef3dc36bbe1fdd244
[ "MIT" ]
12
2020-05-13T03:50:11.000Z
2021-09-16T16:26:06.000Z
src/modes/hip/device.cpp
luspi/occa
a6d9846fc67f35dea1c3af1ef3dc36bbe1fdd244
[ "MIT" ]
10
2020-03-02T15:55:02.000Z
2021-12-03T02:44:10.000Z
#include <occa/core/base.hpp> #include <occa/io/output.hpp> #include <occa/tools/env.hpp> #include <occa/tools/misc.hpp> #include <occa/tools/sys.hpp> #include <occa/modes/hip/device.hpp> #include <occa/modes/hip/kernel.hpp> #include <occa/modes/hip/memory.hpp> #include <occa/modes/hip/stream.hpp> #include <occa/modes/hip/streamTag.hpp> #include <occa/modes/hip/utils.hpp> #include <occa/modes/serial/device.hpp> #include <occa/modes/serial/kernel.hpp> #include <occa/lang/kernelMetadata.hpp> #include <occa/lang/primitive.hpp> #include <occa/lang/modes/hip.hpp> namespace occa { namespace hip { device::device(const occa::properties &properties_) : occa::launchedModeDevice_t(properties_) { hipDeviceProp_t hipProps; if (!properties.has("wrapped")) { OCCA_ERROR("[HIP] device not given a [device_id] integer", properties.has("device_id") && properties["device_id"].isNumber()); deviceID = properties.get<int>("device_id"); OCCA_HIP_ERROR("Device: Creating Device", hipDeviceGet(&hipDevice, deviceID)); OCCA_HIP_ERROR("Device: Setting Device", hipSetDevice(deviceID)); OCCA_HIP_ERROR("Getting device properties", hipGetDeviceProperties(&hipProps, deviceID)); } p2pEnabled = false; occa::json &kernelProps = properties["kernel"]; std::string compiler, compilerFlags; if (env::var("OCCA_HIP_COMPILER").size()) { compiler = env::var("OCCA_HIP_COMPILER"); } else if (kernelProps.get<std::string>("compiler").size()) { compiler = (std::string) kernelProps["compiler"]; } else { compiler = "hipcc"; } if (env::var("OCCA_HIP_COMPILER_FLAGS").size()) { compilerFlags = env::var("OCCA_HIP_COMPILER_FLAGS"); } else if (kernelProps.get<std::string>("compiler_flags").size()) { compilerFlags = (std::string) kernelProps["compiler_flags"]; } else { compilerFlags = "-O3"; } kernelProps["compiler"] = compiler; kernelProps["compiler_flags"] = compilerFlags; archMajorVersion = kernelProps.get<int>("arch/major", hipProps.major); archMinorVersion = kernelProps.get<int>("arch/minor", hipProps.minor); std::string arch = getDeviceArch(deviceID, archMajorVersion, archMinorVersion); std::string archFlag; if (startsWith(arch, "sm_")) { archFlag = " -arch=" + arch; } else if (startsWith(arch, "gfx")) { #ifdef __HIP_ROCclr__ archFlag = " --amdgpu-target=" + arch; #else archFlag = " -t " + arch; #endif } else { OCCA_FORCE_ERROR("Unknown HIP arch"); } kernelProps["compiler_flag_arch"] = archFlag; } device::~device() { } void device::finish() const { OCCA_HIP_ERROR("Device: Finish", hipStreamSynchronize(getHipStream())); } bool device::hasSeparateMemorySpace() const { return true; } hash_t device::hash() const { if (!hash_.initialized) { std::stringstream ss; ss << "major: " << archMajorVersion << ' ' << "minor: " << archMinorVersion; hash_ = occa::hash(ss.str()); } return hash_; } hash_t device::kernelHash(const occa::properties &props) const { return ( occa::hash(props["compiler"]) ^ props["compiler_flags"] ^ props["compiler_env_script"] ); } lang::okl::withLauncher* device::createParser(const occa::properties &props) const { return new lang::okl::hipParser(props); } //---[ Stream ]--------------------- modeStream_t* device::createStream(const occa::properties &props) { hipStream_t hipStream; OCCA_HIP_ERROR("Device: Setting Device", hipSetDevice(deviceID)); OCCA_HIP_ERROR("Device: createStream", hipStreamCreate(&hipStream)); return new stream(this, props, hipStream); } occa::streamTag device::tagStream() { hipEvent_t hipEvent; OCCA_HIP_ERROR("Device: Setting Device", hipSetDevice(deviceID)); OCCA_HIP_ERROR("Device: Tagging Stream (Creating Tag)", hipEventCreate(&hipEvent)); OCCA_HIP_ERROR("Device: Tagging Stream", hipEventRecord(hipEvent, getHipStream())); return new occa::hip::streamTag(this, hipEvent); } void device::waitFor(occa::streamTag tag) { occa::hip::streamTag *hipTag = ( dynamic_cast<occa::hip::streamTag*>(tag.getModeStreamTag()) ); OCCA_HIP_ERROR("Device: Waiting For Tag", hipEventSynchronize(hipTag->hipEvent)); } double device::timeBetween(const occa::streamTag &startTag, const occa::streamTag &endTag) { occa::hip::streamTag *hipStartTag = ( dynamic_cast<occa::hip::streamTag*>(startTag.getModeStreamTag()) ); occa::hip::streamTag *hipEndTag = ( dynamic_cast<occa::hip::streamTag*>(endTag.getModeStreamTag()) ); waitFor(endTag); float msTimeTaken; OCCA_HIP_ERROR("Device: Timing Between Tags", hipEventElapsedTime(&msTimeTaken, hipStartTag->hipEvent, hipEndTag->hipEvent)); return (double) (1.0e-3 * (double) msTimeTaken); } hipStream_t& device::getHipStream() const { occa::hip::stream *stream = (occa::hip::stream*) currentStream.getModeStream(); return stream->hipStream; } //================================== //---[ Kernel ]--------------------- modeKernel_t* device::buildKernelFromProcessedSource( const hash_t kernelHash, const std::string &hashDir, const std::string &kernelName, const std::string &sourceFilename, const std::string &binaryFilename, const bool usingOkl, lang::sourceMetadata_t &launcherMetadata, lang::sourceMetadata_t &deviceMetadata, const occa::properties &kernelProps, io::lock_t lock ) { compileKernel(hashDir, kernelName, kernelProps, lock); if (usingOkl) { return buildOKLKernelFromBinary(kernelHash, hashDir, kernelName, launcherMetadata, deviceMetadata, kernelProps, lock); } // Regular HIP Kernel hipModule_t hipModule; hipFunction_t hipFunction; hipError_t error; error = hipModuleLoad(&hipModule, binaryFilename.c_str()); if (error) { lock.release(); OCCA_HIP_ERROR("Kernel [" + kernelName + "]: Loading Module", error); } error = hipModuleGetFunction(&hipFunction, hipModule, kernelName.c_str()); if (error) { lock.release(); OCCA_HIP_ERROR("Kernel [" + kernelName + "]: Loading Function", error); } return new kernel(this, kernelName, sourceFilename, hipModule, hipFunction, kernelProps); } void device::setArchCompilerFlags(occa::properties &kernelProps) { const std::string hipccCompilerFlags = ( kernelProps.get<std::string>("hipcc_compiler_flags") ); if (hipccCompilerFlags.find("-arch=sm") == std::string::npos && #ifdef __HIP_ROCclr__ hipccCompilerFlags.find("-t gfx") == std::string::npos #else hipccCompilerFlags.find("--amdgpu-target=gfx") == std::string::npos #endif ) { kernelProps["hipcc_compiler_flags"] += " "; kernelProps["hipcc_compiler_flags"] += kernelProps["compiler_flag_arch"]; } } void device::compileKernel(const std::string &hashDir, const std::string &kernelName, const occa::properties &kernelProps, io::lock_t &lock) { occa::properties allProps = kernelProps; const bool verbose = allProps.get("verbose", false); std::string sourceFilename = hashDir + kc::sourceFile; std::string binaryFilename = hashDir + kc::binaryFile; setArchCompilerFlags(allProps); const std::string compiler = allProps["compiler"]; std::string compilerFlags = allProps["compiler_flags"]; const std::string hipccCompilerFlags = allProps["hipcc_compiler_flags"]; const bool compilingOkl = allProps.get("okl/enabled", true); if (!compilingOkl) { sys::addCompilerIncludeFlags(compilerFlags); sys::addCompilerLibraryFlags(compilerFlags); } std::stringstream command; if (allProps.has("compiler_env_script")) { command << allProps["compiler_env_script"] << " && "; } //---[ Compiling Command ]-------- command << compiler << " --genco" #if defined(__HIP_PLATFORM_NVCC___) || defined(__HIP_ROCclr__) << ' ' << compilerFlags #else << " -f=\\\"" << compilerFlags << "\\\"" #endif << ' ' << hipccCompilerFlags #if defined(__HIP_PLATFORM_NVCC___) || defined(__HIP_ROCclr__) << " -I" << env::OCCA_DIR << "include" << " -I" << env::OCCA_INSTALL_DIR << "include" #endif /* NC: hipcc doesn't seem to like linking a library in */ //<< " -L" << env::OCCA_INSTALL_DIR << "lib -locca" << ' ' << sourceFilename << " -o " << binaryFilename; if (!verbose) { command << " > /dev/null 2>&1"; } const std::string &sCommand = command.str(); if (verbose) { io::stdout << sCommand << '\n'; } const int compileError = system(sCommand.c_str()); lock.release(); if (compileError) { OCCA_FORCE_ERROR("Error compiling [" << kernelName << "]," " Command: [" << sCommand << ']'); } //================================ } modeKernel_t* device::buildOKLKernelFromBinary(const hash_t kernelHash, const std::string &hashDir, const std::string &kernelName, lang::sourceMetadata_t &launcherMetadata, lang::sourceMetadata_t &deviceMetadata, const occa::properties &kernelProps, io::lock_t lock) { const std::string sourceFilename = hashDir + kc::sourceFile; const std::string binaryFilename = hashDir + kc::binaryFile; hipModule_t hipModule; hipError_t error; error = hipModuleLoad(&hipModule, binaryFilename.c_str()); if (error) { lock.release(); OCCA_HIP_ERROR("Kernel [" + kernelName + "]: Loading Module", error); } // Create wrapper kernel and set launcherKernel kernel &k = *(new kernel(this, kernelName, sourceFilename, kernelProps)); k.launcherKernel = buildLauncherKernel(kernelHash, hashDir, kernelName, launcherMetadata); // Find device kernels orderedKernelMetadata launchedKernelsMetadata = getLaunchedKernelsMetadata( kernelName, deviceMetadata ); const int launchedKernelsCount = (int) launchedKernelsMetadata.size(); for (int i = 0; i < launchedKernelsCount; ++i) { lang::kernelMetadata_t &metadata = launchedKernelsMetadata[i]; hipFunction_t hipFunction; error = hipModuleGetFunction(&hipFunction, hipModule, metadata.name.c_str()); if (error) { lock.release(); OCCA_HIP_ERROR("Kernel [" + metadata.name + "]: Loading Function", error); } kernel *hipKernel = new kernel(this, metadata.name, sourceFilename, hipModule, hipFunction, kernelProps); hipKernel->metadata = metadata; k.deviceKernels.push_back(hipKernel); } return &k; } modeKernel_t* device::buildKernelFromBinary(const std::string &filename, const std::string &kernelName, const occa::properties &kernelProps) { hipModule_t hipModule; hipFunction_t hipFunction; OCCA_HIP_ERROR("Kernel [" + kernelName + "]: Loading Module", hipModuleLoad(&hipModule, filename.c_str())); OCCA_HIP_ERROR("Kernel [" + kernelName + "]: Loading Function", hipModuleGetFunction(&hipFunction, hipModule, kernelName.c_str())); return new kernel(this, kernelName, filename, hipModule, hipFunction, kernelProps); } //================================== //---[ Memory ]--------------------- modeMemory_t* device::malloc(const udim_t bytes, const void *src, const occa::properties &props) { if (props.get("mapped", false)) { return mappedAlloc(bytes, src, props); } hip::memory &mem = *(new hip::memory(this, bytes, props)); OCCA_HIP_ERROR("Device: Setting Device", hipSetDevice(deviceID)); OCCA_HIP_ERROR("Device: malloc", hipMalloc((void**) &(mem.hipPtr), bytes)); if (src != NULL) { mem.copyFrom(src, bytes, 0); } return &mem; } modeMemory_t* device::mappedAlloc(const udim_t bytes, const void *src, const occa::properties &props) { hip::memory &mem = *(new hip::memory(this, bytes, props)); OCCA_HIP_ERROR("Device: Setting Device", hipSetDevice(deviceID)); OCCA_HIP_ERROR("Device: malloc host", hipHostMalloc((void**) &(mem.mappedPtr), bytes)); OCCA_HIP_ERROR("Device: get device pointer from host", hipHostGetDevicePointer((void**) &(mem.hipPtr), mem.mappedPtr, 0)); if (src != NULL) { ::memcpy(mem.mappedPtr, src, bytes); } return &mem; } udim_t device::memorySize() const { return hip::getDeviceMemorySize(hipDevice); } //================================== } }
34.461197
92
0.527538
luspi
33589817109583ff5c0107e065fa2b2f95d9f573
152,808
cpp
C++
RenderSystems/GL3Plus/src/OgreGL3PlusRenderSystem.cpp
Ybalrid/ogre-next
8a4919be31c4262643a77534f883e35fdf850f4a
[ "MIT" ]
null
null
null
RenderSystems/GL3Plus/src/OgreGL3PlusRenderSystem.cpp
Ybalrid/ogre-next
8a4919be31c4262643a77534f883e35fdf850f4a
[ "MIT" ]
null
null
null
RenderSystems/GL3Plus/src/OgreGL3PlusRenderSystem.cpp
Ybalrid/ogre-next
8a4919be31c4262643a77534f883e35fdf850f4a
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreGL3PlusRenderSystem.h" #include "OgreRenderSystem.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreLight.h" #include "OgreCamera.h" #include "OgreGL3PlusTextureManager.h" #include "OgreGL3PlusHardwareCounterBuffer.h" #include "OgreGL3PlusHardwareUniformBuffer.h" #include "OgreGL3PlusHardwareShaderStorageBuffer.h" #include "OgreGL3PlusHardwareVertexBuffer.h" #include "OgreGL3PlusHardwareIndexBuffer.h" #include "OgreGL3PlusDefaultHardwareBufferManager.h" #include "OgreGL3PlusUtil.h" #include "OgreGLSLShader.h" #include "OgreGLSLShaderManager.h" #include "OgreException.h" #include "OgreGLSLExtSupport.h" #include "OgreGL3PlusHardwareOcclusionQuery.h" #include "OgreGL3PlusDepthBuffer.h" #include "OgreGL3PlusHardwarePixelBuffer.h" #include "OgreGL3PlusContext.h" #include "OgreGLSLShaderFactory.h" #include "OgreGL3PlusFBORenderTexture.h" #include "OgreGL3PlusHardwareBufferManager.h" #include "OgreGLSLSeparableProgramManager.h" #include "OgreGLSLSeparableProgram.h" #include "OgreGLSLMonolithicProgramManager.h" #include "OgreGL3PlusPixelFormat.h" #include "OgreGL3PlusVertexArrayObject.h" #include "OgreGL3PlusHlmsPso.h" #include "OgreHlmsDatablock.h" #include "OgreHlmsSamplerblock.h" #include "Vao/OgreGL3PlusVaoManager.h" #include "Vao/OgreGL3PlusVertexArrayObject.h" #include "Vao/OgreGL3PlusBufferInterface.h" #include "Vao/OgreIndexBufferPacked.h" #include "Vao/OgreIndirectBufferPacked.h" #include "Vao/OgreUavBufferPacked.h" #include "CommandBuffer/OgreCbDrawCall.h" #include "OgreRoot.h" #include "OgreConfig.h" #include "OgreViewport.h" #include "OgreGL3PlusPixelFormat.h" #include "OgreProfiler.h" #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE extern "C" void glFlushRenderAPPLE(); #endif #if OGRE_DEBUG_MODE static void APIENTRY GLDebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { if( type == GL_DEBUG_TYPE_PUSH_GROUP || type == GL_DEBUG_TYPE_POP_GROUP ) return; //Ignore these char debSource[32], debType[32], debSev[32]; if (source == GL_DEBUG_SOURCE_API) strcpy(debSource, "OpenGL"); else if (source == GL_DEBUG_SOURCE_WINDOW_SYSTEM) strcpy(debSource, "Windows"); else if (source == GL_DEBUG_SOURCE_SHADER_COMPILER) strcpy(debSource, "Shader Compiler"); else if (source == GL_DEBUG_SOURCE_THIRD_PARTY) strcpy(debSource, "Third Party"); else if (source == GL_DEBUG_SOURCE_APPLICATION) strcpy(debSource, "Application"); else if (source == GL_DEBUG_SOURCE_OTHER) strcpy(debSource, "Other"); if (type == GL_DEBUG_TYPE_ERROR) strcpy(debType, "error"); else if (type == GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR) strcpy(debType, "deprecated behavior"); else if (type == GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR) strcpy(debType, "undefined behavior"); else if (type == GL_DEBUG_TYPE_PORTABILITY) strcpy(debType, "portability"); else if (type == GL_DEBUG_TYPE_PERFORMANCE) strcpy(debType, "performance"); else if (type == GL_DEBUG_TYPE_OTHER) strcpy(debType, "message"); else if (type == GL_DEBUG_TYPE_PUSH_GROUP) strcpy(debType, "push"); else if (type == GL_DEBUG_TYPE_POP_GROUP) strcpy(debType, "pop"); if (severity == GL_DEBUG_SEVERITY_HIGH) { strcpy(debSev, "high"); } else if (severity == GL_DEBUG_SEVERITY_MEDIUM) strcpy(debSev, "medium"); else if (severity == GL_DEBUG_SEVERITY_LOW) strcpy(debSev, "low"); else if( severity == GL_DEBUG_SEVERITY_NOTIFICATION ) { strcpy(debSev, "notification"); #if OGRE_PROFILING == 0 //Filter notification debug GL messages as they can //be quite noisy, annoying and useless on NVIDIA. return; #endif } else strcpy(debSev, "unknown"); Ogre::LogManager::getSingleton().stream() << debSource << ":" << debType << "(" << debSev << ") " << id << ": " << message; } #endif namespace Ogre { GL3PlusRenderSystem::GL3PlusRenderSystem() : mBlendChannelMask( HlmsBlendblock::BlendChannelAll ), mDepthWrite(true), mScissorsEnabled(false), mGlobalVao( 0 ), mCurrentVertexBuffer( 0 ), mCurrentIndexBuffer( 0 ), mCurrentPolygonMode( GL_TRIANGLES ), mShaderManager(0), mGLSLShaderFactory(0), mHardwareBufferManager(0), mRTTManager(0), mActiveTextureUnit(0), mHasArbInvalidateSubdata( false ), mNullColourFramebuffer( 0 ), mMaxModifiedUavPlusOne( 0 ) { size_t i; LogManager::getSingleton().logMessage(getName() + " created."); mRenderAttribsBound.reserve(100); mRenderInstanceAttribsBound.reserve(100); // Get our GLSupport mGLSupport = Ogre::getGLSupport(); mWorldMatrix = Matrix4::IDENTITY; mViewMatrix = Matrix4::IDENTITY; initConfigOptions(); for (i = 0; i < OGRE_MAX_TEXTURE_LAYERS; i++) { // Dummy value mTextureCoordIndex[i] = 99; mTextureTypes[i] = GL_TEXTURE_2D; } mActiveRenderTarget = 0; mCurrentContext = 0; mMainContext = 0; mGLInitialised = false; mUseAdjacency = false; mTextureMipmapCount = 0; mMinFilter = FO_LINEAR; mMipFilter = FO_POINT; mSwIndirectBufferPtr = 0; mClipDistances = 0; mPso = 0; mCurrentComputeShader = 0; mLargestSupportedAnisotropy = 1; } GL3PlusRenderSystem::~GL3PlusRenderSystem() { shutdown(); // Destroy render windows RenderTargetMap::iterator i; for (i = mRenderTargets.begin(); i != mRenderTargets.end(); ++i) { OGRE_DELETE i->second; } mRenderTargets.clear(); if (mGLSupport) OGRE_DELETE mGLSupport; } const String& GL3PlusRenderSystem::getName(void) const { static String strName("OpenGL 3+ Rendering Subsystem"); return strName; } const String& GL3PlusRenderSystem::getFriendlyName(void) const { static String strName("OpenGL 3+"); return strName; } void GL3PlusRenderSystem::initConfigOptions(void) { mGLSupport->addConfig(); } ConfigOptionMap& GL3PlusRenderSystem::getConfigOptions(void) { return mGLSupport->getConfigOptions(); } void GL3PlusRenderSystem::setConfigOption(const String &name, const String &value) { mGLSupport->setConfigOption(name, value); } String GL3PlusRenderSystem::validateConfigOptions(void) { // XXX Return an error string if something is invalid return mGLSupport->validateConfig(); } RenderWindow* GL3PlusRenderSystem::_initialise(bool autoCreateWindow, const String& windowTitle) { mGLSupport->start(); RenderWindow *autoWindow = mGLSupport->createWindow(autoCreateWindow, this, windowTitle); RenderSystem::_initialise(autoCreateWindow, windowTitle); return autoWindow; } RenderSystemCapabilities* GL3PlusRenderSystem::createRenderSystemCapabilities() const { RenderSystemCapabilities* rsc = OGRE_NEW RenderSystemCapabilities(); rsc->setCategoryRelevant(CAPS_CATEGORY_GL, true); rsc->setDriverVersion(mDriverVersion); const char* deviceName = (const char*)glGetString(GL_RENDERER); if (deviceName) { rsc->setDeviceName(deviceName); } rsc->setRenderSystemName(getName()); rsc->parseVendorFromString(mGLSupport->getGLVendor()); bool hasGL40 = mGLSupport->hasMinGLVersion(4, 0); bool hasGL41 = mGLSupport->hasMinGLVersion(4, 1); bool hasGL42 = mGLSupport->hasMinGLVersion(4, 2); // Check for hardware mipmapping support. bool disableAutoMip = false; #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_LINUX // Apple & Linux ATI drivers have faults in hardware mipmap generation // TODO: Test this with GL3+ if (rsc->getVendor() == GPU_AMD) disableAutoMip = true; #endif // The Intel 915G frequently corrupts textures when using hardware mip generation // I'm not currently sure how many generations of hardware this affects, // so for now, be safe. if (rsc->getVendor() == GPU_INTEL) disableAutoMip = true; if (!disableAutoMip) rsc->setCapability(RSC_AUTOMIPMAP); // Check for blending support rsc->setCapability(RSC_BLENDING); // Multitexturing support and set number of texture units GLint units; OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &units)); rsc->setNumTextureUnits(std::min<ushort>(16, units)); // Check for Anisotropy support if (mGLSupport->checkExtension("GL_EXT_texture_filter_anisotropic")) rsc->setCapability(RSC_ANISOTROPY); // DOT3 support is standard rsc->setCapability(RSC_DOT3); // Cube map rsc->setCapability(RSC_CUBEMAPPING); // Point sprites rsc->setCapability(RSC_POINT_SPRITES); rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS); // Check for hardware stencil support and set bit depth rsc->setCapability(RSC_HWSTENCIL); rsc->setCapability(RSC_TWO_SIDED_STENCIL); rsc->setStencilBufferBitDepth(8); rsc->setCapability(RSC_HW_GAMMA); rsc->setCapability(RSC_TEXTURE_SIGNED_INT); // Vertex Buffer Objects are always supported rsc->setCapability(RSC_VBO); rsc->setCapability(RSC_32BIT_INDEX); // Vertex Array Objects are supported in 3.0 rsc->setCapability(RSC_VAO); // Check for texture compression rsc->setCapability(RSC_TEXTURE_COMPRESSION); // Check for dxt compression if (mGLSupport->checkExtension("GL_EXT_texture_compression_s3tc")) { rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT); } // Check for etc compression if (mGLSupport->checkExtension("GL_ARB_ES3_compatibility") || mHasGL43) { rsc->setCapability(RSC_TEXTURE_COMPRESSION_ETC2); } // Check for vtc compression if (mGLSupport->checkExtension("GL_NV_texture_compression_vtc")) { rsc->setCapability(RSC_TEXTURE_COMPRESSION_VTC); } // RGTC(BC4/BC5) is supported by the 3.0 spec rsc->setCapability(RSC_TEXTURE_COMPRESSION_BC4_BC5); // BPTC(BC6H/BC7) is supported by the extension or OpenGL 4.2 or higher if (mGLSupport->checkExtension("GL_ARB_texture_compression_bptc") || hasGL42) { rsc->setCapability(RSC_TEXTURE_COMPRESSION_BC6H_BC7); } //Technically D3D10.1 hardware (GL3) supports gather and exposes this extension. //However we have bug reports that textureGather isn't working properly, and //sadly these cards no longer receive updates. So, assume modern cards and //modern drivers are needed. //https://bitbucket.org/sinbad/ogre/commits/c76e1bedfed65d0f9dc45353d432a26f278cc968#comment-1776416 //if( mGLSupport->checkExtension("GL_ARB_texture_gather") || mHasGL40 ) if( mHasGL43 ) rsc->setCapability(RSC_TEXTURE_GATHER); if( mHasGL43 || (mGLSupport->checkExtension("GL_ARB_shader_image_load_store") && mGLSupport->checkExtension("GL_ARB_shader_storage_buffer_object")) ) { rsc->setCapability(RSC_UAV); } rsc->setCapability(RSC_FBO); rsc->setCapability(RSC_HWRENDER_TO_TEXTURE); // Probe number of draw buffers // Only makes sense with FBO support, so probe here GLint buffers; OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_DRAW_BUFFERS, &buffers)); rsc->setNumMultiRenderTargets(std::min<int>(buffers, (GLint)OGRE_MAX_MULTIPLE_RENDER_TARGETS)); rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS); // Stencil wrapping rsc->setCapability(RSC_STENCIL_WRAP); // GL always shares vertex and fragment texture units (for now?) rsc->setVertexTextureUnitsShared(true); // Blending support rsc->setCapability(RSC_BLENDING); // Check for non-power-of-2 texture support rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES); // Check for atomic counter support if (mGLSupport->checkExtension("GL_ARB_shader_atomic_counters") || hasGL42) rsc->setCapability(RSC_ATOMIC_COUNTERS); // As are user clipping planes rsc->setCapability(RSC_USER_CLIP_PLANES); // So are 1D & 3D textures rsc->setCapability(RSC_TEXTURE_1D); rsc->setCapability(RSC_TEXTURE_3D); rsc->setCapability(RSC_TEXTURE_2D_ARRAY); if( mDriverVersion.major >= 4 || mGLSupport->checkExtension("GL_ARB_texture_cube_map_array") ) rsc->setCapability(RSC_TEXTURE_CUBE_MAP_ARRAY); // UBYTE4 always supported rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4); // Infinite far plane always supported rsc->setCapability(RSC_INFINITE_FAR_PLANE); // Check for hardware occlusion support rsc->setCapability(RSC_HWOCCLUSION); GLint maxRes2d, maxRes3d, maxResCube; OGRE_CHECK_GL_ERROR( glGetIntegerv( GL_MAX_TEXTURE_SIZE, &maxRes2d ) ); OGRE_CHECK_GL_ERROR( glGetIntegerv( GL_MAX_3D_TEXTURE_SIZE, &maxRes3d ) ); OGRE_CHECK_GL_ERROR( glGetIntegerv( GL_MAX_CUBE_MAP_TEXTURE_SIZE, &maxResCube ) ); rsc->setMaximumResolutions( static_cast<ushort>(maxRes2d), static_cast<ushort>(maxRes3d), static_cast<ushort>(maxResCube) ); // Point size GLfloat psRange[2] = {0.0, 0.0}; OGRE_CHECK_GL_ERROR(glGetFloatv(GL_POINT_SIZE_RANGE, psRange)); rsc->setMaxPointSize(psRange[1]); // GLSL is always supported in GL // TODO: Deprecate this profile name in favor of versioned names rsc->addShaderProfile("glsl"); // Support for specific shader profiles if (getNativeShadingLanguageVersion() >= 440) rsc->addShaderProfile("glsl440"); if (getNativeShadingLanguageVersion() >= 430) rsc->addShaderProfile("glsl430"); if (getNativeShadingLanguageVersion() >= 420) rsc->addShaderProfile("glsl420"); if (getNativeShadingLanguageVersion() >= 410) rsc->addShaderProfile("glsl410"); if (getNativeShadingLanguageVersion() >= 400) rsc->addShaderProfile("glsl400"); if (getNativeShadingLanguageVersion() >= 330) rsc->addShaderProfile("glsl330"); if (getNativeShadingLanguageVersion() >= 150) rsc->addShaderProfile("glsl150"); if (getNativeShadingLanguageVersion() >= 140) rsc->addShaderProfile("glsl140"); if (getNativeShadingLanguageVersion() >= 130) rsc->addShaderProfile("glsl130"); // FIXME: This isn't working right yet in some rarer cases /*if (mGLSupport->checkExtension("GL_ARB_separate_shader_objects") || hasGL41) rsc->setCapability(RSC_SEPARATE_SHADER_OBJECTS);*/ // Vertex/Fragment Programs rsc->setCapability(RSC_VERTEX_PROGRAM); rsc->setCapability(RSC_FRAGMENT_PROGRAM); GLfloat floatConstantCount = 0; OGRE_CHECK_GL_ERROR(glGetFloatv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &floatConstantCount)); rsc->setVertexProgramConstantFloatCount((Ogre::ushort)floatConstantCount); rsc->setVertexProgramConstantBoolCount((Ogre::ushort)floatConstantCount); rsc->setVertexProgramConstantIntCount((Ogre::ushort)floatConstantCount); // Fragment Program Properties floatConstantCount = 0; OGRE_CHECK_GL_ERROR(glGetFloatv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, &floatConstantCount)); rsc->setFragmentProgramConstantFloatCount((Ogre::ushort)floatConstantCount); rsc->setFragmentProgramConstantBoolCount((Ogre::ushort)floatConstantCount); rsc->setFragmentProgramConstantIntCount((Ogre::ushort)floatConstantCount); // Geometry Program Properties rsc->setCapability(RSC_GEOMETRY_PROGRAM); OGRE_CHECK_GL_ERROR(glGetFloatv(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS, &floatConstantCount)); rsc->setGeometryProgramConstantFloatCount(floatConstantCount); GLint maxOutputVertices; OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES, &maxOutputVertices)); rsc->setGeometryProgramNumOutputVertices(maxOutputVertices); //FIXME Is this correct? OGRE_CHECK_GL_ERROR(glGetFloatv(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS, &floatConstantCount)); rsc->setGeometryProgramConstantFloatCount(floatConstantCount); rsc->setGeometryProgramConstantBoolCount(floatConstantCount); rsc->setGeometryProgramConstantIntCount(floatConstantCount); // Tessellation Program Properties if (mGLSupport->checkExtension("GL_ARB_tessellation_shader") || hasGL40) { rsc->setCapability(RSC_TESSELLATION_HULL_PROGRAM); rsc->setCapability(RSC_TESSELLATION_DOMAIN_PROGRAM); OGRE_CHECK_GL_ERROR(glGetFloatv(GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS, &floatConstantCount)); // 16 boolean params allowed rsc->setTessellationHullProgramConstantBoolCount(floatConstantCount); // 16 integer params allowed, 4D rsc->setTessellationHullProgramConstantIntCount(floatConstantCount); // float params, always 4D rsc->setTessellationHullProgramConstantFloatCount(floatConstantCount); OGRE_CHECK_GL_ERROR(glGetFloatv(GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS, &floatConstantCount)); // 16 boolean params allowed rsc->setTessellationDomainProgramConstantBoolCount(floatConstantCount); // 16 integer params allowed, 4D rsc->setTessellationDomainProgramConstantIntCount(floatConstantCount); // float params, always 4D rsc->setTessellationDomainProgramConstantFloatCount(floatConstantCount); } // Compute Program Properties if (mGLSupport->checkExtension("GL_ARB_compute_shader") || mHasGL43) { rsc->setCapability(RSC_COMPUTE_PROGRAM); //FIXME Is this correct? OGRE_CHECK_GL_ERROR(glGetFloatv(GL_MAX_COMPUTE_UNIFORM_COMPONENTS, &floatConstantCount)); rsc->setComputeProgramConstantFloatCount(floatConstantCount); rsc->setComputeProgramConstantBoolCount(floatConstantCount); rsc->setComputeProgramConstantIntCount(floatConstantCount); //TODO we should also check max workgroup count & size // OGRE_CHECK_GL_ERROR(glGetFloatv(GL_MAX_COMPUTE_WORK_GROUP_SIZE, &workgroupCount)); // OGRE_CHECK_GL_ERROR(glGetFloatv(GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS, &workgroupInvocations)); } if (mGLSupport->checkExtension("GL_ARB_get_program_binary") || hasGL41) { GLint formats; OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &formats)); if (formats > 0) rsc->setCapability(RSC_CAN_GET_COMPILED_SHADER_BUFFER); } rsc->setCapability(RSC_VERTEX_BUFFER_INSTANCE_DATA); // Check for Float textures rsc->setCapability(RSC_TEXTURE_FLOAT); // OpenGL 3.0 requires a minimum of 16 texture image units units = std::max<GLint>(16, units); rsc->setNumVertexTextureUnits(static_cast<ushort>(units)); if (units > 0) { rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH); } // Mipmap LOD biasing? rsc->setCapability(RSC_MIPMAP_LOD_BIAS); // Alpha to coverage always 'supported' when MSAA is available // although card may ignore it if it doesn't specifically support A2C rsc->setCapability(RSC_ALPHA_TO_COVERAGE); // Check if render to vertex buffer (transform feedback in OpenGL) rsc->setCapability(RSC_HWRENDER_TO_VERTEX_BUFFER); if( mDriverVersion.hasMinVersion( 4, 2 ) || mGLSupport->checkExtension("GL_ARB_shading_language_420pack" ) ) { rsc->setCapability(RSC_CONST_BUFFER_SLOTS_IN_SHADER); } return rsc; } void GL3PlusRenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary) { if (caps->getRenderSystemName() != getName()) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Trying to initialize GL3PlusRenderSystem from RenderSystemCapabilities that do not support OpenGL 3+", "GL3PlusRenderSystem::initialiseFromRenderSystemCapabilities"); } mShaderManager = OGRE_NEW GLSLShaderManager(); // Create GLSL shader factory mGLSLShaderFactory = new GLSLShaderFactory(*mGLSupport); HighLevelGpuProgramManager::getSingleton().addFactory(mGLSLShaderFactory); // Set texture the number of texture units mFixedFunctionTextureUnits = caps->getNumTextureUnits(); // Use VBO's by default mHardwareBufferManager = new v1::GL3PlusHardwareBufferManager(); // Use FBO's for RTT, PBuffers and Copy are no longer supported // Create FBO manager LogManager::getSingleton().logMessage("GL3+: Using FBOs for rendering to textures"); mRTTManager = new GL3PlusFBOManager(*mGLSupport); caps->setCapability(RSC_RTT_DEPTHBUFFER_RESOLUTION_LESSEQUAL); Log* defaultLog = LogManager::getSingleton().getDefaultLog(); if (defaultLog) { caps->log(defaultLog); } // Create the texture manager mTextureManager = new GL3PlusTextureManager(*mGLSupport); /*if (caps->hasCapability(RSC_CAN_GET_COMPILED_SHADER_BUFFER)) { // Enable microcache mShaderManager->setSaveMicrocodesToCache(true); }*/ if( mGLSupport->hasMinGLVersion( 4, 3 ) ) { //On AMD's GCN cards, there is no performance or memory difference between //PF_D24_UNORM_S8_UINT & PF_D32_FLOAT_X24_S8_UINT, so prefer the latter //on modern cards (GL >= 4.3) and that also claim to support this format. //NVIDIA's preference? Dunno, they don't tell. But at least the quality //will be consistent. GLenum depthFormat, stencilFormat; static_cast<GL3PlusFBOManager*>(mRTTManager)->getBestDepthStencil( PF_D32_FLOAT_X24_S8_UINT, PF_D32_FLOAT_X24_S8_UINT, &depthFormat, &stencilFormat ); DepthBuffer::DefaultDepthBufferFormat = PF_D32_FLOAT_X24_S8_UINT; } mGLInitialised = true; } void GL3PlusRenderSystem::reinitialise(void) { this->shutdown(); this->_initialise(true); } void GL3PlusRenderSystem::shutdown(void) { RenderSystem::shutdown(); // Deleting the GLSL program factory if (mGLSLShaderFactory) { // Remove from manager safely if (HighLevelGpuProgramManager::getSingletonPtr()) HighLevelGpuProgramManager::getSingleton().removeFactory(mGLSLShaderFactory); OGRE_DELETE mGLSLShaderFactory; mGLSLShaderFactory = 0; } // Deleting the GPU program manager and hardware buffer manager. Has to be done before the mGLSupport->stop(). OGRE_DELETE mShaderManager; mShaderManager = 0; OGRE_DELETE mHardwareBufferManager; mHardwareBufferManager = 0; OGRE_DELETE mRTTManager; mRTTManager = 0; OGRE_DELETE mTextureManager; mTextureManager = 0; // Delete extra threads contexts for (GL3PlusContextList::iterator i = mBackgroundContextList.begin(); i != mBackgroundContextList.end(); ++i) { GL3PlusContext* pCurContext = *i; pCurContext->releaseContext(); OGRE_DELETE pCurContext; } mBackgroundContextList.clear(); if( mNullColourFramebuffer ) { OCGE( glDeleteFramebuffers( 1, &mNullColourFramebuffer ) ); mNullColourFramebuffer = 0; } mGLSupport->stop(); mStopRendering = true; // delete mTextureManager; // mTextureManager = 0; if( mGlobalVao ) { OCGE( glBindVertexArray( 0 ) ); OCGE( glDeleteVertexArrays( 1, &mGlobalVao ) ); mGlobalVao = 0; } mGLInitialised = 0; // RenderSystem::shutdown(); } bool GL3PlusRenderSystem::_createRenderWindows(const RenderWindowDescriptionList& renderWindowDescriptions, RenderWindowList& createdWindows) { // Call base render system method. if (false == RenderSystem::_createRenderWindows(renderWindowDescriptions, createdWindows)) return false; // Simply call _createRenderWindow in a loop. for (size_t i = 0; i < renderWindowDescriptions.size(); ++i) { const RenderWindowDescription& curRenderWindowDescription = renderWindowDescriptions[i]; RenderWindow* curWindow = NULL; curWindow = _createRenderWindow(curRenderWindowDescription.name, curRenderWindowDescription.width, curRenderWindowDescription.height, curRenderWindowDescription.useFullScreen, &curRenderWindowDescription.miscParams); createdWindows.push_back(curWindow); } return true; } RenderWindow* GL3PlusRenderSystem::_createRenderWindow(const String &name, unsigned int width, unsigned int height, bool fullScreen, const NameValuePairList *miscParams) { if (mRenderTargets.find(name) != mRenderTargets.end()) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Window with name '" + name + "' already exists", "GL3PlusRenderSystem::_createRenderWindow"); } // Log a message StringStream ss; ss << "GL3PlusRenderSystem::_createRenderWindow \"" << name << "\", " << width << "x" << height << " "; if (fullScreen) ss << "fullscreen "; else ss << "windowed "; if (miscParams) { ss << " miscParams: "; NameValuePairList::const_iterator it; for (it = miscParams->begin(); it != miscParams->end(); ++it) { ss << it->first << "=" << it->second << " "; } LogManager::getSingleton().logMessage(ss.str()); } // Create the window RenderWindow* win = mGLSupport->newWindow(name, width, height, fullScreen, miscParams); attachRenderTarget((Ogre::RenderTarget&) *win); if (!mGLInitialised) { initialiseContext(win); mDriverVersion = mGLSupport->getGLVersion(); if( !mDriverVersion.hasMinVersion( 3, 3 ) ) { OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, "OpenGL 3.3 or greater required. Try updating your drivers.", "GL3PlusRenderSystem::_createRenderWindow" ); } assert( !mVaoManager ); bool supportsArbBufferStorage = mDriverVersion.hasMinVersion( 4, 4 ) || mGLSupport->checkExtension("GL_ARB_buffer_storage"); bool emulateTexBuffers = !(mHasGL43 || mGLSupport->checkExtension("GL_ARB_texture_buffer_range")); bool supportsIndirectBuffers = mDriverVersion.hasMinVersion( 4, 6 ) || mGLSupport->checkExtension("GL_ARB_multi_draw_indirect"); bool supportsBaseInstance = mDriverVersion.hasMinVersion( 4, 2 ) || mGLSupport->checkExtension("GL_ARB_base_instance"); bool supportsSsbo = mHasGL43 || mGLSupport->checkExtension("GL_ARB_shader_storage_buffer_object"); mVaoManager = OGRE_NEW GL3PlusVaoManager( supportsArbBufferStorage, emulateTexBuffers, supportsIndirectBuffers, supportsBaseInstance, supportsSsbo ); //Bind the Draw ID OCGE( glGenVertexArrays( 1, &mGlobalVao ) ); OCGE( glBindVertexArray( mGlobalVao ) ); static_cast<GL3PlusVaoManager*>( mVaoManager )->bindDrawId(); OCGE( glBindVertexArray( 0 ) ); const char* shadingLangVersion = (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION); StringVector tokens = StringUtil::split(shadingLangVersion, ". "); mNativeShadingLanguageVersion = (StringConverter::parseUnsignedInt(tokens[0]) * 100) + StringConverter::parseUnsignedInt(tokens[1]); // Initialise GL after the first window has been created // TODO: fire this from emulation options, and don't duplicate Real and Current capabilities mRealCapabilities = createRenderSystemCapabilities(); mHasArbInvalidateSubdata = mHasGL43 || mGLSupport->checkExtension( "GL_ARB_invalidate_subdata" ); // use real capabilities if custom capabilities are not available if (!mUseCustomCapabilities) mCurrentCapabilities = mRealCapabilities; fireEvent("RenderSystemCapabilitiesCreated"); initialiseFromRenderSystemCapabilities(mCurrentCapabilities, (RenderTarget *) win); // Initialise the main context _oneTimeContextInitialization(); if (mCurrentContext) mCurrentContext->setInitialized(); } if ( win->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH ) { // Unlike D3D9, OGL doesn't allow sharing the main depth buffer, so keep them separate. // Only Copy does, but Copy means only one depth buffer... GL3PlusContext *windowContext = 0; win->getCustomAttribute( GL3PlusRenderTexture::CustomAttributeString_GLCONTEXT, &windowContext ); GL3PlusDepthBuffer *depthBuffer = new GL3PlusDepthBuffer( DepthBuffer::POOL_DEFAULT, this, windowContext, GL_NONE, GL_NONE, win->getWidth(), win->getHeight(), win->getFSAA(), 0, PF_UNKNOWN, false, true ); mDepthBufferPool[depthBuffer->getPoolId()].push_back( depthBuffer ); win->attachDepthBuffer( depthBuffer, false ); } return win; } //--------------------------------------------------------------------- DepthBuffer* GL3PlusRenderSystem::_createDepthBufferFor( RenderTarget *renderTarget, bool exactMatchFormat ) { GL3PlusDepthBuffer *retVal = 0; // Only FBOs support different depth buffers, so everything // else creates dummy (empty) containers // retVal = mRTTManager->_createDepthBufferFor( renderTarget ); GL3PlusFrameBufferObject *fbo = 0; renderTarget->getCustomAttribute(GL3PlusRenderTexture::CustomAttributeString_FBO, &fbo); if( fbo || renderTarget->getForceDisableColourWrites() ) { PixelFormat desiredDepthBufferFormat = renderTarget->getDesiredDepthBufferFormat(); if( !exactMatchFormat ) { if( desiredDepthBufferFormat == PF_D24_UNORM_X8 && renderTarget->prefersDepthTexture() ) desiredDepthBufferFormat = PF_D24_UNORM; else desiredDepthBufferFormat = PF_D24_UNORM_S8_UINT; } PixelFormat renderTargetFormat; if( fbo ) renderTargetFormat = fbo->getFormat(); else { //Deal with depth textures renderTargetFormat = desiredDepthBufferFormat; } // Presence of an FBO means the manager is an FBO Manager, that's why it's safe to downcast // Find best depth & stencil format suited for the RT's format GLenum depthFormat, stencilFormat; static_cast<GL3PlusFBOManager*>(mRTTManager)->getBestDepthStencil( desiredDepthBufferFormat, renderTargetFormat, &depthFormat, &stencilFormat ); // OpenGL specs explicitly disallow depth textures with separate stencil. if( stencilFormat == GL_NONE || !renderTarget->prefersDepthTexture() ) { // No "custom-quality" multisample for now in GL retVal = new GL3PlusDepthBuffer( 0, this, mCurrentContext, depthFormat, stencilFormat, renderTarget->getWidth(), renderTarget->getHeight(), renderTarget->getFSAA(), 0, desiredDepthBufferFormat, renderTarget->prefersDepthTexture(), false ); } } return retVal; } //--------------------------------------------------------------------- void GL3PlusRenderSystem::_getDepthStencilFormatFor( GLenum internalColourFormat, GLenum *depthFormat, GLenum *stencilFormat ) { mRTTManager->getBestDepthStencil( internalColourFormat, depthFormat, stencilFormat ); } MultiRenderTarget* GL3PlusRenderSystem::createMultiRenderTarget(const String & name) { MultiRenderTarget *retval = mRTTManager->createMultiRenderTarget(name); attachRenderTarget(*retval); return retval; } void GL3PlusRenderSystem::destroyRenderWindow(RenderWindow* pWin) { // Find it to remove from list. RenderTargetMap::iterator i = mRenderTargets.begin(); while (i != mRenderTargets.end()) { if (i->second == pWin) { GL3PlusContext *windowContext = 0; pWin->getCustomAttribute(GL3PlusRenderTexture::CustomAttributeString_GLCONTEXT, &windowContext); // 1 Window <-> 1 Context, should be always true. assert( windowContext ); bool bFound = false; // Find the depth buffer from this window and remove it. DepthBufferMap::iterator itMap = mDepthBufferPool.begin(); DepthBufferMap::iterator enMap = mDepthBufferPool.end(); while( itMap != enMap && !bFound ) { DepthBufferVec::iterator itor = itMap->second.begin(); DepthBufferVec::iterator end = itMap->second.end(); while( itor != end ) { // A DepthBuffer with no depth & stencil pointers is a dummy one, // look for the one that matches the same GL context. GL3PlusDepthBuffer *depthBuffer = static_cast<GL3PlusDepthBuffer*>(*itor); GL3PlusContext *glContext = depthBuffer->getGLContext(); if( glContext == windowContext && (depthBuffer->getDepthBuffer() || depthBuffer->getStencilBuffer()) ) { bFound = true; delete *itor; itMap->second.erase( itor ); break; } ++itor; } ++itMap; } mRenderTargets.erase(i); delete pWin; break; } } } String GL3PlusRenderSystem::getErrorDescription(long errorNumber) const { return BLANKSTRING; } VertexElementType GL3PlusRenderSystem::getColourVertexElementType(void) const { return VET_COLOUR_ABGR; } void GL3PlusRenderSystem::_setWorldMatrix(const Matrix4 &m) { mWorldMatrix = m; } void GL3PlusRenderSystem::_setViewMatrix(const Matrix4 &m) { mViewMatrix = m; // Also mark clip planes dirty. if (!mClipPlanes.empty()) { mClipPlanesDirty = true; } } void GL3PlusRenderSystem::_setProjectionMatrix(const Matrix4 &m) { // Nothing to do but mark clip planes dirty. if (!mClipPlanes.empty()) mClipPlanesDirty = true; } void GL3PlusRenderSystem::_setPointParameters(Real size, bool attenuationEnabled, Real constant, Real linear, Real quadratic, Real minSize, Real maxSize) { if (attenuationEnabled) { // Point size is still calculated in pixels even when attenuation is // enabled, which is pretty awkward, since you typically want a viewport // independent size if you're looking for attenuation. // So, scale the point size up by viewport size (this is equivalent to // what D3D does as standard). size = size * mActiveViewport->getActualHeight(); // XXX: why do I need this for results to be consistent with D3D? // Equations are supposedly the same once you factor in vp height. // Real correction = 0.005; // Scaling required. // float val[4] = {1, 0, 0, 1}; // val[1] = linear * correction; // val[2] = quadratic * correction; // val[3] = 1; if (mCurrentCapabilities->hasCapability(RSC_VERTEX_PROGRAM)) { OGRE_CHECK_GL_ERROR(glEnable(GL_PROGRAM_POINT_SIZE)); } } else { if (mCurrentCapabilities->hasCapability(RSC_VERTEX_PROGRAM)) { OGRE_CHECK_GL_ERROR(glDisable(GL_PROGRAM_POINT_SIZE)); } } //FIXME Points do not seem affected by setting this. // OGRE_CHECK_GL_ERROR(glPointSize(size)); OGRE_CHECK_GL_ERROR(glPointSize(30.0)); //OGRE_CHECK_GL_ERROR(glPointParameterf(GL_POINT_FADE_THRESHOLD_SIZE, 64.0)); } void GL3PlusRenderSystem::_setPointSpritesEnabled(bool enabled) { // Point sprites are always on in OpenGL 3.2 and up. } void GL3PlusRenderSystem::_setTexture(size_t stage, bool enabled, Texture *texPtr) { GL3PlusTexture *tex = static_cast<GL3PlusTexture*>( texPtr ); if (!activateGLTextureUnit(stage)) return; if (enabled) { GLenum oldTexType = mTextureTypes[stage]; if ( tex ) { // Note used tex->touch(); mTextureTypes[stage] = tex->getGL3PlusTextureTarget(); // Store the number of mipmaps. mTextureMipmapCount = tex->getNumMipmaps(); } else // Assume 2D. mTextureTypes[stage] = GL_TEXTURE_2D; if( oldTexType != mTextureTypes[stage] ) OCGE( glBindTexture( oldTexType, 0 ) ); if( tex ) { bool isFsaa; GLuint id = tex->getGLID( isFsaa ); OGRE_CHECK_GL_ERROR(glBindTexture( isFsaa ? GL_TEXTURE_2D_MULTISAMPLE : mTextureTypes[stage], id )); } else { OGRE_CHECK_GL_ERROR(glBindTexture( mTextureTypes[stage], static_cast<GL3PlusTextureManager*>(mTextureManager)->getWarningTextureID() )); } } else { // Bind zero texture. OGRE_CHECK_GL_ERROR(glBindTexture(mTextureTypes[stage], 0)); } activateGLTextureUnit(0); } void GL3PlusRenderSystem::_setVertexTexture( size_t unit, const TexturePtr &tex ) { _setTexture(unit, true, tex.get()); } void GL3PlusRenderSystem::_setGeometryTexture( size_t unit, const TexturePtr &tex ) { _setTexture(unit, true, tex.get()); } void GL3PlusRenderSystem::_setTessellationHullTexture( size_t unit, const TexturePtr &tex ) { _setTexture(unit, true, tex.get()); } void GL3PlusRenderSystem::_setTessellationDomainTexture( size_t unit, const TexturePtr &tex ) { _setTexture(unit, true, tex.get()); } void GL3PlusRenderSystem::_setTextureCoordSet(size_t stage, size_t index) { mTextureCoordIndex[stage] = index; } void GL3PlusRenderSystem::setUavStartingSlot( uint32 startingSlot ) { if( startingSlot != mUavStartingSlot ) { for( uint32 i=0; i<64; ++i ) { if( !mUavs[i].texture.isNull() ) mUavs[i].dirty = true; } } RenderSystem::setUavStartingSlot( startingSlot ); } void GL3PlusRenderSystem::queueBindUAV( uint32 slot, TexturePtr texture, ResourceAccess::ResourceAccess access, int32 mipmapLevel, int32 textureArrayIndex, PixelFormat pixelFormat ) { assert( slot < 64 ); if( !mUavs[slot].buffer && mUavs[slot].texture.isNull() && texture.isNull() ) return; mUavs[slot].dirty = true; mUavs[slot].texture = texture; mUavs[slot].buffer = 0; if( !texture.isNull() ) { if( !(texture->getUsage() & TU_UAV) ) { OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Texture " + texture->getName() + " must have been created with TU_UAV to be bound as UAV", "GL3PlusRenderSystem::queueBindUAV" ); } bool isFsaa; if( pixelFormat == PF_UNKNOWN ) pixelFormat = texture->getFormat(); mUavs[slot].textureName = static_cast<GL3PlusTexture*>( texture.get() )->getGLID( isFsaa ); mUavs[slot].mipmap = mipmapLevel; mUavs[slot].isArrayTexture = texture->getTextureType() == TEX_TYPE_2D_ARRAY ? GL_TRUE : GL_FALSE; mUavs[slot].arrayIndex = textureArrayIndex; mUavs[slot].format = GL3PlusPixelUtil::getClosestGLImageInternalFormat( pixelFormat ); switch( access ) { case ResourceAccess::Read: mUavs[slot].access = GL_READ_ONLY; break; case ResourceAccess::Write: mUavs[slot].access = GL_WRITE_ONLY; break; case ResourceAccess::ReadWrite: mUavs[slot].access = GL_READ_WRITE; break; default: OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Invalid ResourceAccess parameter '" + StringConverter::toString( access ) + "'", "GL3PlusRenderSystem::queueBindUAV" ); break; } } mMaxModifiedUavPlusOne = std::max( mMaxModifiedUavPlusOne, static_cast<uint8>( slot + 1 ) ); } void GL3PlusRenderSystem::queueBindUAV( uint32 slot, UavBufferPacked *buffer, ResourceAccess::ResourceAccess access, size_t offset, size_t sizeBytes ) { assert( slot < 64 ); if( mUavs[slot].texture.isNull() && !mUavs[slot].buffer && !buffer ) return; mUavs[slot].dirty = true; mUavs[slot].buffer = buffer; mUavs[slot].texture.setNull(); if( buffer ) { mUavs[slot].offset = offset; mUavs[slot].sizeBytes = sizeBytes; } mMaxModifiedUavPlusOne = std::max( mMaxModifiedUavPlusOne, static_cast<uint8>( slot + 1 ) ); } void GL3PlusRenderSystem::clearUAVs(void) { for( size_t i=0; i<64; ++i ) { if( !mUavs[i].texture.isNull() ) { mUavs[i].dirty = true; mUavs[i].buffer = 0; mUavs[i].texture.setNull(); mMaxModifiedUavPlusOne = i + 1; } } } void GL3PlusRenderSystem::flushUAVs(void) { for( uint32 i=0; i<mMaxModifiedUavPlusOne; ++i ) { if( mUavs[i].dirty ) { if( !mUavs[i].texture.isNull() ) { OCGE( glBindImageTexture( mUavStartingSlot + i, mUavs[i].textureName, mUavs[i].mipmap, mUavs[i].isArrayTexture, mUavs[i].arrayIndex, mUavs[i].access, mUavs[i].format) ); } else if( mUavs[i].buffer ) { //bindBufferCS binds it to all stages in GL, so this will do. mUavs[i].buffer->bindBufferCS( mUavStartingSlot + i, mUavs[i].offset, mUavs[i].sizeBytes ); } else { OCGE( glBindImageTexture( mUavStartingSlot + i, 0, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_R32UI ) ); OCGE( glBindBufferRange( GL_SHADER_STORAGE_BUFFER, mUavStartingSlot + i, 0, 0, 0 ) ); } mUavs[i].dirty = false; } } mMaxModifiedUavPlusOne = 0; } void GL3PlusRenderSystem::_bindTextureUavCS( uint32 slot, Texture *texture, ResourceAccess::ResourceAccess _access, int32 mipmapLevel, int32 textureArrayIndex, PixelFormat pixelFormat ) { //Tag as dirty so next flushUAVs will get called when regular rendering resumes. mMaxModifiedUavPlusOne = std::max( static_cast<uint8>(mUavStartingSlot + slot + 1u), mMaxModifiedUavPlusOne ); mUavs[mUavStartingSlot + slot].dirty = true; if( texture ) { GLenum access; switch( _access ) { case ResourceAccess::Read: access = GL_READ_ONLY; break; case ResourceAccess::Write: access = GL_WRITE_ONLY; break; case ResourceAccess::ReadWrite: access = GL_READ_WRITE; break; default: OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Invalid ResourceAccess parameter '" + StringConverter::toString( _access ) + "'", "GL3PlusRenderSystem::_bindTextureUavCS" ); break; } bool isFsaa; const GLuint textureName = static_cast<GL3PlusTexture*>( texture )->getGLID( isFsaa ); const GLboolean isArrayTexture = texture->getTextureType() == TEX_TYPE_2D_ARRAY ? GL_TRUE : GL_FALSE; const GLenum format = GL3PlusPixelUtil::getClosestGLImageInternalFormat( pixelFormat ); OCGE( glBindImageTexture( slot, textureName, mipmapLevel, isArrayTexture, textureArrayIndex, access, format ) ); } else { glBindImageTexture( slot, 0, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_R32UI ); } } void GL3PlusRenderSystem::_setTextureCS( uint32 slot, bool enabled, Texture *texPtr ) { this->_setTexture( slot, enabled, texPtr ); } void GL3PlusRenderSystem::_setHlmsSamplerblockCS( uint8 texUnit, const HlmsSamplerblock *samplerblock ) { this->_setHlmsSamplerblock( texUnit, samplerblock ); } GLint GL3PlusRenderSystem::getTextureAddressingMode(TextureAddressingMode tam) const { switch (tam) { default: case TAM_WRAP: return GL_REPEAT; case TAM_MIRROR: return GL_MIRRORED_REPEAT; case TAM_CLAMP: return GL_CLAMP_TO_EDGE; case TAM_BORDER: return GL_CLAMP_TO_BORDER; } } GLenum GL3PlusRenderSystem::getBlendMode(SceneBlendFactor ogreBlend) { switch (ogreBlend) { case SBF_ONE: return GL_ONE; case SBF_ZERO: return GL_ZERO; case SBF_DEST_COLOUR: return GL_DST_COLOR; case SBF_SOURCE_COLOUR: return GL_SRC_COLOR; case SBF_ONE_MINUS_DEST_COLOUR: return GL_ONE_MINUS_DST_COLOR; case SBF_ONE_MINUS_SOURCE_COLOUR: return GL_ONE_MINUS_SRC_COLOR; case SBF_DEST_ALPHA: return GL_DST_ALPHA; case SBF_SOURCE_ALPHA: return GL_SRC_ALPHA; case SBF_ONE_MINUS_DEST_ALPHA: return GL_ONE_MINUS_DST_ALPHA; case SBF_ONE_MINUS_SOURCE_ALPHA: return GL_ONE_MINUS_SRC_ALPHA; }; // To keep compiler happy. return GL_ONE; } GLenum GL3PlusRenderSystem::getBlendOperation( SceneBlendOperation op ) { switch( op ) { case SBO_ADD: return GL_FUNC_ADD; case SBO_SUBTRACT: return GL_FUNC_SUBTRACT; case SBO_REVERSE_SUBTRACT: return GL_FUNC_REVERSE_SUBTRACT; case SBO_MIN: return GL_MIN; case SBO_MAX: return GL_MAX; } // To keep compiler happy. return GL_FUNC_ADD; } void GL3PlusRenderSystem::_setSceneBlending(SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendOperation op) { GLenum sourceBlend = getBlendMode(sourceFactor); GLenum destBlend = getBlendMode(destFactor); if(sourceFactor == SBF_ONE && destFactor == SBF_ZERO) { OGRE_CHECK_GL_ERROR(glDisable(GL_BLEND)); } else { OGRE_CHECK_GL_ERROR(glEnable(GL_BLEND)); OGRE_CHECK_GL_ERROR(glBlendFunc(sourceBlend, destBlend)); } GLint func = GL_FUNC_ADD; switch(op) { case SBO_ADD: func = GL_FUNC_ADD; break; case SBO_SUBTRACT: func = GL_FUNC_SUBTRACT; break; case SBO_REVERSE_SUBTRACT: func = GL_FUNC_REVERSE_SUBTRACT; break; case SBO_MIN: func = GL_MIN; break; case SBO_MAX: func = GL_MAX; break; } OGRE_CHECK_GL_ERROR(glBlendEquation(func)); } void GL3PlusRenderSystem::_setSeparateSceneBlending( SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendFactor sourceFactorAlpha, SceneBlendFactor destFactorAlpha, SceneBlendOperation op, SceneBlendOperation alphaOp ) { GLenum sourceBlend = getBlendMode(sourceFactor); GLenum destBlend = getBlendMode(destFactor); GLenum sourceBlendAlpha = getBlendMode(sourceFactorAlpha); GLenum destBlendAlpha = getBlendMode(destFactorAlpha); if (sourceFactor == SBF_ONE && destFactor == SBF_ZERO && sourceFactorAlpha == SBF_ONE && destFactorAlpha == SBF_ZERO) { OGRE_CHECK_GL_ERROR(glDisable(GL_BLEND)); } else { OGRE_CHECK_GL_ERROR(glEnable(GL_BLEND)); OGRE_CHECK_GL_ERROR(glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha)); } GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD; switch(op) { case SBO_ADD: func = GL_FUNC_ADD; break; case SBO_SUBTRACT: func = GL_FUNC_SUBTRACT; break; case SBO_REVERSE_SUBTRACT: func = GL_FUNC_REVERSE_SUBTRACT; break; case SBO_MIN: func = GL_MIN; break; case SBO_MAX: func = GL_MAX; break; } switch(alphaOp) { case SBO_ADD: alphaFunc = GL_FUNC_ADD; break; case SBO_SUBTRACT: alphaFunc = GL_FUNC_SUBTRACT; break; case SBO_REVERSE_SUBTRACT: alphaFunc = GL_FUNC_REVERSE_SUBTRACT; break; case SBO_MIN: alphaFunc = GL_MIN; break; case SBO_MAX: alphaFunc = GL_MAX; break; } OGRE_CHECK_GL_ERROR(glBlendEquationSeparate(func, alphaFunc)); } void GL3PlusRenderSystem::_setViewport(Viewport *vp) { // Check if viewport is different if (!vp) { mActiveViewport = NULL; _setRenderTarget(NULL, VP_RTT_COLOUR_WRITE); } else if (vp != mActiveViewport || vp->_isUpdated()) { RenderTarget* target; target = vp->getTarget(); _setRenderTarget(target, vp->getViewportRenderTargetFlags()); mActiveViewport = vp; GLsizei x, y, w, h; // Calculate the "lower-left" corner of the viewport w = vp->getActualWidth(); h = vp->getActualHeight(); x = vp->getActualLeft(); y = vp->getActualTop(); if (target && !target->requiresTextureFlipping()) { // Convert "upper-left" corner to "lower-left" y = target->getHeight() - h - y; } OGRE_CHECK_GL_ERROR(glViewport(x, y, w, h)); w = vp->getScissorActualWidth(); h = vp->getScissorActualHeight(); x = vp->getScissorActualLeft(); y = vp->getScissorActualTop(); if (target && !target->requiresTextureFlipping()) { // Convert "upper-left" corner to "lower-left" y = target->getHeight() - h - y; } // Configure the viewport clipping OGRE_CHECK_GL_ERROR(glScissor(x, y, w, h)); vp->_clearUpdatedFlag(); } else if( mMaxModifiedUavPlusOne ) { flushUAVs(); } } void GL3PlusRenderSystem::_resourceTransitionCreated( ResourceTransition *resTransition ) { assert( sizeof(void*) >= sizeof(GLbitfield) ); assert( (resTransition->readBarrierBits || resTransition->writeBarrierBits) && "A zero-bit memory barrier is invalid!" ); GLbitfield barriers = 0; //TODO: //GL_QUERY_BUFFER_BARRIER_BIT is nearly impossible to determine //specifically //Should be used in all barriers? Since we don't yet support them, //we don't include it in case it brings performance down. //Or should we use 'All' instead for these edge cases? if( resTransition->readBarrierBits & ReadBarrier::CpuRead || resTransition->writeBarrierBits & WriteBarrier::CpuWrite ) { barriers |= GL_PIXEL_BUFFER_BARRIER_BIT|GL_TEXTURE_UPDATE_BARRIER_BIT| GL_BUFFER_UPDATE_BARRIER_BIT|GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT; } if( resTransition->readBarrierBits & ReadBarrier::Indirect ) barriers |= GL_COMMAND_BARRIER_BIT; if( resTransition->readBarrierBits & ReadBarrier::VertexBuffer ) barriers |= GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT|GL_TRANSFORM_FEEDBACK_BARRIER_BIT; if( resTransition->readBarrierBits & ReadBarrier::IndexBuffer ) barriers |= GL_ELEMENT_ARRAY_BARRIER_BIT; if( resTransition->readBarrierBits & ReadBarrier::ConstBuffer ) barriers |= GL_UNIFORM_BARRIER_BIT; if( resTransition->readBarrierBits & ReadBarrier::Texture ) barriers |= GL_TEXTURE_FETCH_BARRIER_BIT; if( resTransition->readBarrierBits & ReadBarrier::Uav || resTransition->writeBarrierBits & WriteBarrier::Uav ) { barriers |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT|GL_SHADER_STORAGE_BARRIER_BIT| GL_ATOMIC_COUNTER_BARRIER_BIT; } if( resTransition->readBarrierBits & (ReadBarrier::RenderTarget|ReadBarrier::DepthStencil) || resTransition->writeBarrierBits & (WriteBarrier::RenderTarget|WriteBarrier::DepthStencil) ) { barriers |= GL_FRAMEBUFFER_BARRIER_BIT; } if( resTransition->readBarrierBits == ReadBarrier::All || resTransition->writeBarrierBits == WriteBarrier::All ) { barriers = GL_ALL_BARRIER_BITS; } resTransition->mRsData = reinterpret_cast<void*>( barriers ); } void GL3PlusRenderSystem::_resourceTransitionDestroyed( ResourceTransition *resTransition ) { assert( resTransition->mRsData ); //A zero-bit memory barrier is invalid resTransition->mRsData = 0; } void GL3PlusRenderSystem::_executeResourceTransition( ResourceTransition *resTransition ) { if( !glMemoryBarrier ) return; GLbitfield barriers = static_cast<GLbitfield>( reinterpret_cast<intptr_t>( resTransition->mRsData ) ); assert( barriers && "A zero-bit memory barrier is invalid" ); glMemoryBarrier( barriers ); } void GL3PlusRenderSystem::_hlmsPipelineStateObjectCreated( HlmsPso *newBlock ) { GL3PlusHlmsPso *pso = new GL3PlusHlmsPso(); memset( pso, 0, sizeof(GL3PlusHlmsPso) ); // // Macroblock stuff // pso->depthWrite = newBlock->macroblock->mDepthWrite ? GL_TRUE : GL_FALSE; pso->depthFunc = convertCompareFunction( newBlock->macroblock->mDepthFunc ); switch( newBlock->macroblock->mCullMode ) { case CULL_NONE: pso->cullMode = 0; break; default: case CULL_CLOCKWISE: pso->cullMode = GL_BACK; break; case CULL_ANTICLOCKWISE: pso->cullMode = GL_FRONT; break; } switch( newBlock->macroblock->mPolygonMode ) { case PM_POINTS: //pso->polygonMode = GL_POINTS; pso->polygonMode = GL_POINT; break; case PM_WIREFRAME: //pso->polygonMode = GL_LINE_STRIP; pso->polygonMode = GL_LINE; break; default: case PM_SOLID: pso->polygonMode = GL_FILL; break; } // // Blendblock stuff // pso->enableAlphaBlend = newBlock->blendblock->mSourceBlendFactor != SBF_ONE || newBlock->blendblock->mDestBlendFactor != SBF_ZERO; if( newBlock->blendblock->mSeparateBlend ) { pso->enableAlphaBlend |= newBlock->blendblock->mSourceBlendFactorAlpha != SBF_ONE || newBlock->blendblock->mDestBlendFactorAlpha != SBF_ZERO; } pso->sourceBlend = getBlendMode( newBlock->blendblock->mSourceBlendFactor ); pso->destBlend = getBlendMode( newBlock->blendblock->mDestBlendFactor ); pso->sourceBlendAlpha = getBlendMode( newBlock->blendblock->mSourceBlendFactorAlpha ); pso->destBlendAlpha = getBlendMode( newBlock->blendblock->mDestBlendFactorAlpha ); pso->blendFunc = getBlendOperation( newBlock->blendblock->mBlendOperation ); pso->blendFuncAlpha = getBlendOperation( newBlock->blendblock->mBlendOperationAlpha ); // // Shader stuff // if( !newBlock->vertexShader.isNull() ) { pso->vertexShader = static_cast<GLSLShader*>( newBlock->vertexShader-> _getBindingDelegate() ); } if( !newBlock->geometryShader.isNull() ) { pso->geometryShader = static_cast<GLSLShader*>( newBlock->geometryShader-> _getBindingDelegate() ); } if( !newBlock->tesselationHullShader.isNull() ) { pso->hullShader = static_cast<GLSLShader*>( newBlock->tesselationHullShader-> _getBindingDelegate() ); } if( !newBlock->tesselationDomainShader.isNull() ) { pso->domainShader = static_cast<GLSLShader*>( newBlock->tesselationDomainShader-> _getBindingDelegate() ); } if( !newBlock->pixelShader.isNull() ) { pso->pixelShader = static_cast<GLSLShader*>( newBlock->pixelShader-> _getBindingDelegate() ); } newBlock->rsData = pso; } void GL3PlusRenderSystem::_hlmsPipelineStateObjectDestroyed( HlmsPso *pso ) { GL3PlusHlmsPso *glPso = reinterpret_cast<GL3PlusHlmsPso*>(pso->rsData); delete glPso; pso->rsData = 0; } void GL3PlusRenderSystem::_hlmsMacroblockCreated( HlmsMacroblock *newBlock ) { //Set it to non-zero to get the assert in _setHlmsBlendblock //to work correctly (which is a very useful assert) newBlock->mRsData = reinterpret_cast<void*>( 1 ); } void GL3PlusRenderSystem::_hlmsMacroblockDestroyed( HlmsMacroblock *block ) { block->mRsData = 0; } void GL3PlusRenderSystem::_hlmsBlendblockCreated( HlmsBlendblock *newBlock ) { //Set it to non-zero to get the assert in _setHlmsBlendblock //to work correctly (which is a very useful assert) newBlock->mRsData = reinterpret_cast<void*>( 1 ); } void GL3PlusRenderSystem::_hlmsBlendblockDestroyed( HlmsBlendblock *block ) { block->mRsData = 0; } void GL3PlusRenderSystem::_hlmsSamplerblockCreated( HlmsSamplerblock *newBlock ) { GLuint samplerName; glGenSamplers( 1, &samplerName ); GLint minFilter, magFilter; switch( newBlock->mMinFilter ) { case FO_ANISOTROPIC: case FO_LINEAR: switch( newBlock->mMipFilter ) { case FO_ANISOTROPIC: case FO_LINEAR: // linear min, linear mip minFilter = GL_LINEAR_MIPMAP_LINEAR; break; case FO_POINT: // linear min, point mip minFilter = GL_LINEAR_MIPMAP_NEAREST; break; case FO_NONE: // linear min, no mip minFilter = GL_LINEAR; break; } break; case FO_POINT: case FO_NONE: switch( newBlock->mMipFilter ) { case FO_ANISOTROPIC: case FO_LINEAR: // nearest min, linear mip minFilter = GL_NEAREST_MIPMAP_LINEAR; break; case FO_POINT: // nearest min, point mip minFilter = GL_NEAREST_MIPMAP_NEAREST; break; case FO_NONE: // nearest min, no mip minFilter = GL_NEAREST; break; } break; } magFilter = newBlock->mMagFilter <= FO_POINT ? GL_NEAREST : GL_LINEAR; OCGE( glSamplerParameteri( samplerName, GL_TEXTURE_MIN_FILTER, minFilter ) ); OCGE( glSamplerParameteri( samplerName, GL_TEXTURE_MAG_FILTER, magFilter ) ); OCGE( glSamplerParameteri( samplerName, GL_TEXTURE_WRAP_S, getTextureAddressingMode( newBlock->mU ) ) ); OCGE( glSamplerParameteri( samplerName, GL_TEXTURE_WRAP_T, getTextureAddressingMode( newBlock->mV ) ) ); OCGE( glSamplerParameteri( samplerName, GL_TEXTURE_WRAP_R, getTextureAddressingMode( newBlock->mW ) ) ); float borderColour[4] = { (float)newBlock->mBorderColour.r, (float)newBlock->mBorderColour.g, (float)newBlock->mBorderColour.b, (float)newBlock->mBorderColour.a }; OCGE( glSamplerParameterfv( samplerName, GL_TEXTURE_BORDER_COLOR, borderColour ) ); OCGE( glSamplerParameterf( samplerName, GL_TEXTURE_LOD_BIAS, newBlock->mMipLodBias ) ); OCGE( glSamplerParameterf( samplerName, GL_TEXTURE_MIN_LOD, newBlock->mMinLod ) ); OCGE( glSamplerParameterf( samplerName, GL_TEXTURE_MAX_LOD, newBlock->mMaxLod ) ); if( newBlock->mCompareFunction != NUM_COMPARE_FUNCTIONS ) { OCGE( glSamplerParameteri( samplerName, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE ) ); OCGE( glSamplerParameterf( samplerName, GL_TEXTURE_COMPARE_FUNC, convertCompareFunction( newBlock->mCompareFunction ) ) ); } if( mCurrentCapabilities->hasCapability(RSC_ANISOTROPY) ) { OCGE( glSamplerParameterf( samplerName, GL_TEXTURE_MAX_ANISOTROPY_EXT, newBlock->mMaxAnisotropy ) ); } newBlock->mRsData = reinterpret_cast<void*>( samplerName ); /*GL3PlusHlmsSamplerblock *glSamplerblock = new GL3PlusHlmsSamplerblock(); switch( newBlock->mMinFilter ) { case FO_ANISOTROPIC: case FO_LINEAR: switch( newBlock->mMipFilter ) { case FO_ANISOTROPIC: case FO_LINEAR: // linear min, linear mip glSamplerblock->mMinFilter = GL_LINEAR_MIPMAP_LINEAR; break; case FO_POINT: // linear min, point mip glSamplerblock->mMinFilter = GL_LINEAR_MIPMAP_NEAREST; break; case FO_NONE: // linear min, no mip glSamplerblock->mMinFilter = GL_LINEAR; break; } break; case FO_POINT: case FO_NONE: switch( newBlock->mMipFilter ) { case FO_ANISOTROPIC: case FO_LINEAR: // nearest min, linear mip glSamplerblock->mMinFilter = GL_NEAREST_MIPMAP_LINEAR; break; case FO_POINT: // nearest min, point mip glSamplerblock->mMinFilter = GL_NEAREST_MIPMAP_NEAREST; break; case FO_NONE: // nearest min, no mip glSamplerblock->mMinFilter = GL_NEAREST; break; } break; } glSamplerblock->mMagFilter = newBlock->mMagFilter <= FO_POINT ? GL_NEAREST : GL_LINEAR; glSamplerblock->mU = getTextureAddressingMode( newBlock->mU ); glSamplerblock->mV = getTextureAddressingMode( newBlock->mV ); glSamplerblock->mW = getTextureAddressingMode( newBlock->mW ); glSamplerblock->mAnisotropy = std::min( newBlock->mMaxAnisotropy, mLargestSupportedAnisotrop ); newBlock->mRsData = glSamplerblock;*/ } void GL3PlusRenderSystem::_hlmsSamplerblockDestroyed( HlmsSamplerblock *block ) { GLuint samplerName = static_cast<GLuint>( reinterpret_cast<intptr_t>( block->mRsData ) ); glDeleteSamplers( 1, &samplerName ); } void GL3PlusRenderSystem::_setHlmsMacroblock( const HlmsMacroblock *macroblock, const GL3PlusHlmsPso *pso ) { if( macroblock->mDepthCheck ) { OCGE( glEnable( GL_DEPTH_TEST ) ); } else { OCGE( glDisable( GL_DEPTH_TEST ) ); } OCGE( glDepthMask( pso->depthWrite ) ); OCGE( glDepthFunc( pso->depthFunc ) ); _setDepthBias( macroblock->mDepthBiasConstant, macroblock->mDepthBiasSlopeScale ); //Cull mode if( pso->cullMode == 0 ) { OCGE( glDisable( GL_CULL_FACE ) ); } else { OCGE( glEnable( GL_CULL_FACE ) ); OCGE( glCullFace( pso->cullMode ) ); } //Polygon mode OCGE( glPolygonMode( GL_FRONT_AND_BACK, pso->polygonMode ) ); if( macroblock->mScissorTestEnabled ) { OCGE( glEnable(GL_SCISSOR_TEST) ); } else { OCGE( glDisable(GL_SCISSOR_TEST) ); } mDepthWrite = macroblock->mDepthWrite; mScissorsEnabled = macroblock->mScissorTestEnabled; } void GL3PlusRenderSystem::_setHlmsBlendblock( const HlmsBlendblock *blendblock, const GL3PlusHlmsPso *pso ) { if( pso->enableAlphaBlend ) { OCGE( glEnable(GL_BLEND) ); if( blendblock->mSeparateBlend ) { OCGE( glBlendFuncSeparate( pso->sourceBlend, pso->destBlend, pso->sourceBlendAlpha, pso->destBlendAlpha ) ); OCGE( glBlendEquationSeparate( pso->blendFunc, pso->blendFuncAlpha ) ); } else { OCGE( glBlendFunc( pso->sourceBlend, pso->destBlend ) ); OCGE( glBlendEquation( pso->blendFunc ) ); } } else { OCGE( glDisable(GL_BLEND) ); } if( blendblock->mAlphaToCoverageEnabled ) { OCGE( glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) ); } else { OCGE( glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE) ); } if( mBlendChannelMask != blendblock->mBlendChannelMask ) { GLboolean r = (blendblock->mBlendChannelMask & HlmsBlendblock::BlendChannelRed) != 0; GLboolean g = (blendblock->mBlendChannelMask & HlmsBlendblock::BlendChannelGreen) != 0; GLboolean b = (blendblock->mBlendChannelMask & HlmsBlendblock::BlendChannelBlue) != 0; GLboolean a = (blendblock->mBlendChannelMask & HlmsBlendblock::BlendChannelAlpha) != 0; OCGE( glColorMask( r, g, b, a ) ); mBlendChannelMask = blendblock->mBlendChannelMask; } } void GL3PlusRenderSystem::_setHlmsSamplerblock( uint8 texUnit, const HlmsSamplerblock *samplerblock ) { assert( (!samplerblock || samplerblock->mRsData) && "The block must have been created via HlmsManager::getSamplerblock!" ); if( !samplerblock ) { glBindSampler( texUnit, 0 ); } else { glBindSampler( texUnit, static_cast<GLuint>( reinterpret_cast<intptr_t>( samplerblock->mRsData ) ) ); } /*if (!activateGLTextureUnit(texUnit)) return; GL3PlusHlmsSamplerblock *glSamplerblock = reinterpret_cast<GL3PlusHlmsSamplerblock*>( samplerblock->mRsData ); OGRE_CHECK_GL_ERROR(glTexParameteri( mTextureTypes[unit], GL_TEXTURE_MIN_FILTER, glSamplerblock->mMinFilter) ); OGRE_CHECK_GL_ERROR(glTexParameteri( mTextureTypes[unit], GL_TEXTURE_MAG_FILTER, glSamplerblock->mMagFilter)); OGRE_CHECK_GL_ERROR(glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_S, glSamplerblock->mU )); OGRE_CHECK_GL_ERROR(glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_T, glSamplerblock->mV )); OGRE_CHECK_GL_ERROR(glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_R, glSamplerblock->mW )); OGRE_CHECK_GL_ERROR(glTexParameterf( mTextureTypes[stage], GL_TEXTURE_LOD_BIAS, samplerblock->mMipLodBias )); OGRE_CHECK_GL_ERROR(glTexParameterfv( mTextureTypes[stage], GL_TEXTURE_BORDER_COLOR, reinterpret_cast<GLfloat*>( &samplerblock->mBorderColour ) )); OGRE_CHECK_GL_ERROR(glTexParameterf( mTextureTypes[stage], GL_TEXTURE_MIN_LOD, samplerblock->mMinLod )); OGRE_CHECK_GL_ERROR(glTexParameterf( mTextureTypes[stage], GL_TEXTURE_MAX_LOD, samplerblock->mMaxLod )); activateGLTextureUnit(0);*/ } void GL3PlusRenderSystem::_setPipelineStateObject( const HlmsPso *pso ) { //Disable previous state GLSLShader::unbindAll(); RenderSystem::_setPipelineStateObject( pso ); uint8 newClipDistances = 0; if( pso ) newClipDistances = pso->clipDistances; if( mClipDistances != newClipDistances ) { for( size_t i=0; i<8u; ++i ) { const uint8 bitFlag = 1u << i; bool oldClipSet = (mClipDistances & bitFlag) != 0; bool newClipSet = (newClipDistances & bitFlag) != 0; if( oldClipSet != newClipSet ) { if( newClipSet ) glEnable( GL_CLIP_DISTANCE0 + i ); else glDisable( GL_CLIP_DISTANCE0 + i ); } } mClipDistances = newClipDistances; } mUseAdjacency = false; mPso = 0; if( !pso ) return; //Set new state mPso = reinterpret_cast<GL3PlusHlmsPso*>( pso->rsData ); _setHlmsMacroblock( pso->macroblock, mPso ); _setHlmsBlendblock( pso->blendblock, mPso ); if( mPso->vertexShader ) { mPso->vertexShader->bind(); mActiveVertexGpuProgramParameters = mPso->vertexShader->getDefaultParameters(); mVertexProgramBound = true; } if( mPso->geometryShader ) { mPso->geometryShader->bind(); mActiveGeometryGpuProgramParameters = mPso->geometryShader->getDefaultParameters(); mGeometryProgramBound = true; mUseAdjacency = mPso->geometryShader->isAdjacencyInfoRequired(); } if( mPso->hullShader ) { mPso->hullShader->bind(); mActiveTessellationHullGpuProgramParameters = mPso->hullShader->getDefaultParameters(); mTessellationHullProgramBound = true; } if( mPso->domainShader ) { mPso->domainShader->bind(); mActiveTessellationDomainGpuProgramParameters = mPso->domainShader->getDefaultParameters(); mTessellationDomainProgramBound = true; } if( mPso->pixelShader ) { mPso->pixelShader->bind(); mActiveFragmentGpuProgramParameters = mPso->pixelShader->getDefaultParameters(); mFragmentProgramBound = true; } GLSLSeparableProgramManager* separableProgramMgr = GLSLSeparableProgramManager::getSingletonPtr(); if( separableProgramMgr ) { GLSLSeparableProgram* separableProgram = separableProgramMgr->getCurrentSeparableProgram(); if (separableProgram) separableProgram->activate(); } else { GLSLMonolithicProgramManager::getSingleton().getActiveMonolithicProgram(); } } void GL3PlusRenderSystem::_setComputePso( const HlmsComputePso *pso ) { GLSLShader *newComputeShader = 0; if( pso ) { newComputeShader = reinterpret_cast<GLSLShader*>( pso->rsData ); if( mCurrentComputeShader == newComputeShader ) return; } //Disable previous state GLSLShader::unbindAll(); RenderSystem::_setPipelineStateObject( (HlmsPso*)0 ); mUseAdjacency = false; mPso = 0; mCurrentComputeShader = 0; if( !pso ) return; mCurrentComputeShader = newComputeShader; mCurrentComputeShader->bind(); mActiveComputeGpuProgramParameters = pso->computeParams; mComputeProgramBound = true; GLSLSeparableProgramManager* separableProgramMgr = GLSLSeparableProgramManager::getSingletonPtr(); if( separableProgramMgr ) { GLSLSeparableProgram* separableProgram = separableProgramMgr->getCurrentSeparableProgram(); if (separableProgram) separableProgram->activate(); } else { GLSLMonolithicProgramManager::getSingleton().getActiveMonolithicProgram(); } } void GL3PlusRenderSystem::_setIndirectBuffer( IndirectBufferPacked *indirectBuffer ) { if( mVaoManager->supportsIndirectBuffers() ) { if( indirectBuffer ) { GL3PlusBufferInterface *bufferInterface = static_cast<GL3PlusBufferInterface*>( indirectBuffer->getBufferInterface() ); OCGE( glBindBuffer( GL_DRAW_INDIRECT_BUFFER, bufferInterface->getVboName() ) ); } else { OCGE( glBindBuffer( GL_DRAW_INDIRECT_BUFFER, 0 ) ); } } else { if( indirectBuffer ) mSwIndirectBufferPtr = indirectBuffer->getSwBufferPtr(); else mSwIndirectBufferPtr = 0; } } void GL3PlusRenderSystem::_hlmsComputePipelineStateObjectCreated( HlmsComputePso *newPso ) { newPso->rsData = reinterpret_cast<void*>( static_cast<GLSLShader*>( newPso->computeShader->_getBindingDelegate() ) ); } void GL3PlusRenderSystem::_hlmsComputePipelineStateObjectDestroyed( HlmsComputePso *newPso ) { newPso->rsData = 0; } void GL3PlusRenderSystem::_beginFrame(void) { } void GL3PlusRenderSystem::_endFrame(void) { OGRE_CHECK_GL_ERROR(glDisable(GL_DEPTH_CLAMP)); // unbind PSO programs at end of frame // this is mostly to avoid holding bound programs that might get deleted // outside via the resource manager _setPipelineStateObject( 0 ); _setComputePso( 0 ); glBindProgramPipeline( 0 ); } void GL3PlusRenderSystem::_setDepthBias(float constantBias, float slopeScaleBias) { //FIXME glPolygonOffset currently is buggy in GL3+ RS but not GL RS. if (constantBias != 0 || slopeScaleBias != 0) { OGRE_CHECK_GL_ERROR(glEnable(GL_POLYGON_OFFSET_FILL)); OGRE_CHECK_GL_ERROR(glEnable(GL_POLYGON_OFFSET_POINT)); OGRE_CHECK_GL_ERROR(glEnable(GL_POLYGON_OFFSET_LINE)); OGRE_CHECK_GL_ERROR(glPolygonOffset(-slopeScaleBias, -constantBias)); } else { OGRE_CHECK_GL_ERROR(glDisable(GL_POLYGON_OFFSET_FILL)); OGRE_CHECK_GL_ERROR(glDisable(GL_POLYGON_OFFSET_POINT)); OGRE_CHECK_GL_ERROR(glDisable(GL_POLYGON_OFFSET_LINE)); } } void GL3PlusRenderSystem::_convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest, bool forGpuProgram) { // no any conversion request for OpenGL dest = matrix; } void GL3PlusRenderSystem::_makeProjectionMatrix(const Radian& fovy, Real aspect, Real nearPlane, Real farPlane, Matrix4& dest, bool forGpuProgram) { Radian thetaY(fovy / 2.0f); Real tanThetaY = Math::Tan(thetaY); // Calc matrix elements Real w = (1.0f / tanThetaY) / aspect; Real h = 1.0f / tanThetaY; Real q, qn; if (farPlane == 0) { // Infinite far plane q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1; qn = nearPlane * (Frustum::INFINITE_FAR_PLANE_ADJUST - 2); } else { q = -(farPlane + nearPlane) / (farPlane - nearPlane); qn = -2 * (farPlane * nearPlane) / (farPlane - nearPlane); } // NB This creates Z in range [-1,1] // // [ w 0 0 0 ] // [ 0 h 0 0 ] // [ 0 0 q qn ] // [ 0 0 -1 0 ] dest = Matrix4::ZERO; dest[0][0] = w; dest[1][1] = h; dest[2][2] = q; dest[2][3] = qn; dest[3][2] = -1; } void GL3PlusRenderSystem::_makeProjectionMatrix(Real left, Real right, Real bottom, Real top, Real nearPlane, Real farPlane, Matrix4& dest, bool forGpuProgram) { Real width = right - left; Real height = top - bottom; Real q, qn; if (farPlane == 0) { // Infinite far plane q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1; qn = nearPlane * (Frustum::INFINITE_FAR_PLANE_ADJUST - 2); } else { q = -(farPlane + nearPlane) / (farPlane - nearPlane); qn = -2 * (farPlane * nearPlane) / (farPlane - nearPlane); } dest = Matrix4::ZERO; dest[0][0] = 2 * nearPlane / width; dest[0][2] = (right+left) / width; dest[1][1] = 2 * nearPlane / height; dest[1][2] = (top+bottom) / height; dest[2][2] = q; dest[2][3] = qn; dest[3][2] = -1; } void GL3PlusRenderSystem::_makeOrthoMatrix(const Radian& fovy, Real aspect, Real nearPlane, Real farPlane, Matrix4& dest, bool forGpuProgram) { Radian thetaY(fovy / 2.0f); Real tanThetaY = Math::Tan(thetaY); // Real thetaX = thetaY * aspect; Real tanThetaX = tanThetaY * aspect; // Math::Tan(thetaX); Real half_w = tanThetaX * nearPlane; Real half_h = tanThetaY * nearPlane; Real iw = 1.0 / half_w; Real ih = 1.0 / half_h; Real q; if (farPlane == 0) { q = 0; } else { q = 2.0 / (farPlane - nearPlane); } dest = Matrix4::ZERO; dest[0][0] = iw; dest[1][1] = ih; dest[2][2] = -q; dest[2][3] = -(farPlane + nearPlane) / (farPlane - nearPlane); dest[3][3] = 1; } void GL3PlusRenderSystem::_applyObliqueDepthProjection(Matrix4& matrix, const Plane& plane, bool forGpuProgram) { // Thanks to Eric Lenyel for posting this calculation at www.terathon.com // Calculate the clip-space corner point opposite the clipping plane // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and // transform it into camera space by multiplying it // by the inverse of the projection matrix Vector4 q; q.x = (Math::Sign(plane.normal.x) + matrix[0][2]) / matrix[0][0]; q.y = (Math::Sign(plane.normal.y) + matrix[1][2]) / matrix[1][1]; q.z = -1.0F; q.w = (1.0F + matrix[2][2]) / matrix[2][3]; // Calculate the scaled plane vector Vector4 clipPlane4d(plane.normal.x, plane.normal.y, plane.normal.z, plane.d); Vector4 c = clipPlane4d * (2.0F / (clipPlane4d.dotProduct(q))); // Replace the third row of the projection matrix matrix[2][0] = c.x; matrix[2][1] = c.y; matrix[2][2] = c.z + 1.0F; matrix[2][3] = c.w; } HardwareOcclusionQuery* GL3PlusRenderSystem::createHardwareOcclusionQuery(void) { GL3PlusHardwareOcclusionQuery* ret = new GL3PlusHardwareOcclusionQuery(); mHwOcclusionQueries.push_back(ret); return ret; } void GL3PlusRenderSystem::setStencilBufferParams( uint32 refValue, const StencilParams &stencilParams ) { RenderSystem::setStencilBufferParams( refValue, stencilParams ); if( mStencilParams.enabled ) { OCGE( glEnable(GL_STENCIL_TEST) ); OCGE( glStencilMask( mStencilParams.writeMask ) ); //OCGE( glStencilMaskSeparate( GL_BACK, mStencilParams.writeMask ) ); //OCGE( glStencilMaskSeparate( GL_FRONT, mStencilParams.writeMask ) ); OCGE( glStencilFuncSeparate( GL_BACK, convertCompareFunction( stencilParams.stencilBack.compareOp ), refValue, stencilParams.readMask ) ); OCGE( glStencilOpSeparate( GL_BACK, convertStencilOp( stencilParams.stencilBack.stencilFailOp ), convertStencilOp( stencilParams.stencilBack.stencilDepthFailOp ), convertStencilOp( stencilParams.stencilBack.stencilPassOp ) ) ); OCGE( glStencilFuncSeparate( GL_FRONT, convertCompareFunction( stencilParams.stencilFront.compareOp ), refValue, stencilParams.readMask ) ); OCGE( glStencilOpSeparate( GL_FRONT, convertStencilOp( stencilParams.stencilFront.stencilFailOp ), convertStencilOp( stencilParams.stencilFront.stencilDepthFailOp ), convertStencilOp( stencilParams.stencilFront.stencilPassOp ) ) ); } else { OCGE( glDisable(GL_STENCIL_TEST) ); } } GLint GL3PlusRenderSystem::getCombinedMinMipFilter(void) const { switch(mMinFilter) { case FO_ANISOTROPIC: case FO_LINEAR: switch (mMipFilter) { case FO_ANISOTROPIC: case FO_LINEAR: // linear min, linear mip return GL_LINEAR_MIPMAP_LINEAR; case FO_POINT: // linear min, point mip return GL_LINEAR_MIPMAP_NEAREST; case FO_NONE: // linear min, no mip return GL_LINEAR; } break; case FO_POINT: case FO_NONE: switch (mMipFilter) { case FO_ANISOTROPIC: case FO_LINEAR: // nearest min, linear mip return GL_NEAREST_MIPMAP_LINEAR; case FO_POINT: // nearest min, point mip return GL_NEAREST_MIPMAP_NEAREST; case FO_NONE: // nearest min, no mip return GL_NEAREST; } break; } // should never get here return 0; } void GL3PlusRenderSystem::_render(const v1::RenderOperation& op) { // Call super class. RenderSystem::_render(op); // Create variables related to instancing. v1::HardwareVertexBufferSharedPtr globalInstanceVertexBuffer = getGlobalInstanceVertexBuffer(); v1::VertexDeclaration* globalVertexDeclaration = getGlobalInstanceVertexBufferVertexDeclaration(); bool hasInstanceData = (op.useGlobalInstancingVertexBufferIsAvailable && !globalInstanceVertexBuffer.isNull() && (globalVertexDeclaration != NULL)) || op.vertexData->vertexBufferBinding->getHasInstanceData(); size_t numberOfInstances = op.numberOfInstances; if (op.useGlobalInstancingVertexBufferIsAvailable) { numberOfInstances *= getGlobalNumberOfInstances(); } // Get vertex array organization. const v1::VertexDeclaration::VertexElementList& decl = op.vertexData->vertexDeclaration->getElements(); v1::VertexDeclaration::VertexElementList::const_iterator elemIter, elemEnd; elemEnd = decl.end(); // Bind VAO (set of per-vertex attributes: position, normal, etc.). bool updateVAO = true; if (Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) { GLSLSeparableProgram* separableProgram = GLSLSeparableProgramManager::getSingleton().getCurrentSeparableProgram(); if (separableProgram) { if (!op.renderToVertexBuffer) { separableProgram->activate(); } updateVAO = !separableProgram->getVertexArrayObject()->isInitialised(); separableProgram->getVertexArrayObject()->bind(); } else { Ogre::LogManager::getSingleton().logMessage( "ERROR: Failed to create separable program.", LML_CRITICAL); } } else { GLSLMonolithicProgram* monolithicProgram = GLSLMonolithicProgramManager::getSingleton().getActiveMonolithicProgram(); if (monolithicProgram) { updateVAO = !monolithicProgram->getVertexArrayObject()->isInitialised(); monolithicProgram->getVertexArrayObject()->bind(); } else { Ogre::LogManager::getSingleton().logMessage( "ERROR: Failed to create monolithic program.", LML_CRITICAL); } } // Bind the appropriate VBOs to the active attributes of the VAO. for (elemIter = decl.begin(); elemIter != elemEnd; ++elemIter) { const v1::VertexElement & elem = *elemIter; size_t source = elem.getSource(); if (!op.vertexData->vertexBufferBinding->isBufferBound(source)) continue; // Skip unbound elements. v1::HardwareVertexBufferSharedPtr vertexBuffer = op.vertexData->vertexBufferBinding->getBuffer(source); bindVertexElementToGpu(elem, vertexBuffer, op.vertexData->vertexStart, mRenderAttribsBound, mRenderInstanceAttribsBound, updateVAO); } if ( !globalInstanceVertexBuffer.isNull() && globalVertexDeclaration != NULL ) { elemEnd = globalVertexDeclaration->getElements().end(); for (elemIter = globalVertexDeclaration->getElements().begin(); elemIter != elemEnd; ++elemIter) { const v1::VertexElement & elem = *elemIter; bindVertexElementToGpu(elem, globalInstanceVertexBuffer, 0, mRenderAttribsBound, mRenderInstanceAttribsBound, updateVAO); } } activateGLTextureUnit(0); // Determine the correct primitive type to render. GLint primType; // Use adjacency if there is a geometry program and it requested adjacency info. bool useAdjacency = (mGeometryProgramBound && mPso->geometryShader && mPso->geometryShader->isAdjacencyInfoRequired()); switch (op.operationType) { case OT_POINT_LIST: primType = GL_POINTS; break; case OT_LINE_LIST: primType = useAdjacency ? GL_LINES_ADJACENCY : GL_LINES; break; case OT_LINE_STRIP: primType = useAdjacency ? GL_LINE_STRIP_ADJACENCY : GL_LINE_STRIP; break; default: case OT_TRIANGLE_LIST: primType = useAdjacency ? GL_TRIANGLES_ADJACENCY : GL_TRIANGLES; break; case OT_TRIANGLE_STRIP: primType = useAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY : GL_TRIANGLE_STRIP; break; case OT_TRIANGLE_FAN: primType = GL_TRIANGLE_FAN; break; } // Bind atomic counter buffers. // if (Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_ATOMIC_COUNTERS)) // { // GLuint atomicsBuffer = 0; // glGenBuffers(1, &atomicsBuffer); // glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, // static_cast<GL3PlusHardwareCounterBuffer*>(HardwareBufferManager::getSingleton().getCounterBuffer().getGLBufferId())); // //static_cast<GL3PlusHardwareCounterBuffer*>(op..getCounterBuffer().getGLBufferId())); // // glBufferData(GL_ATOMIC_COUNTER_BUFFER, sizeof(GLuint) * 3, NULL, GL_DYNAMIC_DRAW); // // glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0); // } //TODO: Reset atomic counters somewhere // Render to screen! if (mPso->domainShader) { // Tessellation shader special case. // Note: Only evaluation (domain) shaders are required. // GLuint primCount = 0; // // Useful primitives for tessellation // switch( op.operationType ) // { // case OT_LINE_LIST: // primCount = (GLuint)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 2; // break; // case OT_LINE_STRIP: // primCount = (GLuint)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 1; // break; // case OT_TRIANGLE_LIST: // primCount = (GLuint)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount); // //primCount = (GLuint)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 3; // break; // case OT_TRIANGLE_STRIP: // primCount = (GLuint)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 2; // break; // default: // break; // } // These are set via shader in DX11, SV_InsideTessFactor and SV_OutsideTessFactor // Hardcoding for the sample // float patchLevel(1.f); // OGRE_CHECK_GL_ERROR(glPatchParameterfv(GL_PATCH_DEFAULT_INNER_LEVEL, &patchLevel)); // OGRE_CHECK_GL_ERROR(glPatchParameterfv(GL_PATCH_DEFAULT_OUTER_LEVEL, &patchLevel)); // OGRE_CHECK_GL_ERROR(glPatchParameteri(GL_PATCH_VERTICES, op.vertexData->vertexCount)); if (op.useIndexes) { OGRE_CHECK_GL_ERROR(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, static_cast<v1::GL3PlusHardwareIndexBuffer*>(op.indexData->indexBuffer.get())->getGLBufferId())); void *pBufferData = GL_BUFFER_OFFSET(op.indexData->indexStart * op.indexData->indexBuffer->getIndexSize()); GLenum indexType = (op.indexData->indexBuffer->getType() == v1::HardwareIndexBuffer::IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT; OGRE_CHECK_GL_ERROR(glDrawElements(GL_PATCHES, op.indexData->indexCount, indexType, pBufferData)); //OGRE_CHECK_GL_ERROR(glDrawElements(GL_PATCHES, op.indexData->indexCount, indexType, pBufferData)); // OGRE_CHECK_GL_ERROR(glDrawArraysInstanced(GL_PATCHES, 0, primCount, 1)); } else { OGRE_CHECK_GL_ERROR(glDrawArrays(GL_PATCHES, 0, op.vertexData->vertexCount)); //OGRE_CHECK_GL_ERROR(glDrawArrays(GL_PATCHES, 0, primCount)); // OGRE_CHECK_GL_ERROR(glDrawArraysInstanced(GL_PATCHES, 0, primCount, 1)); } } else if (op.useIndexes) { OGRE_CHECK_GL_ERROR(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, static_cast<v1::GL3PlusHardwareIndexBuffer*>(op.indexData->indexBuffer.get())->getGLBufferId())); void *pBufferData = GL_BUFFER_OFFSET(op.indexData->indexStart * op.indexData->indexBuffer->getIndexSize()); GLenum indexType = (op.indexData->indexBuffer->getType() == v1::HardwareIndexBuffer::IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT; do { // Update derived depth bias. if (mDerivedDepthBias && mCurrentPassIterationNum > 0) { _setDepthBias(mDerivedDepthBiasBase + mDerivedDepthBiasMultiplier * mCurrentPassIterationNum, mDerivedDepthBiasSlopeScale); } if(hasInstanceData) { OGRE_CHECK_GL_ERROR(glDrawElementsInstancedBaseVertex(primType, op.indexData->indexCount, indexType, pBufferData, numberOfInstances, op.vertexData->vertexStart)); } else { OGRE_CHECK_GL_ERROR( glDrawElementsBaseVertex( primType, op.indexData->indexCount, indexType, pBufferData, op.vertexData->vertexStart ) ); } } while (updatePassIterationRenderState()); } else { do { // Update derived depth bias. if (mDerivedDepthBias && mCurrentPassIterationNum > 0) { _setDepthBias(mDerivedDepthBiasBase + mDerivedDepthBiasMultiplier * mCurrentPassIterationNum, mDerivedDepthBiasSlopeScale); } if (hasInstanceData) { OGRE_CHECK_GL_ERROR(glDrawArraysInstanced(primType, 0, op.vertexData->vertexCount, numberOfInstances)); } else { OGRE_CHECK_GL_ERROR(glDrawArrays(primType, 0, op.vertexData->vertexCount)); } } while (updatePassIterationRenderState()); } // Unbind VAO (if updated). if (updateVAO) { if (Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) { GLSLSeparableProgram* separableProgram = GLSLSeparableProgramManager::getSingleton().getCurrentSeparableProgram(); if (separableProgram) { separableProgram->getVertexArrayObject()->setInitialised(true); } } else { GLSLMonolithicProgram* monolithicProgram = GLSLMonolithicProgramManager::getSingleton().getActiveMonolithicProgram(); if (monolithicProgram) { monolithicProgram->getVertexArrayObject()->setInitialised(true); } } // Unbind the vertex array object. // Marks the end of what state will be included. OGRE_CHECK_GL_ERROR(glBindVertexArray(0)); } mRenderAttribsBound.clear(); mRenderInstanceAttribsBound.clear(); } void GL3PlusRenderSystem::_dispatch( const HlmsComputePso &pso ) { glDispatchCompute( pso.mNumThreadGroups[0], pso.mNumThreadGroups[1], pso.mNumThreadGroups[2] ); } void GL3PlusRenderSystem::_setVertexArrayObject( const VertexArrayObject *_vao ) { if( _vao ) { const GL3PlusVertexArrayObject *vao = static_cast<const GL3PlusVertexArrayObject*>( _vao ); OGRE_CHECK_GL_ERROR( glBindVertexArray( vao->mVaoName ) ); } else { OGRE_CHECK_GL_ERROR( glBindVertexArray( 0 ) ); } } void GL3PlusRenderSystem::_render( const CbDrawCallIndexed *cmd ) { const GL3PlusVertexArrayObject *vao = static_cast<const GL3PlusVertexArrayObject*>( cmd->vao ); GLenum mode = mPso->domainShader ? GL_PATCHES : vao->mPrimType[mUseAdjacency]; GLenum indexType = vao->mIndexBuffer->getIndexType() == IndexBufferPacked::IT_16BIT ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT; OCGE( glMultiDrawElementsIndirect( mode, indexType, cmd->indirectBufferOffset, cmd->numDraws, sizeof(CbDrawIndexed) ) ); } void GL3PlusRenderSystem::_render( const CbDrawCallStrip *cmd ) { const GL3PlusVertexArrayObject *vao = static_cast<const GL3PlusVertexArrayObject*>( cmd->vao ); GLenum mode = mPso->domainShader ? GL_PATCHES : vao->mPrimType[mUseAdjacency]; OCGE( glMultiDrawArraysIndirect( mode, cmd->indirectBufferOffset, cmd->numDraws, sizeof(CbDrawStrip) ) ); } void GL3PlusRenderSystem::_renderEmulated( const CbDrawCallIndexed *cmd ) { const GL3PlusVertexArrayObject *vao = static_cast<const GL3PlusVertexArrayObject*>( cmd->vao ); GLenum mode = mPso->domainShader ? GL_PATCHES : vao->mPrimType[mUseAdjacency]; GLenum indexType = vao->mIndexBuffer->getIndexType() == IndexBufferPacked::IT_16BIT ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT; CbDrawIndexed *drawCmd = reinterpret_cast<CbDrawIndexed*>( mSwIndirectBufferPtr + (size_t)cmd->indirectBufferOffset ); const size_t bytesPerIndexElement = vao->mIndexBuffer->getBytesPerElement(); for( uint32 i=cmd->numDraws; i--; ) { OCGE( glDrawElementsInstancedBaseVertexBaseInstance( mode, drawCmd->primCount, indexType, reinterpret_cast<void*>( drawCmd->firstVertexIndex * bytesPerIndexElement ), drawCmd->instanceCount, drawCmd->baseVertex, drawCmd->baseInstance ) ); ++drawCmd; } } void GL3PlusRenderSystem::_renderEmulated( const CbDrawCallStrip *cmd ) { const GL3PlusVertexArrayObject *vao = static_cast<const GL3PlusVertexArrayObject*>( cmd->vao ); GLenum mode = mPso->domainShader ? GL_PATCHES : vao->mPrimType[mUseAdjacency]; CbDrawStrip *drawCmd = reinterpret_cast<CbDrawStrip*>( mSwIndirectBufferPtr + (size_t)cmd->indirectBufferOffset ); for( uint32 i=cmd->numDraws; i--; ) { OCGE( glDrawArraysInstancedBaseInstance( mode, drawCmd->firstVertexIndex, drawCmd->primCount, drawCmd->instanceCount, drawCmd->baseInstance ) ); ++drawCmd; } } void GL3PlusRenderSystem::_renderEmulatedNoBaseInstance( const CbDrawCallIndexed *cmd ) { const GL3PlusVertexArrayObject *vao = static_cast<const GL3PlusVertexArrayObject*>( cmd->vao ); GLenum mode = mPso->domainShader ? GL_PATCHES : vao->mPrimType[mUseAdjacency]; GLenum indexType = vao->mIndexBuffer->getIndexType() == IndexBufferPacked::IT_16BIT ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT; CbDrawIndexed *drawCmd = reinterpret_cast<CbDrawIndexed*>( mSwIndirectBufferPtr + (size_t)cmd->indirectBufferOffset ); const size_t bytesPerIndexElement = vao->mIndexBuffer->getBytesPerElement(); GLSLMonolithicProgram *activeLinkProgram = GLSLMonolithicProgramManager::getSingleton().getActiveMonolithicProgram(); for( uint32 i=cmd->numDraws; i--; ) { OCGE( glUniform1ui( activeLinkProgram->mBaseInstanceLocation, static_cast<GLuint>( drawCmd->baseInstance ) ) ); OCGE( glDrawElementsInstancedBaseVertex( mode, drawCmd->primCount, indexType, reinterpret_cast<void*>( drawCmd->firstVertexIndex * bytesPerIndexElement ), drawCmd->instanceCount, drawCmd->baseVertex ) ); ++drawCmd; } } void GL3PlusRenderSystem::_renderEmulatedNoBaseInstance( const CbDrawCallStrip *cmd ) { const GL3PlusVertexArrayObject *vao = static_cast<const GL3PlusVertexArrayObject*>( cmd->vao ); GLenum mode = mPso->domainShader ? GL_PATCHES : vao->mPrimType[mUseAdjacency]; CbDrawStrip *drawCmd = reinterpret_cast<CbDrawStrip*>( mSwIndirectBufferPtr + (size_t)cmd->indirectBufferOffset ); GLSLMonolithicProgram *activeLinkProgram = GLSLMonolithicProgramManager::getSingleton().getActiveMonolithicProgram(); for( uint32 i=cmd->numDraws; i--; ) { OCGE( glUniform1ui( activeLinkProgram->mBaseInstanceLocation, static_cast<GLuint>( drawCmd->baseInstance ) ) ); OCGE( glDrawArraysInstanced( mode, drawCmd->firstVertexIndex, drawCmd->primCount, drawCmd->instanceCount ) ); ++drawCmd; } } void GL3PlusRenderSystem::_startLegacyV1Rendering(void) { glBindVertexArray( mGlobalVao ); } void GL3PlusRenderSystem::_setRenderOperation( const v1::CbRenderOp *cmd ) { mCurrentVertexBuffer = cmd->vertexData; mCurrentIndexBuffer = cmd->indexData; glBindVertexArray( mGlobalVao ); v1::VertexBufferBinding *vertexBufferBinding = cmd->vertexData->vertexBufferBinding; v1::VertexDeclaration *vertexDeclaration = cmd->vertexData->vertexDeclaration; const v1::VertexDeclaration::VertexElementList& elements = vertexDeclaration->getElements(); v1::VertexDeclaration::VertexElementList::const_iterator itor; v1::VertexDeclaration::VertexElementList::const_iterator end; itor = elements.begin(); end = elements.end(); while( itor != end ) { const v1::VertexElement &elem = *itor; unsigned short source = elem.getSource(); VertexElementSemantic semantic = elem.getSemantic(); GLuint attributeIndex = GL3PlusVaoManager::getAttributeIndexFor( semantic ) + elem.getIndex(); if( !vertexBufferBinding->isBufferBound( source ) ) { OCGE( glDisableVertexAttribArray( attributeIndex ) ); ++itor; continue; // Skip unbound elements. } v1::HardwareVertexBufferSharedPtr vertexBuffer = vertexBufferBinding->getBuffer( source ); const v1::GL3PlusHardwareVertexBuffer* hwGlBuffer = static_cast<v1::GL3PlusHardwareVertexBuffer*>( vertexBuffer.get() ); OCGE( glBindBuffer( GL_ARRAY_BUFFER, hwGlBuffer->getGLBufferId() ) ); void *bindOffset = GL_BUFFER_OFFSET( elem.getOffset() ); VertexElementType vertexElementType = elem.getType(); GLint typeCount = v1::VertexElement::getTypeCount( vertexElementType ); GLboolean normalised = v1::VertexElement::isTypeNormalized( vertexElementType ) ? GL_TRUE : GL_FALSE; switch( vertexElementType ) { case VET_COLOUR: case VET_COLOUR_ABGR: case VET_COLOUR_ARGB: // Because GL takes these as a sequence of single unsigned bytes, count needs to be 4 // VertexElement::getTypeCount treats them as 1 (RGBA) // Also need to normalise the fixed-point data typeCount = 4; normalised = GL_TRUE; break; default: break; }; assert( (semantic != VES_TEXTURE_COORDINATES || elem.getIndex() < 8) && "Up to 8 UVs are supported." ); if( semantic == VES_BINORMAL ) { LogManager::getSingleton().logMessage( "WARNING: VES_BINORMAL will not render properly in " "many GPUs where GL_MAX_VERTEX_ATTRIBS = 16. Consider" " changing for VES_TANGENT with 4 components or use" " QTangents", LML_CRITICAL ); } GLenum type = v1::GL3PlusHardwareBufferManager::getGLType( vertexElementType ); switch( v1::VertexElement::getBaseType( vertexElementType ) ) { default: case VET_FLOAT1: OCGE( glVertexAttribPointer( attributeIndex, typeCount, type, normalised, static_cast<GLsizei>(vertexBuffer->getVertexSize()), bindOffset ) ); break; case VET_BYTE4: case VET_UBYTE4: case VET_SHORT2: case VET_USHORT2: case VET_UINT1: case VET_INT1: OCGE( glVertexAttribIPointer( attributeIndex, typeCount, type, static_cast<GLsizei>(vertexBuffer->getVertexSize()), bindOffset ) ); break; case VET_DOUBLE1: OCGE( glVertexAttribLPointer( attributeIndex, typeCount, type, static_cast<GLsizei>(vertexBuffer->getVertexSize()), bindOffset ) ); break; } OCGE( glVertexAttribDivisor( attributeIndex, hwGlBuffer->getInstanceDataStepRate() * hwGlBuffer->getIsInstanceData() ) ); OCGE( glEnableVertexAttribArray( attributeIndex ) ); ++itor; } if( cmd->indexData ) { v1::GL3PlusHardwareIndexBuffer *indexBuffer = static_cast<v1::GL3PlusHardwareIndexBuffer*>( cmd->indexData->indexBuffer.get() ); OCGE( glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, indexBuffer->getGLBufferId() ) ); } mCurrentPolygonMode = GL_TRIANGLES; switch( cmd->operationType ) { case OT_POINT_LIST: mCurrentPolygonMode = GL_POINTS; break; case OT_LINE_LIST: mCurrentPolygonMode = mUseAdjacency ? GL_LINES_ADJACENCY : GL_LINES; break; case OT_LINE_STRIP: mCurrentPolygonMode = mUseAdjacency ? GL_LINE_STRIP_ADJACENCY : GL_LINE_STRIP; break; default: case OT_TRIANGLE_LIST: mCurrentPolygonMode = mUseAdjacency ? GL_TRIANGLES_ADJACENCY : GL_TRIANGLES; break; case OT_TRIANGLE_STRIP: mCurrentPolygonMode = mUseAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY : GL_TRIANGLE_STRIP; break; case OT_TRIANGLE_FAN: mCurrentPolygonMode = GL_TRIANGLE_FAN; break; } } void GL3PlusRenderSystem::_render( const v1::CbDrawCallIndexed *cmd ) { GLenum indexType = mCurrentIndexBuffer->indexBuffer->getType() == v1::HardwareIndexBuffer::IT_16BIT ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT; const size_t bytesPerIndexElement = mCurrentIndexBuffer->indexBuffer->getIndexSize(); OCGE( glDrawElementsInstancedBaseVertexBaseInstance( mCurrentPolygonMode, cmd->primCount, indexType, reinterpret_cast<void*>( cmd->firstVertexIndex * bytesPerIndexElement ), cmd->instanceCount, mCurrentVertexBuffer->vertexStart, cmd->baseInstance ) ); } void GL3PlusRenderSystem::_render( const v1::CbDrawCallStrip *cmd ) { OCGE( glDrawArraysInstancedBaseInstance( mCurrentPolygonMode, cmd->firstVertexIndex, cmd->primCount, cmd->instanceCount, cmd->baseInstance ) ); } void GL3PlusRenderSystem::_renderNoBaseInstance( const v1::CbDrawCallIndexed *cmd ) { GLenum indexType = mCurrentIndexBuffer->indexBuffer->getType() == v1::HardwareIndexBuffer::IT_16BIT ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT; const size_t bytesPerIndexElement = mCurrentIndexBuffer->indexBuffer->getIndexSize(); GLSLMonolithicProgram *activeLinkProgram = GLSLMonolithicProgramManager::getSingleton().getActiveMonolithicProgram(); OCGE( glUniform1ui( activeLinkProgram->mBaseInstanceLocation, static_cast<GLuint>( cmd->baseInstance ) ) ); OCGE( glDrawElementsInstancedBaseVertex( mCurrentPolygonMode, cmd->primCount, indexType, reinterpret_cast<void*>(cmd->firstVertexIndex * bytesPerIndexElement), cmd->instanceCount, mCurrentVertexBuffer->vertexStart ) ); } void GL3PlusRenderSystem::_renderNoBaseInstance( const v1::CbDrawCallStrip *cmd ) { GLSLMonolithicProgram *activeLinkProgram = GLSLMonolithicProgramManager::getSingleton().getActiveMonolithicProgram(); OCGE( glUniform1ui( activeLinkProgram->mBaseInstanceLocation, static_cast<GLuint>( cmd->baseInstance ) ) ); OCGE( glDrawArraysInstanced( mCurrentPolygonMode, cmd->firstVertexIndex, cmd->primCount, cmd->instanceCount ) ); } void GL3PlusRenderSystem::clearFrameBuffer(unsigned int buffers, const ColourValue& colour, Real depth, unsigned short stencil) { bool colourMask = mBlendChannelMask != HlmsBlendblock::BlendChannelAll; GLbitfield flags = 0; if (buffers & FBT_COLOUR) { flags |= GL_COLOR_BUFFER_BIT; // Enable buffer for writing if it isn't if (colourMask) { OGRE_CHECK_GL_ERROR(glColorMask(true, true, true, true)); } OGRE_CHECK_GL_ERROR(glClearColor(colour.r, colour.g, colour.b, colour.a)); } if (buffers & FBT_DEPTH) { flags |= GL_DEPTH_BUFFER_BIT; // Enable buffer for writing if it isn't if (!mDepthWrite) { OGRE_CHECK_GL_ERROR(glDepthMask(GL_TRUE)); } OGRE_CHECK_GL_ERROR(glClearDepth(depth)); } if (buffers & FBT_STENCIL) { flags |= GL_STENCIL_BUFFER_BIT; // Enable buffer for writing if it isn't OGRE_CHECK_GL_ERROR(glStencilMask(0xFFFFFFFF)); OGRE_CHECK_GL_ERROR(glClearStencil(stencil)); } RenderTarget* target = mActiveViewport->getTarget(); bool scissorsNeeded = mActiveViewport->getActualLeft() != 0 || mActiveViewport->getActualTop() != 0 || mActiveViewport->getActualWidth() != (int)target->getWidth() || mActiveViewport->getActualHeight() != (int)target->getHeight(); if( scissorsNeeded ) { //We clear the viewport area. The Viewport may not //coincide with the current clipping region GLsizei x, y, w, h; w = mActiveViewport->getActualWidth(); h = mActiveViewport->getActualHeight(); x = mActiveViewport->getActualLeft(); y = mActiveViewport->getActualTop(); if( !target->requiresTextureFlipping() ) { // Convert "upper-left" corner to "lower-left" y = target->getHeight() - h - y; } OGRE_CHECK_GL_ERROR(glScissor(x, y, w, h)); } if( scissorsNeeded && !mScissorsEnabled ) { // Clear the buffers // Subregion clears need scissort tests enabled. OGRE_CHECK_GL_ERROR(glEnable(GL_SCISSOR_TEST)); OGRE_CHECK_GL_ERROR(glClear(flags)); OGRE_CHECK_GL_ERROR(glDisable(GL_SCISSOR_TEST)); } else { // Clear the buffers // Either clearing the whole screen, or scissor test is already enabled. OGRE_CHECK_GL_ERROR(glClear(flags)); } if( scissorsNeeded ) { //Restore the clipping region GLsizei x, y, w, h; w = mActiveViewport->getScissorActualWidth(); h = mActiveViewport->getScissorActualHeight(); x = mActiveViewport->getScissorActualLeft(); y = mActiveViewport->getScissorActualTop(); if( !target->requiresTextureFlipping() ) { // Convert "upper-left" corner to "lower-left" y = target->getHeight() - h - y; } OGRE_CHECK_GL_ERROR(glScissor(x, y, w, h)); } // Reset buffer write state if (!mDepthWrite && (buffers & FBT_DEPTH)) { OGRE_CHECK_GL_ERROR(glDepthMask(GL_FALSE)); } if (colourMask && (buffers & FBT_COLOUR)) { GLboolean r = (mBlendChannelMask & HlmsBlendblock::BlendChannelRed) != 0; GLboolean g = (mBlendChannelMask & HlmsBlendblock::BlendChannelGreen) != 0; GLboolean b = (mBlendChannelMask & HlmsBlendblock::BlendChannelBlue) != 0; GLboolean a = (mBlendChannelMask & HlmsBlendblock::BlendChannelAlpha) != 0; OCGE( glColorMask( r, g, b, a ) ); } if (buffers & FBT_STENCIL) { OGRE_CHECK_GL_ERROR(glStencilMask(mStencilParams.writeMask)); } } void GL3PlusRenderSystem::discardFrameBuffer( unsigned int buffers ) { //To GLES2 porting note: //GL_EXT_discard_framebuffer does not imply a clear. //GL_EXT_discard_framebuffer should be called after rendering //(Allows to omit writeback of unneeded data e.g. Z-buffers, Stencil) //On most renderers, not clearing (and invalidate is not clearing) //can put you in slow mode //GL_ARB_invalidate_subdata assert( mActiveRenderTarget ); if( !mHasArbInvalidateSubdata ) return; GLsizei numAttachments = 0; GLenum attachments[OGRE_MAX_MULTIPLE_RENDER_TARGETS+2]; GL3PlusFrameBufferObject *fbo = 0; mActiveRenderTarget->getCustomAttribute( GL3PlusRenderTexture::CustomAttributeString_FBO, &fbo ); if( fbo ) { if( buffers & FBT_COLOUR ) { for( size_t i=0; i<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++i ) { const GL3PlusSurfaceDesc &surfDesc = fbo->getSurface( i ); if( surfDesc.buffer ) attachments[numAttachments++] = static_cast<GLenum>( GL_COLOR_ATTACHMENT0 + i ); } } GL3PlusDepthBuffer *depthBuffer = static_cast<GL3PlusDepthBuffer*>( mActiveRenderTarget->getDepthBuffer() ); if( depthBuffer ) { if( buffers & FBT_STENCIL && depthBuffer->getStencilBuffer() ) attachments[numAttachments++] = GL_STENCIL_ATTACHMENT; if( buffers & FBT_DEPTH ) attachments[numAttachments++] = GL_DEPTH_ATTACHMENT; } } else { if( buffers & FBT_COLOUR ) { attachments[numAttachments++] = GL_COLOR; /*attachments[numAttachments++] = GL_BACK_LEFT; attachments[numAttachments++] = GL_BACK_RIGHT;*/ } if( buffers & FBT_DEPTH ) attachments[numAttachments++] = GL_DEPTH; if( buffers & FBT_STENCIL ) attachments[numAttachments++] = GL_STENCIL; } assert( numAttachments && "Bad flags provided" ); assert( numAttachments <= sizeof(attachments) / sizeof(attachments[0]) ); glInvalidateFramebuffer( GL_FRAMEBUFFER, numAttachments, attachments ); } void GL3PlusRenderSystem::_switchContext(GL3PlusContext *context) { // Unbind GPU programs and rebind to new context later, because // scene manager treat render system as ONE 'context' ONLY, and it // cached the GPU programs using state. if( mPso ) { if (mPso->vertexShader) mPso->vertexShader->unbind(); if (mPso->geometryShader) mPso->geometryShader->unbind(); if (mPso->pixelShader) mPso->pixelShader->unbind(); if (mPso->hullShader) mPso->hullShader->unbind(); if (mPso->domainShader) mPso->domainShader->unbind(); } if (mCurrentComputeShader) mCurrentComputeShader->unbind(); // Disable textures _disableTextureUnitsFrom(0); // It's ready for switching if (mCurrentContext!=context) { #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE // NSGLContext::makeCurrentContext does not flush automatically. everybody else does. glFlushRenderAPPLE(); #endif mCurrentContext->endCurrent(); mCurrentContext = context; } mCurrentContext->setCurrent(); // Check if the context has already done one-time initialisation if (!mCurrentContext->getInitialized()) { _oneTimeContextInitialization(); mCurrentContext->setInitialized(); } // Rebind GPU programs to new context if( mPso ) { if (mPso->vertexShader) mPso->vertexShader->bind(); if (mPso->geometryShader) mPso->geometryShader->bind(); if (mPso->pixelShader) mPso->pixelShader->bind(); if (mPso->hullShader) mPso->hullShader->bind(); if (mPso->domainShader) mPso->domainShader->bind(); } if (mCurrentComputeShader) mCurrentComputeShader->bind(); // Must reset depth/colour write mask to according with user desired, otherwise, // clearFrameBuffer would be wrong because the value we are recorded may be // difference with the really state stored in GL context. OGRE_CHECK_GL_ERROR(glDepthMask(mDepthWrite)); { GLboolean r = (mBlendChannelMask & HlmsBlendblock::BlendChannelRed) != 0; GLboolean g = (mBlendChannelMask & HlmsBlendblock::BlendChannelGreen) != 0; GLboolean b = (mBlendChannelMask & HlmsBlendblock::BlendChannelBlue) != 0; GLboolean a = (mBlendChannelMask & HlmsBlendblock::BlendChannelAlpha) != 0; OCGE( glColorMask( r, g, b, a ) ); } OGRE_CHECK_GL_ERROR(glStencilMask(mStencilParams.writeMask)); } void GL3PlusRenderSystem::_unregisterContext(GL3PlusContext *context) { if (mCurrentContext == context) { // Change the context to something else so that a valid context // remains active. When this is the main context being unregistered, // we set the main context to 0. if (mCurrentContext != mMainContext) { _switchContext(mMainContext); } else { /// No contexts remain mCurrentContext->endCurrent(); mCurrentContext = 0; mMainContext = 0; } } } void GL3PlusRenderSystem::_oneTimeContextInitialization() { OGRE_CHECK_GL_ERROR(glDisable(GL_DITHER)); // Check for FSAA // Enable the extension if it was enabled by the GL3PlusSupport int fsaa_active = false; OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_SAMPLE_BUFFERS, (GLint*)&fsaa_active)); if (fsaa_active) { OGRE_CHECK_GL_ERROR(glEnable(GL_MULTISAMPLE)); LogManager::getSingleton().logMessage("Using FSAA."); } if (mGLSupport->checkExtension("GL_EXT_texture_filter_anisotropic")) { OGRE_CHECK_GL_ERROR(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &mLargestSupportedAnisotropy)); } OCGE( glGenFramebuffers( 1, &mNullColourFramebuffer ) ); #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE // Some Apple NVIDIA hardware can't handle seamless cubemaps if (mCurrentCapabilities->getVendor() != GPU_NVIDIA) #endif // Enable seamless cube maps OGRE_CHECK_GL_ERROR(glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS)); // Set provoking vertex convention OGRE_CHECK_GL_ERROR(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION)); if (mGLSupport->checkExtension("GL_KHR_debug") || mHasGL43) { #if OGRE_DEBUG_MODE OGRE_CHECK_GL_ERROR(glDebugMessageCallbackARB(&GLDebugCallback, NULL)); OGRE_CHECK_GL_ERROR(glDebugMessageControlARB(GL_DEBUG_SOURCE_THIRD_PARTY, GL_DEBUG_TYPE_OTHER, GL_DONT_CARE, 0, NULL, GL_TRUE)); OGRE_CHECK_GL_ERROR(glEnable(GL_DEBUG_OUTPUT)); OGRE_CHECK_GL_ERROR(glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS)); #endif } } void GL3PlusRenderSystem::initialiseContext(RenderWindow* primary) { // Set main and current context mMainContext = 0; primary->getCustomAttribute(GL3PlusRenderTexture::CustomAttributeString_GLCONTEXT, &mMainContext); mCurrentContext = mMainContext; // Set primary context as active if (mCurrentContext) mCurrentContext->setCurrent(); // Initialise GL3W bool gl3wFailed = gl3wInit() != 0; if( gl3wFailed ) { LogManager::getSingleton().logMessage("Failed to initialize GL3W", LML_CRITICAL); } else { // Setup GL3PlusSupport mGLSupport->initialiseExtensions(); } // Make sure that OpenGL 3.3+ is supported in this context if( gl3wFailed || !mGLSupport->hasMinGLVersion(3, 3) ) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "OpenGL 3.3 is not supported. Please update your graphics card drivers.", "GL3PlusRenderSystem::initialiseContext"); } mHasGL43 = mGLSupport->hasMinGLVersion(4, 3); LogManager::getSingleton().logMessage("**************************************"); LogManager::getSingleton().logMessage("*** OpenGL 3+ Renderer Started ***"); LogManager::getSingleton().logMessage("**************************************"); } void GL3PlusRenderSystem::_setRenderTarget(RenderTarget *target, uint8 viewportRenderTargetFlags) { mActiveViewport = 0; // Unbind frame buffer object if (mActiveRenderTarget) { mRTTManager->unbind(mActiveRenderTarget); if( mActiveRenderTarget->getForceDisableColourWrites() && !mActiveRenderTarget->getDepthBuffer() ) { //Disable target independent rasterization to let the driver warn us //of wrong behavior during regular rendering. OCGE( glFramebufferParameteri( GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_WIDTH, 0 ) ); OCGE( glFramebufferParameteri( GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_HEIGHT, 0 ) ); } } mActiveRenderTarget = target; if (target) { // Switch context if different from current one GL3PlusContext *newContext = 0; target->getCustomAttribute(GL3PlusRenderTexture::CustomAttributeString_GLCONTEXT, &newContext); if (newContext && mCurrentContext != newContext) { _switchContext(newContext); } // Check the FBO's depth buffer status GL3PlusDepthBuffer *depthBuffer = static_cast<GL3PlusDepthBuffer*>(target->getDepthBuffer()); if( target->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH && (!depthBuffer || depthBuffer->getGLContext() != mCurrentContext ) ) { // Depth is automatically managed and there is no depth buffer attached to this RT // or the Current context doesn't match the one this Depth buffer was created with setDepthBufferFor( target, true ); } depthBuffer = static_cast<GL3PlusDepthBuffer*>(target->getDepthBuffer()); if( target->getForceDisableColourWrites() ) viewportRenderTargetFlags &= ~VP_RTT_COLOUR_WRITE; if( !(viewportRenderTargetFlags & VP_RTT_COLOUR_WRITE) ) { if( target->isRenderWindow() ) { OCGE( glBindFramebuffer( GL_FRAMEBUFFER, 0 ) ); } else { OCGE( glBindFramebuffer( GL_FRAMEBUFFER, mNullColourFramebuffer ) ); if( depthBuffer ) { //Attach the depth buffer to this no-colour framebuffer depthBuffer->bindToFramebuffer(); } else { //Detach all depth buffers from this no-colour framebuffer OCGE( glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0 ) ); OCGE( glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0 ) ); OCGE( glFramebufferParameteri( GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_WIDTH, target->getWidth() ) ); OCGE( glFramebufferParameteri( GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_HEIGHT, target->getHeight() ) ); OCGE( glFramebufferParameteri( GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_SAMPLES, target->getFSAA() > 1 ? target->getFSAA() : 0 ) ); } } //Do not render to colour Render Targets. OCGE( glDrawBuffer( GL_NONE ) ); } else { if( target->isRenderWindow() ) { //Make sure colour writes are enabled for RenderWindows. OCGE( glBindFramebuffer( GL_FRAMEBUFFER, 0 ) ); //TODO: Restore the setting sent to OGRE_NO_QUAD_BUFFER_STEREO? OCGE( glDrawBuffer( GL_BACK ) ); } // Bind frame buffer object mRTTManager->bind(target); } // Enable / disable sRGB states if (target->isHardwareGammaEnabled()) { OGRE_CHECK_GL_ERROR(glEnable(GL_FRAMEBUFFER_SRGB)); // Note: could test GL_FRAMEBUFFER_SRGB_CAPABLE here before // enabling, but GL spec says incapable surfaces ignore the setting // anyway. We test the capability to enable isHardwareGammaEnabled. } else { OGRE_CHECK_GL_ERROR(glDisable(GL_FRAMEBUFFER_SRGB)); } } flushUAVs(); } GLint GL3PlusRenderSystem::convertCompareFunction(CompareFunction func) const { switch(func) { case CMPF_ALWAYS_FAIL: return GL_NEVER; case CMPF_ALWAYS_PASS: return GL_ALWAYS; case CMPF_LESS: return GL_LESS; case CMPF_LESS_EQUAL: return GL_LEQUAL; case CMPF_EQUAL: return GL_EQUAL; case CMPF_NOT_EQUAL: return GL_NOTEQUAL; case CMPF_GREATER_EQUAL: return GL_GEQUAL; case CMPF_GREATER: return GL_GREATER; }; // To keep compiler happy return GL_ALWAYS; } GLint GL3PlusRenderSystem::convertStencilOp(StencilOperation op) const { switch(op) { case SOP_KEEP: return GL_KEEP; case SOP_ZERO: return GL_ZERO; case SOP_REPLACE: return GL_REPLACE; case SOP_INCREMENT: return GL_INCR; case SOP_DECREMENT: return GL_DECR; case SOP_INCREMENT_WRAP: return GL_INCR_WRAP; case SOP_DECREMENT_WRAP: return GL_DECR_WRAP; case SOP_INVERT: return GL_INVERT; }; // to keep compiler happy return SOP_KEEP; } void GL3PlusRenderSystem::bindGpuProgramParameters(GpuProgramType gptype, GpuProgramParametersSharedPtr params, uint16 mask) { // if (mask & (uint16)GPV_GLOBAL) // { //TODO We could maybe use GL_EXT_bindable_uniform here to produce Dx10-style // shared constant buffers, but GPU support seems fairly weak? // check the match to constant buffers & use rendersystem data hooks to store // for now, just copy params->_copySharedParams(); switch (gptype) { case GPT_VERTEX_PROGRAM: mActiveVertexGpuProgramParameters = params; mPso->vertexShader->bindSharedParameters(params, mask); break; case GPT_FRAGMENT_PROGRAM: mActiveFragmentGpuProgramParameters = params; mPso->pixelShader->bindSharedParameters(params, mask); break; case GPT_GEOMETRY_PROGRAM: mActiveGeometryGpuProgramParameters = params; mPso->geometryShader->bindSharedParameters(params, mask); break; case GPT_HULL_PROGRAM: mActiveTessellationHullGpuProgramParameters = params; mPso->hullShader->bindSharedParameters(params, mask); break; case GPT_DOMAIN_PROGRAM: mActiveTessellationDomainGpuProgramParameters = params; mPso->domainShader->bindSharedParameters(params, mask); break; case GPT_COMPUTE_PROGRAM: mActiveComputeGpuProgramParameters = params; mCurrentComputeShader->bindSharedParameters(params, mask); break; default: break; } // } // else // { switch (gptype) { case GPT_VERTEX_PROGRAM: mActiveVertexGpuProgramParameters = params; mPso->vertexShader->bindParameters(params, mask); break; case GPT_FRAGMENT_PROGRAM: mActiveFragmentGpuProgramParameters = params; mPso->pixelShader->bindParameters(params, mask); break; case GPT_GEOMETRY_PROGRAM: mActiveGeometryGpuProgramParameters = params; mPso->geometryShader->bindParameters(params, mask); break; case GPT_HULL_PROGRAM: mActiveTessellationHullGpuProgramParameters = params; mPso->hullShader->bindParameters(params, mask); break; case GPT_DOMAIN_PROGRAM: mActiveTessellationDomainGpuProgramParameters = params; mPso->domainShader->bindParameters(params, mask); break; case GPT_COMPUTE_PROGRAM: mActiveComputeGpuProgramParameters = params; mCurrentComputeShader->bindParameters(params, mask); break; default: break; } // } //FIXME This needs to be moved somewhere texture specific. // Update image bindings for image load/store // static_cast<GL3PlusTextureManager*>(mTextureManager)->bindImages(); } void GL3PlusRenderSystem::bindGpuProgramPassIterationParameters(GpuProgramType gptype) { switch (gptype) { case GPT_VERTEX_PROGRAM: mPso->vertexShader->bindPassIterationParameters(mActiveVertexGpuProgramParameters); break; case GPT_FRAGMENT_PROGRAM: mPso->pixelShader->bindPassIterationParameters(mActiveFragmentGpuProgramParameters); break; case GPT_GEOMETRY_PROGRAM: mPso->geometryShader->bindPassIterationParameters(mActiveGeometryGpuProgramParameters); break; case GPT_HULL_PROGRAM: mPso->hullShader->bindPassIterationParameters(mActiveTessellationHullGpuProgramParameters); break; case GPT_DOMAIN_PROGRAM: mPso->domainShader->bindPassIterationParameters(mActiveTessellationDomainGpuProgramParameters); break; case GPT_COMPUTE_PROGRAM: mCurrentComputeShader->bindPassIterationParameters(mActiveComputeGpuProgramParameters); break; default: break; } } void GL3PlusRenderSystem::setClipPlanesImpl(const Ogre::PlaneList& planeList) { OGRE_CHECK_GL_ERROR(glEnable(GL_DEPTH_CLAMP)); } void GL3PlusRenderSystem::registerThread() { OGRE_LOCK_MUTEX(mThreadInitMutex); // This is only valid once we've created the main context if (!mMainContext) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot register a background thread before the main context " "has been created.", "GL3PlusRenderSystem::registerThread"); } // Create a new context for this thread. Cloning from the main context // will ensure that resources are shared with the main context // We want a separate context so that we can safely create GL // objects in parallel with the main thread GL3PlusContext* newContext = mMainContext->clone(); mBackgroundContextList.push_back(newContext); // Bind this new context to this thread. newContext->setCurrent(); _oneTimeContextInitialization(); newContext->setInitialized(); } void GL3PlusRenderSystem::unregisterThread() { // nothing to do here? // Don't need to worry about active context, just make sure we delete // on shutdown. } void GL3PlusRenderSystem::preExtraThreadsStarted() { OGRE_LOCK_MUTEX(mThreadInitMutex); // free context, we'll need this to share lists if (mCurrentContext) mCurrentContext->endCurrent(); } void GL3PlusRenderSystem::postExtraThreadsStarted() { OGRE_LOCK_MUTEX(mThreadInitMutex); // reacquire context if (mCurrentContext) mCurrentContext->setCurrent(); } unsigned int GL3PlusRenderSystem::getDisplayMonitorCount() const { return mGLSupport->getDisplayMonitorCount(); } void GL3PlusRenderSystem::beginProfileEvent( const String &eventName ) { markProfileEvent("Begin Event: " + eventName); if( mHasGL43 || mGLSupport->checkExtension("ARB_debug_group") ) { OCGE( glPushDebugGroup( GL_DEBUG_SOURCE_THIRD_PARTY, 0, static_cast<GLint>( eventName.length() ), eventName.c_str() ) ); } } void GL3PlusRenderSystem::endProfileEvent( void ) { markProfileEvent("End Event"); if( mHasGL43 || mGLSupport->checkExtension("ARB_debug_group") ) OCGE( glPopDebugGroup() ); } void GL3PlusRenderSystem::markProfileEvent( const String &eventName ) { if( eventName.empty() ) return; if( mHasGL43 || mGLSupport->checkExtension("GL_KHR_debug") ) { glDebugMessageInsert( GL_DEBUG_SOURCE_THIRD_PARTY, GL_DEBUG_TYPE_PERFORMANCE, 0, GL_DEBUG_SEVERITY_LOW, static_cast<GLint>( eventName.length() ), eventName.c_str() ); } } void GL3PlusRenderSystem::initGPUProfiling(void) { #if OGRE_PROFILING == OGRE_PROFILING_REMOTERY _rmt_BindOpenGL(); #endif } void GL3PlusRenderSystem::deinitGPUProfiling(void) { #if OGRE_PROFILING == OGRE_PROFILING_REMOTERY _rmt_UnbindOpenGL(); #endif } void GL3PlusRenderSystem::beginGPUSampleProfile( const String &name, uint32 *hashCache ) { #if OGRE_PROFILING == OGRE_PROFILING_REMOTERY _rmt_BeginOpenGLSample( name.c_str(), hashCache ); #endif } void GL3PlusRenderSystem::endGPUSampleProfile( const String &name ) { #if OGRE_PROFILING == OGRE_PROFILING_REMOTERY _rmt_EndOpenGLSample(); #endif } bool GL3PlusRenderSystem::activateGLTextureUnit(size_t unit) { if (mActiveTextureUnit != unit) { if (unit < getCapabilities()->getNumTextureUnits()) { OGRE_CHECK_GL_ERROR(glActiveTexture(static_cast<uint32>(GL_TEXTURE0 + unit))); mActiveTextureUnit = static_cast<GLenum>(unit); return true; } else if (!unit) { //FIXME If the above case fails, should this case ever be taken? // Also switch to (unit == number) unless not operation is actually // faster on some architectures. // Always OK to use the first unit. return true; } else { return false; } } else { return true; } } void GL3PlusRenderSystem::bindVertexElementToGpu( const v1::VertexElement &elem, v1::HardwareVertexBufferSharedPtr vertexBuffer, const size_t vertexStart, vector<GLuint>::type &attribsBound, vector<GLuint>::type &instanceAttribsBound, bool updateVAO) { const v1::GL3PlusHardwareVertexBuffer* hwGlBuffer = static_cast<const v1::GL3PlusHardwareVertexBuffer*>( vertexBuffer.get()); // FIXME: Having this commented out fixes some rendering issues but leaves VAO's useless // if (updateVAO) { OGRE_CHECK_GL_ERROR(glBindBuffer(GL_ARRAY_BUFFER, hwGlBuffer->getGLBufferId())); void* pBufferData = GL_BUFFER_OFFSET(elem.getOffset()); if (vertexStart) { pBufferData = static_cast<char*>(pBufferData) + vertexStart * vertexBuffer->getVertexSize(); } VertexElementSemantic sem = elem.getSemantic(); unsigned short typeCount = v1::VertexElement::getTypeCount(elem.getType()); GLboolean normalised = GL_FALSE; GLuint attrib = 0; unsigned short elemIndex = elem.getIndex(); if (Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) { GLSLSeparableProgram* separableProgram = GLSLSeparableProgramManager::getSingleton().getCurrentSeparableProgram(); if (!separableProgram || !separableProgram->isAttributeValid(sem, elemIndex)) { return; } attrib = (GLuint)separableProgram->getAttributeIndex(sem, elemIndex); } else { GLSLMonolithicProgram* monolithicProgram = GLSLMonolithicProgramManager::getSingleton().getActiveMonolithicProgram(); if (!monolithicProgram || !monolithicProgram->isAttributeValid(sem, elemIndex)) { return; } attrib = (GLuint)monolithicProgram->getAttributeIndex(sem, elemIndex); } if (mPso->vertexShader) { if (hwGlBuffer->getIsInstanceData()) { OGRE_CHECK_GL_ERROR(glVertexAttribDivisor(attrib, hwGlBuffer->getInstanceDataStepRate())); instanceAttribsBound.push_back(attrib); } } switch(elem.getType()) { case VET_COLOUR: case VET_COLOUR_ABGR: case VET_COLOUR_ARGB: // Because GL takes these as a sequence of single unsigned bytes, count needs to be 4 // VertexElement::getTypeCount treats them as 1 (RGBA) // Also need to normalise the fixed-point data typeCount = 4; normalised = GL_TRUE; break; default: break; }; switch(elem.getBaseType(elem.getType())) { default: case VET_FLOAT1: OGRE_CHECK_GL_ERROR(glVertexAttribPointer(attrib, typeCount, v1::GL3PlusHardwareBufferManager::getGLType(elem.getType()), normalised, static_cast<GLsizei>(vertexBuffer->getVertexSize()), pBufferData)); break; case VET_DOUBLE1: OGRE_CHECK_GL_ERROR(glVertexAttribLPointer(attrib, typeCount, v1::GL3PlusHardwareBufferManager::getGLType(elem.getType()), static_cast<GLsizei>(vertexBuffer->getVertexSize()), pBufferData)); break; } // If this attribute hasn't been enabled, do so and keep a record of it. OGRE_CHECK_GL_ERROR(glEnableVertexAttribArray(attrib)); attribsBound.push_back(attrib); } } #if OGRE_NO_QUAD_BUFFER_STEREO == 0 bool GL3PlusRenderSystem::setDrawBuffer(ColourBufferType colourBuffer) { bool result = true; switch (colourBuffer) { case CBT_BACK: OGRE_CHECK_GL_ERROR(glDrawBuffer(GL_BACK)); break; case CBT_BACK_LEFT: OGRE_CHECK_GL_ERROR(glDrawBuffer(GL_BACK_LEFT)); break; case CBT_BACK_RIGHT: OGRE_CHECK_GL_ERROR(glDrawBuffer(GL_BACK_RIGHT)); // break; default: result = false; } return result; } #endif bool GL3PlusRenderSystem::checkExtension( const String &ext ) const { return mGLSupport->checkExtension( ext ); } const PixelFormatToShaderType* GL3PlusRenderSystem::getPixelFormatToShaderType(void) const { return &mPixelFormatToShaderType; } }
38.307345
182
0.573445
Ybalrid
3358c5e078d542649f3778d2702e7a73cc809bf0
1,501
cpp
C++
quic/common/test/TimeUtilTest.cpp
jsquyres/mvfst
4dd8efffcbd49db0e7a70f534c2f01bac74cd0ed
[ "MIT" ]
null
null
null
quic/common/test/TimeUtilTest.cpp
jsquyres/mvfst
4dd8efffcbd49db0e7a70f534c2f01bac74cd0ed
[ "MIT" ]
null
null
null
quic/common/test/TimeUtilTest.cpp
jsquyres/mvfst
4dd8efffcbd49db0e7a70f534c2f01bac74cd0ed
[ "MIT" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ #include <quic/common/TimeUtil.h> #include <gtest/gtest.h> namespace quic { namespace test { using namespace std; using namespace quic; using namespace testing; TEST(TimeUtil, TestMinTwo) { std::chrono::milliseconds ms1 = std::chrono::milliseconds(10); std::chrono::milliseconds ms2 = std::chrono::milliseconds(20); EXPECT_EQ(timeMin(ms1, ms2).count(), 10); } TEST(TimeUtil, TestMinFive) { std::chrono::milliseconds ms1 = std::chrono::milliseconds(20); std::chrono::milliseconds ms2 = std::chrono::milliseconds(30); std::chrono::milliseconds ms3 = std::chrono::milliseconds(40); std::chrono::milliseconds ms4 = std::chrono::milliseconds(10); EXPECT_EQ(timeMin(ms1, ms2, ms3, ms4).count(), 10); } TEST(TimeUtil, TestMaxTwo) { std::chrono::milliseconds ms1 = std::chrono::milliseconds(10); std::chrono::milliseconds ms2 = std::chrono::milliseconds(20); EXPECT_EQ(timeMax(ms1, ms2).count(), 20); } TEST(TimeUtil, TestMaxFive) { std::chrono::milliseconds ms1 = std::chrono::milliseconds(20); std::chrono::milliseconds ms2 = std::chrono::milliseconds(30); std::chrono::milliseconds ms3 = std::chrono::milliseconds(40); std::chrono::milliseconds ms4 = std::chrono::milliseconds(10); EXPECT_EQ(timeMax(ms1, ms2, ms3, ms4).count(), 40); } } // namespace test } // namespace quic
31.270833
66
0.711526
jsquyres
3359e463a9f49f08f03780efc8e4f8f4db39b0f6
2,250
cpp
C++
tests/lsutils_alloc_chunk_test.cpp
hamsham/LightUtils
ae909ee0e6d8915b1447cbb41aceceb98df1a2e6
[ "BSD-3-Clause" ]
1
2021-09-04T19:23:37.000Z
2021-09-04T19:23:37.000Z
tests/lsutils_alloc_chunk_test.cpp
hamsham/LightUtils
ae909ee0e6d8915b1447cbb41aceceb98df1a2e6
[ "BSD-3-Clause" ]
null
null
null
tests/lsutils_alloc_chunk_test.cpp
hamsham/LightUtils
ae909ee0e6d8915b1447cbb41aceceb98df1a2e6
[ "BSD-3-Clause" ]
1
2015-10-16T06:07:58.000Z
2015-10-16T06:07:58.000Z
#include <cassert> #include <cstdio> #include <iostream> #include "lightsky/utils/ChunkAllocator.hpp" int main() { constexpr unsigned alloc_table_size = 1024*1024; constexpr unsigned block_size = 512; constexpr unsigned max_allocations = alloc_table_size / block_size; // test allocator of 64 bytes in a 256-byte container ls::utils::ChunkAllocator<block_size, alloc_table_size> testAllocator; void** allocations = new void*[max_allocations]; void* p = nullptr; void* last = nullptr; (void)last; for (unsigned i = 0; i < max_allocations; ++i) { allocations[i] = nullptr; } for (unsigned testRuns = 0; testRuns < 3; ++testRuns) { for (unsigned i = 0; i <= max_allocations+1; ++i) { p = testAllocator.allocate(); if (!p && i < max_allocations) { std::cerr << "Error: ran out of memory at block " << i << std::endl; return -1; } last = p; std::cout << "Allocated chunk " << i << ": " << p << std::endl; if (i >= max_allocations) { if (p != nullptr) { std::cerr << "Error: test pointer 4 provided unknown memory!" << std::endl; return -2; } } else { allocations[i] = p; } } // we should be able to retrieve and reallocate testAllocator.free(allocations[2]); allocations[2] = nullptr; p = testAllocator.allocate(); if (!p) { std::cerr << "Error: Unable to reallocate block 2!" << std::endl; return -3; } else { allocations[2] = p; } p = testAllocator.allocate(); if (p) { std::cerr << "Error: Allocated too many chunks!" << std::endl; return -4; } // free all chunks and try again for (unsigned i = 0; i < max_allocations; ++i) { testAllocator.free(allocations[i]); allocations[i] = nullptr; } } delete [] allocations; return 0; }
25
95
0.492889
hamsham
335a1f7e2f14d2f765af640085054541005f500e
10,910
hpp
C++
src/lib/xml_compiler/include/pqrs/xml_compiler/detail/extracted_ptree.hpp
liasica/Karabiner_CN
5e9e4cb6734777bc9eecc57c5fcd0e8010c2bdc2
[ "Unlicense" ]
null
null
null
src/lib/xml_compiler/include/pqrs/xml_compiler/detail/extracted_ptree.hpp
liasica/Karabiner_CN
5e9e4cb6734777bc9eecc57c5fcd0e8010c2bdc2
[ "Unlicense" ]
null
null
null
src/lib/xml_compiler/include/pqrs/xml_compiler/detail/extracted_ptree.hpp
liasica/Karabiner_CN
5e9e4cb6734777bc9eecc57c5fcd0e8010c2bdc2
[ "Unlicense" ]
null
null
null
// This header intentionally has no include guards. class extracted_ptree final { public: extracted_ptree(const xml_compiler& xml_compiler, const pqrs::string::replacement& replacement, const boost::property_tree::ptree& pt, const std::string& xml_file_path) : xml_compiler_(xml_compiler), replacement_(replacement), pt_(pt), local_included_files_ptr_(new std::deque<std::string>), local_included_files_(*local_included_files_ptr_), stack_ptr_(new std::stack<stack_data>), stack_(*stack_ptr_) { local_included_files_.push_back(xml_file_path); } class node final { public: node(const boost::property_tree::ptree::value_type& node, const extracted_ptree& extracted_ptree, const pqrs::string::replacement& replacement) : node_(node), extracted_ptree_(extracted_ptree), replacement_(replacement) {} const std::string& get_tag_name(void) const { return node_.first; } const std::string& get_data(void) const { return node_.second.data(); } boost::optional<std::string> get_optional(const std::string& path) const { return node_.second.get_optional<std::string>(path); } bool children_empty(void) const { return node_.second.empty(); } extracted_ptree children_extracted_ptree(void) const { return extracted_ptree(extracted_ptree_, replacement_, node_.second); } private: const boost::property_tree::ptree::value_type& node_; const extracted_ptree& extracted_ptree_; const pqrs::string::replacement& replacement_; }; class stack_data final { public: stack_data(const boost::property_tree::ptree& pt, const pqrs::string::replacement& r) : it(pt.begin()), end(pt.end()), parent_replacement(r) {} // For extracted ptree. stack_data(const ptree_ptr& p, const std::shared_ptr<pqrs::string::replacement>& r, const boost::property_tree::ptree& root_children) : it(root_children.begin()), end(root_children.end()), parent_replacement(*r), pt_ptr_(p), replacement_ptr_(r) {} boost::property_tree::ptree::const_iterator it; boost::property_tree::ptree::const_iterator end; const pqrs::string::replacement& parent_replacement; bool extracted(void) const { return pt_ptr_ != nullptr; } private: // Keep extracted ptree_ptr, replacement_ptr until we finish traversing. const ptree_ptr pt_ptr_; const std::shared_ptr<pqrs::string::replacement> replacement_ptr_; }; class extracted_ptree_iterator final : public boost::iterator_facade<extracted_ptree_iterator, const node, boost::forward_traversal_tag> { public: extracted_ptree_iterator(const extracted_ptree& extracted_ptree) : extracted_ptree_(extracted_ptree), stack_size_(0), node_(nullptr) { set_node_(); } extracted_ptree_iterator(const extracted_ptree& extracted_ptree, const pqrs::string::replacement& replacement, const boost::property_tree::ptree& pt) : extracted_ptree_(extracted_ptree), stack_size_(extracted_ptree.stack_.size() + 1), node_(nullptr) { if (!pt.empty()) { extracted_ptree_.stack_.push(stack_data(pt, replacement)); extract_include_(); } set_node_(); } ~extracted_ptree_iterator(void) { if (node_) { delete node_; node_ = nullptr; } while (!ended_()) { auto& top = extracted_ptree_.stack_.top(); top.it = top.end; collapse_(); } } private: friend class boost::iterator_core_access; void increment(void) { if (ended_()) return; auto& top = extracted_ptree_.stack_.top(); if (top.it == top.end) return; ++(top.it); collapse_(); extract_include_(); set_node_(); } const node& dereference(void) const { assert(node_); return *node_; } bool equal(const extracted_ptree_iterator& other) const { if (is_end_() && other.is_end_()) { return true; } // extracted_ptree_iterator::equal supports only it == end(). assert(is_end_() || other.is_end_()); // ---------------------------------------- if (is_end_()) { other.equal(*this); } // ---------------------------------------- if (ended_()) { return true; } return false; } void set_node_(void) { if (node_) { delete node_; } node_ = nullptr; if (ended_()) { return; } const auto& top = extracted_ptree_.stack_.top(); if (top.it == top.end) { return; } node_ = new node(*(top.it), extracted_ptree_, top.parent_replacement); } void extract_include_(void) const { if (ended_()) return; const auto& xml_compiler = extracted_ptree_.xml_compiler_; auto& top = extracted_ptree_.stack_.top(); const auto& it = *(top.it); if (it.first != "include") return; // ---------------------------------------- // replacement std::shared_ptr<pqrs::string::replacement> replacement_ptr(new pqrs::string::replacement); if (!it.second.empty()) { replacement_loader loader(xml_compiler, *replacement_ptr); loader.traverse(extracted_ptree(extracted_ptree_, top.parent_replacement, it.second)); } auto end = replacement_ptr->end(); for (const auto& i : top.parent_replacement) { if (replacement_ptr->find(i.first) == end) { (*replacement_ptr)[i.first] = i.second; } } // ---------------------------------------- std::string xml_file_path; { auto path = it.second.get_optional<std::string>("<xmlattr>.path"); if (!path) { xml_compiler.error_information_.set("`path` attribute is not found in <include>."); } else { assert(!extracted_ptree_.local_included_files_.empty()); xml_file_path = xml_compiler.make_file_path(pqrs::file_path::dirname(extracted_ptree_.local_included_files_.back()), *path); } } if (!xml_file_path.empty()) { // check global_included_files_ auto attr_once = it.second.get_optional<std::string>("<xmlattr>.once"); if (attr_once) { for (const auto& i : xml_compiler.global_included_files_) { if (i == xml_file_path) { return; } } } xml_compiler.global_included_files_.push_back(xml_file_path); // check local_included_files_ for (const auto& i : extracted_ptree_.local_included_files_) { if (i == xml_file_path) { xml_compiler.error_information_.set("An infinite include loop is detected:\n" + xml_file_path); return; } } ptree_ptr pt_ptr; xml_compiler.read_xml_(pt_ptr, xml_file_path, *replacement_ptr); if (pt_ptr) { // Skip <include> next time. ++(top.it); // Do not call collapse_ here. // (Keep local_included_files_ to detect an infinite include loop.) if (!pt_ptr->empty()) { auto root_node = pt_ptr->begin(); const auto& root_children = root_node->second; if (!root_children.empty()) { extracted_ptree_.stack_.push(stack_data(pt_ptr, replacement_ptr, root_children)); extracted_ptree_.local_included_files_.push_back(xml_file_path); extract_include_(); } } collapse_(); } } } void collapse_(void) const { for (;;) { if (ended_()) break; const auto& top = extracted_ptree_.stack_.top(); if (top.it != top.end) { break; } if (top.extracted()) { assert(!extracted_ptree_.local_included_files_.empty()); extracted_ptree_.local_included_files_.pop_back(); } extracted_ptree_.stack_.pop(); } } bool is_end_(void) const { return stack_size_ == 0; } bool ended_(void) const { return (stack_size_ == 0) || (extracted_ptree_.stack_.size() < stack_size_); } const extracted_ptree& extracted_ptree_; const size_t stack_size_; node* node_; }; extracted_ptree_iterator begin(void) const { return extracted_ptree_iterator(*this, replacement_, pt_); } extracted_ptree_iterator end(void) const { return extracted_ptree_iterator(*this); } private: extracted_ptree(const extracted_ptree& extracted_ptree, const pqrs::string::replacement& replacement, const boost::property_tree::ptree& pt) : xml_compiler_(extracted_ptree.xml_compiler_), replacement_(replacement), pt_(pt), local_included_files_(extracted_ptree.local_included_files_), stack_(extracted_ptree.stack_) {} const xml_compiler& xml_compiler_; const pqrs::string::replacement& replacement_; const boost::property_tree::ptree& pt_; // shared_ptr for local_included_files_. std::shared_ptr<std::deque<std::string>> local_included_files_ptr_; // for infinite loop detection. std::deque<std::string>& local_included_files_; // shared_ptr for stack_. std::shared_ptr<std::stack<stack_data>> stack_ptr_; std::stack<stack_data>& stack_; };
35.537459
126
0.534189
liasica
335c4ea94b60c2b37eac096a95aa53644fd4b39b
1,554
cpp
C++
src/scenemanager.cpp
thatretrodev/unnamedgame
9292a8d6a02206b0cceb063e24d53dbd2e048f3d
[ "MIT" ]
4
2022-01-09T18:13:29.000Z
2022-01-09T18:15:54.000Z
src/scenemanager.cpp
thatretrodev/unnamedgame
9292a8d6a02206b0cceb063e24d53dbd2e048f3d
[ "MIT" ]
null
null
null
src/scenemanager.cpp
thatretrodev/unnamedgame
9292a8d6a02206b0cceb063e24d53dbd2e048f3d
[ "MIT" ]
null
null
null
#include "raylib.h" #include "scenemanager.hpp" SceneManager::SceneManager(bool* gameRunning) { this->gameRunning = gameRunning; } void SceneManager::SwitchScene(int SceneID) { this->sceneType = SceneID; switch (this->sceneType) { case 1: this->mainMenuScene.Init(this->gameRunning); break; case 2: this->gameScene.Init(); break; case 3: this->settingsScene.Init(this->gameRunning); default: break; } } void SceneManager::DrawUnknownSceneScreen() { ClearBackground(DARKBLUE); char* text = "Somehow, you have reached a scene that does not exist.\nWas it even worth your time?"; int textWidth = MeasureText(text, 20); DrawText(text, (GetScreenWidth() / 2) - (textWidth / 2), GetScreenHeight() / 2, 20, WHITE); } void SceneManager::Render() { switch (this->sceneType) { case 1: { int SceneID = this->mainMenuScene.Render(); if (SceneID != 0) { printf("Considering scene: %d\n", SceneID); } if (SceneID > 0 && 4 > SceneID) { printf("Switching to Scene: %d\n", SceneID); this->SwitchScene(SceneID); } } break; case 2: this->gameScene.Render(); break; case 3: { int SceneID = this->settingsScene.Render(); if (SceneID != 0) { printf("Considering scene: %d\n", SceneID); } if (SceneID > 0 && 4 > SceneID) { printf("Switching to Scene: %d\n", SceneID); this->SwitchScene(SceneID); } } break; default: this->DrawUnknownSceneScreen(); break; } } void SceneManager::Unload() { this->mainMenuScene.Unload(); }
21.287671
101
0.637066
thatretrodev
3364518322a07a828793414021d6a4ee5feacb8b
770
cc
C++
test/google-test/loan_controllers_parser_test/loan_controllers_parser_test.cc
fadi-alkhoury/fisim
08d91973251c94b8ac60b1889b41ffa3ace0d8ad
[ "MIT" ]
null
null
null
test/google-test/loan_controllers_parser_test/loan_controllers_parser_test.cc
fadi-alkhoury/fisim
08d91973251c94b8ac60b1889b41ffa3ace0d8ad
[ "MIT" ]
null
null
null
test/google-test/loan_controllers_parser_test/loan_controllers_parser_test.cc
fadi-alkhoury/fisim
08d91973251c94b8ac60b1889b41ffa3ace0d8ad
[ "MIT" ]
null
null
null
#include "json_helpers.h" #include "rapidjson/document.h" #include "rapidjson/filereadstream.h" #include "simulator.h" #include <gtest/gtest.h> namespace { TEST(ParserLoansDataTest, test00) { using namespace rapidjson; FILE* fp = std::fopen("./test/google-test/loan_controllers_parser_test/loan_controllers_test00.json", "r"); // non-Windows use "r" char readBuffer[65536]; FileReadStream is(fp, readBuffer, sizeof(readBuffer)); Document doc; doc.ParseStream(is); fclose(fp); const auto relations = fisim::json::parseRelationsRecords(doc); auto loanControllers = fisim::json::parseLoans(doc, relations.loanTaxLinks, fisim::CalendarMonth::aug, 50u); EXPECT_EQ(3, 3); // manually compare with the json file } } // namespace
27.5
134
0.720779
fadi-alkhoury
336527597c5d575414f18202a7e0c7ad5b9fca4f
114,677
cc
C++
zircon/kernel/vm/vm_unittest.cc
oshunter/fuchsia
2196fc8c176d01969466b97bba3f31ec55f7767b
[ "BSD-3-Clause" ]
2
2020-08-16T15:32:35.000Z
2021-11-07T20:09:46.000Z
zircon/kernel/vm/vm_unittest.cc
oshunter/fuchsia
2196fc8c176d01969466b97bba3f31ec55f7767b
[ "BSD-3-Clause" ]
null
null
null
zircon/kernel/vm/vm_unittest.cc
oshunter/fuchsia
2196fc8c176d01969466b97bba3f31ec55f7767b
[ "BSD-3-Clause" ]
1
2021-08-15T04:29:11.000Z
2021-08-15T04:29:11.000Z
// Copyright 2016 The Fuchsia Authors // // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT #include <align.h> #include <assert.h> #include <err.h> #include <lib/instrumentation/asan.h> #include <lib/unittest/unittest.h> #include <lib/unittest/user_memory.h> #include <zircon/types.h> #include <arch/kernel_aspace.h> #include <fbl/algorithm.h> #include <fbl/alloc_checker.h> #include <fbl/auto_call.h> #include <fbl/vector.h> #include <kernel/semaphore.h> #include <ktl/algorithm.h> #include <ktl/iterator.h> #include <ktl/move.h> #include <vm/fault.h> #include <vm/physmap.h> #include <vm/pmm.h> #include <vm/pmm_checker.h> #include <vm/scanner.h> #include <vm/vm.h> #include <vm/vm_address_region.h> #include <vm/vm_aspace.h> #include <vm/vm_object.h> #include <vm/vm_object_paged.h> #include <vm/vm_object_physical.h> #include "pmm_node.h" static const uint kArchRwFlags = ARCH_MMU_FLAG_PERM_READ | ARCH_MMU_FLAG_PERM_WRITE; namespace { // Helper class for managing a PmmNode with real pages. AllocRange and AllocContiguous are not // supported by the managed PmmNode object. Only a single instance can exist at a time. class ManagedPmmNode { public: static constexpr size_t kNumPages = 64; static constexpr size_t kDefaultWatermark = kNumPages / 2; static constexpr size_t kDefaultDebounce = 2; // Number of pages to alloc from the default config to put the node in a low mem state. static constexpr size_t kDefaultLowMemAlloc = ManagedPmmNode::kNumPages - ManagedPmmNode::kDefaultWatermark + ManagedPmmNode::kDefaultDebounce; explicit ManagedPmmNode(const uint64_t* watermarks = kDefaultArray, uint8_t watermark_count = 1, uint64_t debounce = kDefaultDebounce) { list_node list = LIST_INITIAL_VALUE(list); ZX_ASSERT(pmm_alloc_pages(kNumPages, 0, &list) == ZX_OK); vm_page_t* page; list_for_every_entry (&list, page, vm_page_t, queue_node) { page->set_state(VM_PAGE_STATE_FREE); } node_.AddFreePages(&list); ZX_ASSERT(node_.InitReclamation(watermarks, watermark_count, debounce * PAGE_SIZE, this, StateCallback) == ZX_OK); node_.InitRequestThread(); } ~ManagedPmmNode() { list_node list = LIST_INITIAL_VALUE(list); zx_status_t status = node_.AllocPages(kNumPages, 0, &list); ASSERT(status == ZX_OK); vm_page_t* page; list_for_every_entry (&list, page, vm_page_t, queue_node) { page->set_state(VM_PAGE_STATE_ALLOC); } pmm_free(&list); } uint8_t cur_level() const { return cur_level_; } PmmNode& node() { return node_; } private: PmmNode node_; uint8_t cur_level_ = MAX_WATERMARK_COUNT + 1; static void StateCallback(void* context, uint8_t level) { ManagedPmmNode* instance = reinterpret_cast<ManagedPmmNode*>(context); instance->cur_level_ = level; } static constexpr uint64_t kDefaultArray[1] = {kDefaultWatermark * PAGE_SIZE}; }; class TestPageRequest { public: TestPageRequest(PmmNode* node, uint64_t off, uint64_t len) : node_(node), request_({off, len, pages_available_cb, drop_ref_cb, this, {}}) {} ~TestPageRequest() { ASSERT(drop_ref_evt_.Wait(Deadline::no_slack(ZX_TIME_INFINITE_PAST)) == ZX_OK); } void WaitForAvailable(uint64_t* expected_off, uint64_t* expected_len, uint64_t* actual_supplied) { expected_off_ = expected_off; expected_len_ = expected_len; actual_supplied_ = actual_supplied; avail_sem_.Post(); wait_for_avail_sem_.Wait(Deadline::infinite()); } bool Cancel() { bool res = node_->ClearRequest(&request_); actual_supplied_ = nullptr; avail_sem_.Post(); return res; } page_request_t* request() { return &request_; } Event& drop_ref_evt() { return drop_ref_evt_; } list_node* page_list() { return &page_list_; } Event& on_pages_avail_evt() { return on_pages_avail_evt_; } private: void OnPagesAvailable(uint64_t offset, uint64_t count, uint64_t* actual_supplied) { on_pages_avail_evt_.Signal(); avail_sem_.Wait(Deadline::infinite()); if (actual_supplied_) { *expected_off_ = offset; *expected_len_ = count; *actual_supplied = 0; while (count) { vm_page_t* page; zx_status_t status = node_->AllocPage(PMM_ALLOC_DELAY_OK, &page, nullptr); if (status != ZX_OK) { break; } count--; *actual_supplied += 1; list_add_tail(&page_list_, &page->queue_node); } *actual_supplied_ = *actual_supplied; } else { *actual_supplied = count; } wait_for_avail_sem_.Post(); on_pages_avail_evt_.Unsignal(); } void OnDropRef() { drop_ref_evt_.Signal(); } PmmNode* node_; page_request_t request_; list_node page_list_ = LIST_INITIAL_VALUE(page_list_); Semaphore wait_for_avail_sem_; Semaphore avail_sem_; Event on_pages_avail_evt_; uint64_t* expected_off_; uint64_t* expected_len_; uint64_t* actual_supplied_; Event drop_ref_evt_; static void pages_available_cb(void* ctx, uint64_t offset, uint64_t count, uint64_t* actual_supplied) { static_cast<TestPageRequest*>(ctx)->OnPagesAvailable(offset, count, actual_supplied); } static void drop_ref_cb(void* ctx) { static_cast<TestPageRequest*>(ctx)->OnDropRef(); } }; // Stubbed page source that is intended to be allowed to create a vmo that believes it is backed by // a user pager, but is incapable of actually providing pages. class StubPageSource : public PageSource { public: StubPageSource() {} ~StubPageSource() {} bool GetPage(uint64_t offset, VmoDebugInfo vmo_debug_info, vm_page_t** const page_out, paddr_t* const pa_out) { return false; } void GetPageAsync(page_request_t* request) { panic("Not implemented\n"); } void ClearAsyncRequest(page_request_t* request) { panic("Not implemented\n"); } void SwapRequest(page_request_t* old, page_request_t* new_req) { panic("Not implemented\n"); } void OnDetach() {} void OnClose() {} zx_status_t WaitOnEvent(Event* event) { panic("Not implemented\n"); } }; } // namespace static zx_status_t make_committed_pager_vmo(vm_page_t** out_page, fbl::RefPtr<VmObject>* out_vmo) { // Create a pager backed VMO and jump through some hoops to pre-fill a page for it so we do not // actually take any page faults. fbl::AllocChecker ac; fbl::RefPtr<StubPageSource> pager = fbl::MakeRefCountedChecked<StubPageSource>(&ac); if (!ac.check()) { return ZX_ERR_NO_MEMORY; } fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::CreateExternal(ktl::move(pager), 0, PAGE_SIZE, &vmo); if (status != ZX_OK) { return status; } VmPageList pl; pl.InitializeSkew(0, 0); vm_page_t* page; status = pmm_alloc_page(0, &page); if (status != ZX_OK) { return status; } page->set_state(VM_PAGE_STATE_OBJECT); VmPageOrMarker* page_or_marker = pl.LookupOrAllocate(0); if (!page_or_marker) { return ZX_ERR_NO_MEMORY; } *page_or_marker = VmPageOrMarker::Page(page); VmPageSpliceList splice_list = pl.TakePages(0, PAGE_SIZE); status = vmo->SupplyPages(0, PAGE_SIZE, &splice_list); if (status != ZX_OK) { return status; } *out_page = page; *out_vmo = ktl::move(vmo); return ZX_OK; } // Allocates a single page, translates it to a vm_page_t and frees it. static bool pmm_smoke_test() { BEGIN_TEST; paddr_t pa; vm_page_t* page; zx_status_t status = pmm_alloc_page(0, &page, &pa); ASSERT_EQ(ZX_OK, status, "pmm_alloc single page"); ASSERT_NONNULL(page, "pmm_alloc single page"); ASSERT_NE(0u, pa, "pmm_alloc single page"); vm_page_t* page2 = paddr_to_vm_page(pa); ASSERT_EQ(page2, page, "paddr_to_vm_page on single page"); pmm_free_page(page); END_TEST; } // Allocates one page and frees it. static bool pmm_alloc_contiguous_one_test() { BEGIN_TEST; list_node list = LIST_INITIAL_VALUE(list); paddr_t pa; size_t count = 1U; zx_status_t status = pmm_alloc_contiguous(count, 0, PAGE_SIZE_SHIFT, &pa, &list); ASSERT_EQ(ZX_OK, status, "pmm_alloc_contiguous returned failure\n"); ASSERT_EQ(count, list_length(&list), "pmm_alloc_contiguous list size is wrong"); ASSERT_NONNULL(paddr_to_physmap(pa)); pmm_free(&list); END_TEST; } // Allocates more than one page and frees them. static bool pmm_node_multi_alloc_test() { BEGIN_TEST; ManagedPmmNode node; static constexpr size_t alloc_count = ManagedPmmNode::kNumPages / 2; list_node list = LIST_INITIAL_VALUE(list); zx_status_t status = node.node().AllocPages(alloc_count, 0, &list); EXPECT_EQ(ZX_OK, status, "pmm_alloc_pages a few pages"); EXPECT_EQ(alloc_count, list_length(&list), "pmm_alloc_pages a few pages list count"); status = node.node().AllocPages(alloc_count, 0, &list); EXPECT_EQ(ZX_OK, status, "pmm_alloc_pages a few pages"); EXPECT_EQ(2 * alloc_count, list_length(&list), "pmm_alloc_pages a few pages list count"); node.node().FreeList(&list); END_TEST; } // Allocates one page from the bulk allocation api. static bool pmm_node_singlton_list_test() { BEGIN_TEST; ManagedPmmNode node; list_node list = LIST_INITIAL_VALUE(list); zx_status_t status = node.node().AllocPages(1, 0, &list); EXPECT_EQ(ZX_OK, status, "pmm_alloc_pages a few pages"); EXPECT_EQ(1ul, list_length(&list), "pmm_alloc_pages a few pages list count"); node.node().FreeList(&list); END_TEST; } // Allocates too many pages and makes sure it fails nicely. static bool pmm_node_oversized_alloc_test() { BEGIN_TEST; ManagedPmmNode node; list_node list = LIST_INITIAL_VALUE(list); zx_status_t status = node.node().AllocPages(ManagedPmmNode::kNumPages + 1, 0, &list); EXPECT_EQ(ZX_ERR_NO_MEMORY, status, "pmm_alloc_pages failed to alloc"); EXPECT_TRUE(list_is_empty(&list), "pmm_alloc_pages list is empty"); END_TEST; } // Checks the correctness of the reported watermark level. static bool pmm_node_watermark_level_test() { BEGIN_TEST; ManagedPmmNode node; list_node list = LIST_INITIAL_VALUE(list); EXPECT_EQ(node.cur_level(), 1); while (node.node().CountFreePages() > (ManagedPmmNode::kDefaultWatermark - ManagedPmmNode::kDefaultDebounce) + 1) { vm_page_t* page; zx_status_t status = node.node().AllocPage(0, &page, nullptr); EXPECT_EQ(ZX_OK, status); EXPECT_EQ(node.cur_level(), 1); list_add_tail(&list, &page->queue_node); } vm_page_t* page; zx_status_t status = node.node().AllocPage(0, &page, nullptr); EXPECT_EQ(ZX_OK, status); EXPECT_EQ(node.cur_level(), 0); list_add_tail(&list, &page->queue_node); while (!list_is_empty(&list)) { node.node().FreePage(list_remove_head_type(&list, vm_page_t, queue_node)); uint8_t expected = node.node().CountFreePages() >= ManagedPmmNode::kDefaultWatermark + ManagedPmmNode::kDefaultDebounce; EXPECT_EQ(node.cur_level(), expected); } END_TEST; } // Checks the multiple watermark case given in the documentation for |pmm_init_reclamation|. static bool pmm_node_multi_watermark_level_test() { BEGIN_TEST; uint64_t watermarks[4] = {20 * PAGE_SIZE, 40 * PAGE_SIZE, 45 * PAGE_SIZE, 55 * PAGE_SIZE}; ManagedPmmNode node(watermarks, 4, 15); list_node list = LIST_INITIAL_VALUE(list); EXPECT_EQ(node.cur_level(), 4); auto consume_fn = [&](uint64_t level, uint64_t lower_limit) -> bool { while (node.node().CountFreePages() > lower_limit) { EXPECT_EQ(node.cur_level(), level); vm_page_t* page; zx_status_t status = node.node().AllocPage(0, &page, nullptr); EXPECT_EQ(ZX_OK, status); list_add_tail(&list, &page->queue_node); } return true; }; EXPECT_TRUE(consume_fn(4, 40)); EXPECT_TRUE(consume_fn(2, 25)); EXPECT_TRUE(consume_fn(1, 5)); auto release_fn = [&](uint64_t level, uint64_t upper_limit) -> bool { while (node.node().CountFreePages() < upper_limit) { EXPECT_EQ(node.cur_level(), level); node.node().FreePage(list_remove_head_type(&list, vm_page_t, queue_node)); } return true; }; EXPECT_TRUE(release_fn(0, 35)); EXPECT_TRUE(release_fn(1, 55)); EXPECT_TRUE(release_fn(4, node.kNumPages)); END_TEST; } // A more abstract test for multiple watermarks. static bool pmm_node_multi_watermark_level_test2() { BEGIN_TEST; static constexpr uint64_t kInterval = 7; uint64_t watermarks[MAX_WATERMARK_COUNT]; for (unsigned i = 0; i < MAX_WATERMARK_COUNT; i++) { watermarks[i] = (i + 1) * kInterval * PAGE_SIZE; } static_assert(kInterval * MAX_WATERMARK_COUNT < ManagedPmmNode::kNumPages); ManagedPmmNode node(watermarks, MAX_WATERMARK_COUNT); list_node list = LIST_INITIAL_VALUE(list); EXPECT_EQ(node.cur_level(), MAX_WATERMARK_COUNT); uint64_t count = ManagedPmmNode::kNumPages; while (node.node().CountFreePages() > 0) { vm_page_t* page; zx_status_t status = node.node().AllocPage(0, &page, nullptr); EXPECT_EQ(ZX_OK, status); list_add_tail(&list, &page->queue_node); count--; uint64_t expected = ktl::min(static_cast<uint64_t>(MAX_WATERMARK_COUNT), (count + ManagedPmmNode::kDefaultDebounce - 1) / kInterval); EXPECT_EQ(node.cur_level(), expected); } vm_page_t* page; zx_status_t status = node.node().AllocPage(0, &page, nullptr); EXPECT_EQ(ZX_ERR_NO_MEMORY, status); EXPECT_EQ(node.cur_level(), 0); while (!list_is_empty(&list)) { node.node().FreePage(list_remove_head_type(&list, vm_page_t, queue_node)); count++; uint64_t expected = ktl::min(static_cast<uint64_t>(MAX_WATERMARK_COUNT), count > ManagedPmmNode::kDefaultDebounce ? (count - ManagedPmmNode::kDefaultDebounce) / kInterval : 0); EXPECT_EQ(node.cur_level(), expected); } END_TEST; } // Checks sync allocation failure when the node is in a low-memory state. static bool pmm_node_oom_sync_alloc_failure_test() { BEGIN_TEST; ManagedPmmNode node; list_node list = LIST_INITIAL_VALUE(list); // Put the node in an oom state and make sure allocation fails. zx_status_t status = node.node().AllocPages(ManagedPmmNode::kDefaultLowMemAlloc, 0, &list); EXPECT_EQ(ZX_OK, status); EXPECT_EQ(node.cur_level(), 0); vm_page_t* page; status = node.node().AllocPage(PMM_ALLOC_DELAY_OK, &page, nullptr); EXPECT_EQ(status, ZX_ERR_NO_MEMORY); // Free the list and make sure allocations work again. node.node().FreeList(&list); status = node.node().AllocPage(PMM_ALLOC_DELAY_OK, &page, nullptr); EXPECT_EQ(ZX_OK, status); node.node().FreePage(page); END_TEST; } // Checks async allocation queued while the node is in a low-memory state. static bool pmm_node_delayed_alloc_test() { BEGIN_TEST; ManagedPmmNode node; list_node list = LIST_INITIAL_VALUE(list); zx_status_t status = node.node().AllocPages(ManagedPmmNode::kDefaultLowMemAlloc, 0, &list); EXPECT_EQ(ZX_OK, status); EXPECT_EQ(node.cur_level(), 0); vm_page_t* page; status = node.node().AllocPage(PMM_ALLOC_DELAY_OK, &page, nullptr); EXPECT_EQ(status, ZX_ERR_NO_MEMORY); static constexpr uint64_t kOffset = 1; static constexpr uint64_t kLen = 3 * ManagedPmmNode::kDefaultDebounce; TestPageRequest request(&node.node(), kOffset, kLen); node.node().AllocPages(0, request.request()); EXPECT_EQ(node.cur_level(), 0); for (unsigned i = 0; i < 2 * ManagedPmmNode::kDefaultDebounce; i++) { node.node().FreePage(list_remove_head_type(&list, vm_page, queue_node)); } EXPECT_EQ(node.cur_level(), 1); uint64_t expected_off, expected_len, actual_supplied; request.WaitForAvailable(&expected_off, &expected_len, &actual_supplied); EXPECT_EQ(expected_off, kOffset); EXPECT_EQ(expected_len, kLen); EXPECT_EQ(actual_supplied, 2 * ManagedPmmNode::kDefaultDebounce); EXPECT_EQ(request.drop_ref_evt().Wait(Deadline::no_slack(ZX_TIME_INFINITE_PAST)), ZX_ERR_TIMED_OUT); node.node().FreeList(&list); request.WaitForAvailable(&expected_off, &expected_len, &actual_supplied); EXPECT_EQ(expected_off, kOffset + 2 * ManagedPmmNode::kDefaultDebounce); EXPECT_EQ(expected_len, kLen - 2 * ManagedPmmNode::kDefaultDebounce); EXPECT_EQ(actual_supplied, kLen - 2 * ManagedPmmNode::kDefaultDebounce); EXPECT_EQ(request.drop_ref_evt().Wait(Deadline::no_slack(ZX_TIME_INFINITE)), ZX_OK); EXPECT_EQ(list_length(request.page_list()), kLen); node.node().FreeList(request.page_list()); END_TEST; } // Checks async allocation queued while the node is not in a low-memory state. static bool pmm_node_delayed_alloc_no_lowmem_test() { BEGIN_TEST; ManagedPmmNode node; TestPageRequest request(&node.node(), 0, 1); node.node().AllocPages(0, request.request()); uint64_t expected_off, expected_len, actual_supplied; request.WaitForAvailable(&expected_off, &expected_len, &actual_supplied); EXPECT_EQ(expected_off, 0ul); EXPECT_EQ(expected_len, 1ul); EXPECT_EQ(actual_supplied, 1ul); EXPECT_EQ(request.drop_ref_evt().Wait(Deadline::no_slack(ZX_TIME_INFINITE)), ZX_OK); EXPECT_EQ(list_length(request.page_list()), 1ul); node.node().FreeList(request.page_list()); END_TEST; } // Checks swapping out the page_request_t backing a request, either before the request // starts being serviced or while the request is being serviced (depending on |early|). static bool pmm_node_delayed_alloc_swap_test_helper(bool early) { BEGIN_TEST; ManagedPmmNode node; list_node list = LIST_INITIAL_VALUE(list); zx_status_t status = node.node().AllocPages(ManagedPmmNode::kDefaultLowMemAlloc, 0, &list); EXPECT_EQ(ZX_OK, status); EXPECT_EQ(node.cur_level(), 0); vm_page_t* page; status = node.node().AllocPage(PMM_ALLOC_DELAY_OK, &page, nullptr); EXPECT_EQ(status, ZX_ERR_NO_MEMORY); TestPageRequest request(&node.node(), 0, 1); node.node().AllocPages(0, request.request()); page_request_t new_mem = *request.request(); if (early) { node.node().SwapRequest(request.request(), &new_mem); } EXPECT_EQ(node.cur_level(), 0); for (unsigned i = 0; i < 2 * ManagedPmmNode::kDefaultDebounce; i++) { node.node().FreePage(list_remove_head_type(&list, vm_page, queue_node)); } EXPECT_EQ(node.cur_level(), 1); if (!early) { EXPECT_EQ(request.on_pages_avail_evt().Wait(Deadline::infinite()), ZX_OK); node.node().SwapRequest(request.request(), &new_mem); } uint64_t expected_off, expected_len, actual_supplied; request.WaitForAvailable(&expected_off, &expected_len, &actual_supplied); EXPECT_EQ(expected_off, 0ul); EXPECT_EQ(expected_len, 1ul); EXPECT_EQ(actual_supplied, 1ul); EXPECT_EQ(request.drop_ref_evt().Wait(Deadline::infinite()), ZX_OK); EXPECT_EQ(list_length(request.page_list()), 1ul); node.node().FreeList(&list); node.node().FreeList(request.page_list()); END_TEST; } static bool pmm_node_delayed_alloc_swap_early_test() { return pmm_node_delayed_alloc_swap_test_helper(true); } static bool pmm_node_delayed_alloc_swap_late_test() { return pmm_node_delayed_alloc_swap_test_helper(false); } // Checks cancelling the page_request_t backing a request, either before the request // starts being serviced or while the request is being serviced (depending on |early|). static bool pmm_node_delayed_alloc_clear_test_helper(bool early) { BEGIN_TEST; ManagedPmmNode node; list_node list = LIST_INITIAL_VALUE(list); zx_status_t status = node.node().AllocPages(ManagedPmmNode::kDefaultLowMemAlloc, 0, &list); EXPECT_EQ(ZX_OK, status); EXPECT_EQ(node.cur_level(), 0); vm_page_t* page; status = node.node().AllocPage(PMM_ALLOC_DELAY_OK, &page, nullptr); EXPECT_EQ(status, ZX_ERR_NO_MEMORY); TestPageRequest request(&node.node(), 0, 1); node.node().AllocPages(0, request.request()); if (early) { EXPECT_TRUE(request.Cancel()); } EXPECT_EQ(node.cur_level(), 0); for (unsigned i = 0; i < 2 * ManagedPmmNode::kDefaultDebounce; i++) { node.node().FreePage(list_remove_head_type(&list, vm_page, queue_node)); } EXPECT_EQ(node.cur_level(), 1); if (!early) { EXPECT_EQ(request.on_pages_avail_evt().Wait(Deadline::infinite()), ZX_OK); EXPECT_FALSE(request.Cancel()); EXPECT_EQ(request.drop_ref_evt().Wait(Deadline::infinite()), ZX_OK); } else { EXPECT_EQ(request.drop_ref_evt().Wait(Deadline::no_slack(ZX_TIME_INFINITE_PAST)), ZX_ERR_TIMED_OUT); request.drop_ref_evt().Signal(); } EXPECT_EQ(list_length(request.page_list()), 0ul); node.node().FreeList(&list); END_TEST; } static bool pmm_node_delayed_alloc_clear_early_test() { return pmm_node_delayed_alloc_clear_test_helper(true); } static bool pmm_node_delayed_alloc_clear_late_test() { return pmm_node_delayed_alloc_clear_test_helper(false); } static bool pmm_checker_test_with_fill_size(size_t fill_size) { BEGIN_TEST; PmmChecker checker; // Starts off unarmed. EXPECT_FALSE(checker.IsArmed()); // Borrow a real page from the PMM, ask the checker to validate it. See that because the checker // is not armed, |ValidatePattern| still returns true even though the page has no pattern. vm_page_t* page; EXPECT_EQ(pmm_alloc_page(0, &page), ZX_OK); page->set_state(VM_PAGE_STATE_FREE); auto p = static_cast<uint8_t*>(paddr_to_physmap(page->paddr())); memset(p, 0, PAGE_SIZE); EXPECT_TRUE(checker.ValidatePattern(page)); checker.AssertPattern(page); // Set the fill size and see that |GetFillSize| returns the size. checker.SetFillSize(fill_size); EXPECT_EQ(fill_size, checker.GetFillSize()); // Arm the checker and see that |ValidatePattern| returns false. checker.Arm(); EXPECT_TRUE(checker.IsArmed()); EXPECT_FALSE(checker.ValidatePattern(page)); // Fill with pattern one less than the fill size and see that it does not pass validation. memset(p, 0, fill_size - 1); EXPECT_FALSE(checker.ValidatePattern(page)); // Fill with the full pattern and see that it validates. checker.FillPattern(page); for (size_t i = 0; i < fill_size; ++i) { EXPECT_NE(0, p[i]); } EXPECT_TRUE(checker.ValidatePattern(page)); // Corrupt the page after the first |fill_size| bytes and see that the corruption is not detected. if (fill_size < PAGE_SIZE) { p[fill_size] = 1; EXPECT_TRUE(checker.ValidatePattern(page)); } // Corrupt the page within the first |fill_size| bytes and see that the corruption is detected. p[fill_size - 1] = 1; EXPECT_FALSE(checker.ValidatePattern(page)); // Disarm the checker and see that it now passes. checker.Disarm(); EXPECT_FALSE(checker.IsArmed()); EXPECT_TRUE(checker.ValidatePattern(page)); checker.AssertPattern(page); page->set_state(VM_PAGE_STATE_ALLOC); pmm_free_page(page); END_TEST; } static bool pmm_checker_test() { BEGIN_TEST; EXPECT_TRUE(pmm_checker_test_with_fill_size(8)); EXPECT_TRUE(pmm_checker_test_with_fill_size(16)); EXPECT_TRUE(pmm_checker_test_with_fill_size(512)); EXPECT_TRUE(pmm_checker_test_with_fill_size(PAGE_SIZE)); END_TEST; } static bool pmm_checker_is_valid_fill_size_test() { BEGIN_TEST; EXPECT_FALSE(PmmChecker::IsValidFillSize(0)); EXPECT_FALSE(PmmChecker::IsValidFillSize(7)); EXPECT_FALSE(PmmChecker::IsValidFillSize(9)); EXPECT_FALSE(PmmChecker::IsValidFillSize(PAGE_SIZE + 8)); EXPECT_FALSE(PmmChecker::IsValidFillSize(PAGE_SIZE * 2)); EXPECT_TRUE(PmmChecker::IsValidFillSize(8)); EXPECT_TRUE(PmmChecker::IsValidFillSize(16)); EXPECT_TRUE(PmmChecker::IsValidFillSize(24)); EXPECT_TRUE(PmmChecker::IsValidFillSize(512)); EXPECT_TRUE(PmmChecker::IsValidFillSize(PAGE_SIZE)); END_TEST; } static bool pmm_get_arena_info_test() { BEGIN_TEST; const size_t num_arenas = pmm_num_arenas(); ASSERT_GT(num_arenas, 0u); fbl::AllocChecker ac; auto buffer = ktl::unique_ptr<pmm_arena_info_t[]>(new (&ac) pmm_arena_info_t[num_arenas]); ASSERT(ac.check()); const size_t buffer_size = num_arenas * sizeof(pmm_arena_info_t); // Not enough room for one. zx_status_t status = pmm_get_arena_info(1, 0, buffer.get(), sizeof(pmm_arena_info_t) - 1); ASSERT_EQ(status, ZX_ERR_BUFFER_TOO_SMALL); // Asking for none. status = pmm_get_arena_info(0, 0, buffer.get(), buffer_size); ASSERT_EQ(status, ZX_ERR_OUT_OF_RANGE); // Asking for more than exist. status = pmm_get_arena_info(num_arenas + 1, 0, buffer.get(), buffer_size); ASSERT_EQ(status, ZX_ERR_OUT_OF_RANGE); // Attempting to skip them all. status = pmm_get_arena_info(1, num_arenas, buffer.get(), buffer_size); ASSERT_EQ(status, ZX_ERR_OUT_OF_RANGE); // Asking for one. status = pmm_get_arena_info(1, 0, buffer.get(), buffer_size); ASSERT_EQ(status, ZX_OK); // Asking for them all. status = pmm_get_arena_info(num_arenas, 0, buffer.get(), buffer_size); ASSERT_EQ(status, ZX_OK); // See they are in ascending order by base. paddr_t prev = 0; for (unsigned i = 0; i < num_arenas; ++i) { if (i == 0) { ASSERT_GE(buffer[i].base, prev); } else { ASSERT_GT(buffer[i].base, prev); } prev = buffer[i].base; ASSERT_GT(buffer[i].size, 0u); } END_TEST; } static uint32_t test_rand(uint32_t seed) { return (seed = seed * 1664525 + 1013904223); } // These two functions do direct access to specially-mapped memory that is // outside the normal range of kernel pointers. Hence any memory access instrumentation // instrumentation needs to be disabled in these functions. // fill a region of memory with a pattern based on the address of the region NO_ASAN static void fill_region(uintptr_t seed, void* _ptr, size_t len) { uint32_t* ptr = (uint32_t*)_ptr; ASSERT(IS_ALIGNED((uintptr_t)ptr, 4)); uint32_t val = (uint32_t)seed; #if UINTPTR_MAX > UINT32_MAX val ^= (uint32_t)(seed >> 32); #endif for (size_t i = 0; i < len / 4; i++) { ptr[i] = val; val = test_rand(val); } } // test a region of memory against a known pattern NO_ASAN static bool test_region(uintptr_t seed, void* _ptr, size_t len) { uint32_t* ptr = (uint32_t*)_ptr; ASSERT(IS_ALIGNED((uintptr_t)ptr, 4)); uint32_t val = (uint32_t)seed; #if UINTPTR_MAX > UINT32_MAX val ^= (uint32_t)(seed >> 32); #endif for (size_t i = 0; i < len / 4; i++) { if (ptr[i] != val) { unittest_printf("value at %p (%zu) is incorrect: 0x%x vs 0x%x\n", &ptr[i], i, ptr[i], val); return false; } val = test_rand(val); } return true; } static bool fill_and_test(void* ptr, size_t len) { BEGIN_TEST; // fill it with a pattern fill_region((uintptr_t)ptr, ptr, len); // test that the pattern is read back properly auto result = test_region((uintptr_t)ptr, ptr, len); EXPECT_TRUE(result, "testing region for corruption"); END_TEST; } // Allocates a region in kernel space, reads/writes it, then destroys it. static bool vmm_alloc_smoke_test() { BEGIN_TEST; static const size_t alloc_size = 256 * 1024; // allocate a region of memory void* ptr; auto kaspace = VmAspace::kernel_aspace(); auto err = kaspace->Alloc("test", alloc_size, &ptr, 0, 0, kArchRwFlags); ASSERT_EQ(ZX_OK, err, "VmAspace::Alloc region of memory"); ASSERT_NONNULL(ptr, "VmAspace::Alloc region of memory"); // fill with known pattern and test if (!fill_and_test(ptr, alloc_size)) { all_ok = false; } // free the region err = kaspace->FreeRegion(reinterpret_cast<vaddr_t>(ptr)); EXPECT_EQ(ZX_OK, err, "VmAspace::FreeRegion region of memory"); END_TEST; } // Allocates a contiguous region in kernel space, reads/writes it, // then destroys it. static bool vmm_alloc_contiguous_smoke_test() { BEGIN_TEST; static const size_t alloc_size = 256 * 1024; // allocate a region of memory void* ptr; auto kaspace = VmAspace::kernel_aspace(); auto err = kaspace->AllocContiguous("test", alloc_size, &ptr, 0, VmAspace::VMM_FLAG_COMMIT, kArchRwFlags); ASSERT_EQ(ZX_OK, err, "VmAspace::AllocContiguous region of memory"); ASSERT_NONNULL(ptr, "VmAspace::AllocContiguous region of memory"); // fill with known pattern and test if (!fill_and_test(ptr, alloc_size)) { all_ok = false; } // test that it is indeed contiguous unittest_printf("testing that region is contiguous\n"); paddr_t last_pa = 0; for (size_t i = 0; i < alloc_size / PAGE_SIZE; i++) { paddr_t pa = vaddr_to_paddr((uint8_t*)ptr + i * PAGE_SIZE); if (last_pa != 0) { EXPECT_EQ(pa, last_pa + PAGE_SIZE, "region is contiguous"); } last_pa = pa; } // free the region err = kaspace->FreeRegion(reinterpret_cast<vaddr_t>(ptr)); EXPECT_EQ(ZX_OK, err, "VmAspace::FreeRegion region of memory"); END_TEST; } // Allocates a new address space and creates a few regions in it, // then destroys it. static bool multiple_regions_test() { BEGIN_TEST; // As we create a user aspace whose pointers we will directly touch we must disable the scanner // to prevent our mappings from being removed from underneath us. AutoVmScannerDisable scanner_disable; void* ptr; static const size_t alloc_size = 16 * 1024; fbl::RefPtr<VmAspace> aspace = VmAspace::Create(0, "test aspace"); ASSERT_NONNULL(aspace, "VmAspace::Create pointer"); VmAspace* old_aspace = Thread::Current::Get()->aspace(); vmm_set_active_aspace(aspace.get()); // allocate region 0 zx_status_t err = aspace->Alloc("test0", alloc_size, &ptr, 0, 0, kArchRwFlags); ASSERT_EQ(ZX_OK, err, "VmAspace::Alloc region of memory"); ASSERT_NONNULL(ptr, "VmAspace::Alloc region of memory"); // fill with known pattern and test if (!fill_and_test(ptr, alloc_size)) { all_ok = false; } // allocate region 1 err = aspace->Alloc("test1", 16384, &ptr, 0, 0, kArchRwFlags); ASSERT_EQ(ZX_OK, err, "VmAspace::Alloc region of memory"); ASSERT_NONNULL(ptr, "VmAspace::Alloc region of memory"); // fill with known pattern and test if (!fill_and_test(ptr, alloc_size)) { all_ok = false; } // allocate region 2 err = aspace->Alloc("test2", 16384, &ptr, 0, 0, kArchRwFlags); ASSERT_EQ(ZX_OK, err, "VmAspace::Alloc region of memory"); ASSERT_NONNULL(ptr, "VmAspace::Alloc region of memory"); // fill with known pattern and test if (!fill_and_test(ptr, alloc_size)) { all_ok = false; } vmm_set_active_aspace(old_aspace); // free the address space all at once err = aspace->Destroy(); EXPECT_EQ(ZX_OK, err, "VmAspace::Destroy"); END_TEST; } static bool vmm_alloc_zero_size_fails() { BEGIN_TEST; const size_t zero_size = 0; void* ptr; zx_status_t err = VmAspace::kernel_aspace()->Alloc("test", zero_size, &ptr, 0, 0, kArchRwFlags); ASSERT_EQ(ZX_ERR_INVALID_ARGS, err); END_TEST; } static bool vmm_alloc_bad_specific_pointer_fails() { BEGIN_TEST; // bad specific pointer void* ptr = (void*)1; zx_status_t err = VmAspace::kernel_aspace()->Alloc( "test", 16384, &ptr, 0, VmAspace::VMM_FLAG_VALLOC_SPECIFIC | VmAspace::VMM_FLAG_COMMIT, kArchRwFlags); ASSERT_EQ(ZX_ERR_INVALID_ARGS, err); END_TEST; } static bool vmm_alloc_contiguous_missing_flag_commit_fails() { BEGIN_TEST; // should have VmAspace::VMM_FLAG_COMMIT const uint zero_vmm_flags = 0; void* ptr; zx_status_t err = VmAspace::kernel_aspace()->AllocContiguous("test", 4096, &ptr, 0, zero_vmm_flags, kArchRwFlags); ASSERT_EQ(ZX_ERR_INVALID_ARGS, err); END_TEST; } static bool vmm_alloc_contiguous_zero_size_fails() { BEGIN_TEST; const size_t zero_size = 0; void* ptr; zx_status_t err = VmAspace::kernel_aspace()->AllocContiguous( "test", zero_size, &ptr, 0, VmAspace::VMM_FLAG_COMMIT, kArchRwFlags); ASSERT_EQ(ZX_ERR_INVALID_ARGS, err); END_TEST; } // Allocates a vm address space object directly, allows it to go out of scope. static bool vmaspace_create_smoke_test() { BEGIN_TEST; auto aspace = VmAspace::Create(0, "test aspace"); zx_status_t err = aspace->Destroy(); EXPECT_EQ(ZX_OK, err, "VmAspace::Destroy"); END_TEST; } // Allocates a vm address space object directly, maps something on it, // allows it to go out of scope. static bool vmaspace_alloc_smoke_test() { BEGIN_TEST; auto aspace = VmAspace::Create(0, "test aspace2"); void* ptr; auto err = aspace->Alloc("test", PAGE_SIZE, &ptr, 0, 0, kArchRwFlags); ASSERT_EQ(ZX_OK, err, "allocating region\n"); // destroy the aspace, which should drop all the internal refs to it err = aspace->Destroy(); EXPECT_EQ(ZX_OK, err, "VmAspace::Destroy"); // drop the ref held by this pointer aspace.reset(); END_TEST; } // Touch mappings in an aspace and ensure we can correctly harvest the accessed bits. static bool vmaspace_accessed_test() { BEGIN_TEST; AutoVmScannerDisable scanner_disable; // Create some memory we can map touch to test accessed tracking on. Needs to be created from // user pager backed memory as harvesting is allowed to be limited to just that. vm_page_t* page; fbl::RefPtr<VmObject> vmo; zx_status_t status = make_committed_pager_vmo(&page, &vmo); ASSERT_EQ(ZX_OK, status); auto mem = testing::UserMemory::Create(vmo); ASSERT_EQ(ZX_OK, mem->CommitAndMap(PAGE_SIZE)); // Helpers for query the arch aspace. auto harvest_take = [&mem, &page]() { int found = 0; ArchVmAspace::HarvestCallback harvest = [&found, &mem, &page](paddr_t paddr, vaddr_t vaddr, uint mmu_flags) { found++; DEBUG_ASSERT(vaddr == mem->base()); DEBUG_ASSERT(paddr == page->paddr()); return true; }; mem->aspace()->arch_aspace().HarvestAccessed(mem->base(), 1, harvest); return found; }; auto harvest_leave = [&mem, &page]() { int found = 0; ArchVmAspace::HarvestCallback harvest = [&found, &mem, &page](paddr_t paddr, vaddr_t vaddr, uint mmu_flags) { found++; DEBUG_ASSERT(vaddr == mem->base()); DEBUG_ASSERT(paddr == page->paddr()); return false; }; mem->aspace()->arch_aspace().HarvestAccessed(mem->base(), 1, harvest); return found; }; // Initial accessed state is undefined, so harvest it away. mem->vmo()->HarvestAccessedBits(); // Reach into the arch aspace and check that the accessed bit is really gone. EXPECT_EQ(0, harvest_take()); // Read from the mapping to (hopefully) set the accessed bit. asm volatile("" ::"r"(mem->get<int>(0)) : "memory"); // Query the arch aspace and make sure we can leave and take the accessed bit. EXPECT_EQ(1, harvest_leave()); EXPECT_EQ(1, harvest_leave()); EXPECT_EQ(1, harvest_take()); EXPECT_EQ(0, harvest_take()); // Set the accessed bit again and see if the VMO can harvest it. asm volatile("" ::"r"(mem->get<int>(0)) : "memory"); EXPECT_EQ(1, harvest_leave()); mem->vmo()->HarvestAccessedBits(); EXPECT_EQ(0, harvest_take()); END_TEST; } // Ensure that if a user requested VMO read/write operation would hit a page that has had its // accessed bits harvested that any resulting fault (on ARM) can be handled. static bool vmaspace_usercopy_accessed_fault_test() { BEGIN_TEST; AutoVmScannerDisable scanner_disable; // Create some memory we can map touch to test accessed tracking on. Needs to be created from // user pager backed memory as harvesting is allowed to be limited to just that. vm_page_t* page; fbl::RefPtr<VmObject> mapping_vmo; zx_status_t status = make_committed_pager_vmo(&page, &mapping_vmo); ASSERT_EQ(ZX_OK, status); auto mem = testing::UserMemory::Create(mapping_vmo); ASSERT_EQ(ZX_OK, mem->CommitAndMap(PAGE_SIZE)); // Need a separate VMO to read/write from. fbl::RefPtr<VmObject> vmo; status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, PAGE_SIZE, &vmo); ASSERT_EQ(status, ZX_OK); // Touch the mapping to make sure it is committed and mapped. mem->put<char>(42); // Harvest any accessed bits. mem->vmo()->HarvestAccessedBits(); // Read from the VMO into the mapping that has been harvested. status = vmo->ReadUser(Thread::Current::Get()->aspace(), mem->user_out<char>(), 0, sizeof(char)); ASSERT_EQ(status, ZX_OK); END_TEST; } // Doesn't do anything, just prints all aspaces. // Should be run after all other tests so that people can manually comb // through the output for leaked test aspaces. static bool dump_all_aspaces() { BEGIN_TEST; unittest_printf("verify there are no test aspaces left around\n"); DumpAllAspaces(/*verbose*/ true); END_TEST; } // Creates a vm object. static bool vmo_create_test() { BEGIN_TEST; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, PAGE_SIZE, &vmo); ASSERT_EQ(status, ZX_OK); ASSERT_TRUE(vmo); EXPECT_FALSE(vmo->is_contiguous(), "vmo is not contig\n"); EXPECT_FALSE(vmo->is_resizable(), "vmo is not resizable\n"); END_TEST; } static bool vmo_create_maximum_size() { BEGIN_TEST; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, 0xfffffffffffe0000, &vmo); EXPECT_EQ(status, ZX_OK, "should be ok\n"); status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, 0xfffffffffffe1000, &vmo); EXPECT_EQ(status, ZX_ERR_OUT_OF_RANGE, "should be too large\n"); END_TEST; } // Helper that tests if all pages in a vmo in the specified range pass the given predicate. template <typename F> static bool AllPagesMatch(VmObject* vmo, F pred, uint64_t offset, uint64_t len) { struct Context { bool result; F pred; } context = {true, ktl::move(pred)}; zx_status_t status = vmo->Lookup( offset, len, [](void* context, size_t offset, size_t index, paddr_t pa) { Context* c = reinterpret_cast<Context*>(context); const vm_page_t* p = paddr_to_vm_page(pa); if (!c->pred(p)) { c->result = false; return ZX_ERR_STOP; } return ZX_OK; }, &context); return status == ZX_OK ? context.result : false; } static bool PagesInUnswappableZeroForkQueue(VmObject* vmo, uint64_t offset, uint64_t len) { return AllPagesMatch( vmo, [](const vm_page_t* p) { return pmm_page_queues()->DebugPageIsUnswappableZeroFork(p); }, offset, len); } static bool PagesInAnyUnswappableQueue(VmObject* vmo, uint64_t offset, uint64_t len) { return AllPagesMatch( vmo, [](const vm_page_t* p) { return pmm_page_queues()->DebugPageIsAnyUnswappable(p); }, offset, len); } static bool PagesInWiredQueue(VmObject* vmo, uint64_t offset, uint64_t len) { return AllPagesMatch( vmo, [](const vm_page_t* p) { return pmm_page_queues()->DebugPageIsWired(p); }, offset, len); } // Creates a vm object, commits memory. static bool vmo_commit_test() { BEGIN_TEST; AutoVmScannerDisable scanner_disable; static const size_t alloc_size = PAGE_SIZE * 16; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, alloc_size, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); auto ret = vmo->CommitRange(0, alloc_size); ASSERT_EQ(ZX_OK, ret, "committing vm object\n"); EXPECT_EQ(ROUNDUP_PAGE_SIZE(alloc_size), PAGE_SIZE * vmo->AttributedPages(), "committing vm object\n"); EXPECT_TRUE(PagesInAnyUnswappableQueue(vmo.get(), 0, alloc_size)); END_TEST; } // Creates a paged VMO, pins it, and tries operations that should unpin it. static bool vmo_pin_test() { BEGIN_TEST; AutoVmScannerDisable scanner_disable; static const size_t alloc_size = PAGE_SIZE * 16; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, VmObjectPaged::kResizable, alloc_size, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); status = vmo->CommitRangePinned(PAGE_SIZE, alloc_size); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, status, "pinning out of range\n"); status = vmo->CommitRangePinned(PAGE_SIZE, 0); EXPECT_EQ(ZX_ERR_INVALID_ARGS, status, "pinning range of len 0\n"); status = vmo->CommitRangePinned(PAGE_SIZE, 3 * PAGE_SIZE); EXPECT_EQ(ZX_OK, status, "pinning committed range\n"); EXPECT_TRUE(PagesInWiredQueue(vmo.get(), PAGE_SIZE, 3 * PAGE_SIZE)); status = vmo->DecommitRange(PAGE_SIZE, 3 * PAGE_SIZE); EXPECT_EQ(ZX_ERR_BAD_STATE, status, "decommitting pinned range\n"); status = vmo->DecommitRange(PAGE_SIZE, PAGE_SIZE); EXPECT_EQ(ZX_ERR_BAD_STATE, status, "decommitting pinned range\n"); status = vmo->DecommitRange(3 * PAGE_SIZE, PAGE_SIZE); EXPECT_EQ(ZX_ERR_BAD_STATE, status, "decommitting pinned range\n"); vmo->Unpin(PAGE_SIZE, 3 * PAGE_SIZE); EXPECT_TRUE(PagesInAnyUnswappableQueue(vmo.get(), PAGE_SIZE, 3 * PAGE_SIZE)); status = vmo->DecommitRange(PAGE_SIZE, 3 * PAGE_SIZE); EXPECT_EQ(ZX_OK, status, "decommitting unpinned range\n"); status = vmo->CommitRangePinned(PAGE_SIZE, 3 * PAGE_SIZE); EXPECT_EQ(ZX_OK, status, "pinning committed range\n"); EXPECT_TRUE(PagesInWiredQueue(vmo.get(), PAGE_SIZE, 3 * PAGE_SIZE)); status = vmo->Resize(0); EXPECT_EQ(ZX_ERR_BAD_STATE, status, "resizing pinned range\n"); vmo->Unpin(PAGE_SIZE, 3 * PAGE_SIZE); status = vmo->Resize(0); EXPECT_EQ(ZX_OK, status, "resizing unpinned range\n"); END_TEST; } // Creates a page VMO and pins the same pages multiple times static bool vmo_multiple_pin_test() { BEGIN_TEST; AutoVmScannerDisable scanner_disable; static const size_t alloc_size = PAGE_SIZE * 16; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, alloc_size, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); status = vmo->CommitRangePinned(0, alloc_size); EXPECT_EQ(ZX_OK, status, "pinning whole range\n"); EXPECT_TRUE(PagesInWiredQueue(vmo.get(), 0, alloc_size)); status = vmo->CommitRangePinned(PAGE_SIZE, 4 * PAGE_SIZE); EXPECT_EQ(ZX_OK, status, "pinning subrange\n"); EXPECT_TRUE(PagesInWiredQueue(vmo.get(), 0, alloc_size)); for (unsigned int i = 1; i < VM_PAGE_OBJECT_MAX_PIN_COUNT; ++i) { status = vmo->CommitRangePinned(0, PAGE_SIZE); EXPECT_EQ(ZX_OK, status, "pinning first page max times\n"); } status = vmo->CommitRangePinned(0, PAGE_SIZE); EXPECT_EQ(ZX_ERR_UNAVAILABLE, status, "page is pinned too much\n"); vmo->Unpin(0, alloc_size); EXPECT_TRUE(PagesInWiredQueue(vmo.get(), PAGE_SIZE, 4 * PAGE_SIZE)); EXPECT_TRUE(PagesInAnyUnswappableQueue(vmo.get(), 5 * PAGE_SIZE, alloc_size - 5 * PAGE_SIZE)); status = vmo->DecommitRange(PAGE_SIZE, 4 * PAGE_SIZE); EXPECT_EQ(ZX_ERR_BAD_STATE, status, "decommitting pinned range\n"); status = vmo->DecommitRange(5 * PAGE_SIZE, alloc_size - 5 * PAGE_SIZE); EXPECT_EQ(ZX_OK, status, "decommitting unpinned range\n"); vmo->Unpin(PAGE_SIZE, 4 * PAGE_SIZE); status = vmo->DecommitRange(PAGE_SIZE, 4 * PAGE_SIZE); EXPECT_EQ(ZX_OK, status, "decommitting unpinned range\n"); for (unsigned int i = 2; i < VM_PAGE_OBJECT_MAX_PIN_COUNT; ++i) { vmo->Unpin(0, PAGE_SIZE); } status = vmo->DecommitRange(0, PAGE_SIZE); EXPECT_EQ(ZX_ERR_BAD_STATE, status, "decommitting unpinned range\n"); vmo->Unpin(0, PAGE_SIZE); status = vmo->DecommitRange(0, PAGE_SIZE); EXPECT_EQ(ZX_OK, status, "decommitting unpinned range\n"); END_TEST; } // Creates a vm object, commits odd sized memory. static bool vmo_odd_size_commit_test() { BEGIN_TEST; AutoVmScannerDisable scanner_disable; static const size_t alloc_size = 15; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, alloc_size, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); auto ret = vmo->CommitRange(0, alloc_size); EXPECT_EQ(ZX_OK, ret, "committing vm object\n"); EXPECT_EQ(ROUNDUP_PAGE_SIZE(alloc_size), PAGE_SIZE * vmo->AttributedPages(), "committing vm object\n"); END_TEST; } static bool vmo_create_physical_test() { BEGIN_TEST; paddr_t pa; vm_page_t* vm_page; zx_status_t status = pmm_alloc_page(0, &vm_page, &pa); uint32_t cache_policy; ASSERT_EQ(ZX_OK, status, "vm page allocation\n"); ASSERT_TRUE(vm_page); fbl::RefPtr<VmObject> vmo; status = VmObjectPhysical::Create(pa, PAGE_SIZE, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); cache_policy = vmo->GetMappingCachePolicy(); EXPECT_EQ(ARCH_MMU_FLAG_UNCACHED, cache_policy, "check initial cache policy"); EXPECT_TRUE(vmo->is_contiguous(), "check contiguous"); pmm_free_page(vm_page); END_TEST; } // Creates a vm object that commits contiguous memory. static bool vmo_create_contiguous_test() { BEGIN_TEST; static const size_t alloc_size = PAGE_SIZE * 16; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::CreateContiguous(PMM_ALLOC_FLAG_ANY, alloc_size, 0, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); EXPECT_TRUE(vmo->is_contiguous(), "vmo is contig\n"); EXPECT_TRUE(PagesInWiredQueue(vmo.get(), 0, alloc_size)); paddr_t last_pa; auto lookup_func = [](void* ctx, size_t offset, size_t index, paddr_t pa) { paddr_t* last_pa = static_cast<paddr_t*>(ctx); if (index != 0 && *last_pa + PAGE_SIZE != pa) { return ZX_ERR_BAD_STATE; } *last_pa = pa; return ZX_OK; }; status = vmo->Lookup(0, alloc_size, lookup_func, &last_pa); EXPECT_EQ(status, ZX_OK, "vmo lookup\n"); END_TEST; } // Make sure decommitting is disallowed static bool vmo_contiguous_decommit_test() { BEGIN_TEST; static const size_t alloc_size = PAGE_SIZE * 16; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::CreateContiguous(PMM_ALLOC_FLAG_ANY, alloc_size, 0, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); status = vmo->DecommitRange(PAGE_SIZE, 4 * PAGE_SIZE); ASSERT_EQ(status, ZX_ERR_NOT_SUPPORTED, "decommit fails due to pinned pages\n"); status = vmo->DecommitRange(0, 4 * PAGE_SIZE); ASSERT_EQ(status, ZX_ERR_NOT_SUPPORTED, "decommit fails due to pinned pages\n"); status = vmo->DecommitRange(alloc_size - PAGE_SIZE, PAGE_SIZE); ASSERT_EQ(status, ZX_ERR_NOT_SUPPORTED, "decommit fails due to pinned pages\n"); // Make sure all pages are still present and contiguous paddr_t last_pa; auto lookup_func = [](void* ctx, size_t offset, size_t index, paddr_t pa) { paddr_t* last_pa = static_cast<paddr_t*>(ctx); if (index != 0 && *last_pa + PAGE_SIZE != pa) { return ZX_ERR_BAD_STATE; } *last_pa = pa; return ZX_OK; }; status = vmo->Lookup(0, alloc_size, lookup_func, &last_pa); ASSERT_EQ(status, ZX_OK, "vmo lookup\n"); END_TEST; } // Creats a vm object, maps it, precommitted. static bool vmo_precommitted_map_test() { BEGIN_TEST; static const size_t alloc_size = PAGE_SIZE * 16; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0, alloc_size, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); auto ka = VmAspace::kernel_aspace(); void* ptr; auto ret = ka->MapObjectInternal(vmo, "test", 0, alloc_size, &ptr, 0, VmAspace::VMM_FLAG_COMMIT, kArchRwFlags); ASSERT_EQ(ZX_OK, ret, "mapping object"); // fill with known pattern and test if (!fill_and_test(ptr, alloc_size)) { all_ok = false; } auto err = ka->FreeRegion((vaddr_t)ptr); EXPECT_EQ(ZX_OK, err, "unmapping object"); END_TEST; } // Creates a vm object, maps it, demand paged. static bool vmo_demand_paged_map_test() { BEGIN_TEST; static const size_t alloc_size = PAGE_SIZE * 16; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, alloc_size, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); auto ka = VmAspace::kernel_aspace(); void* ptr; auto ret = ka->MapObjectInternal(vmo, "test", 0, alloc_size, &ptr, 0, 0, kArchRwFlags); ASSERT_EQ(ret, ZX_OK, "mapping object"); // fill with known pattern and test if (!fill_and_test(ptr, alloc_size)) { all_ok = false; } auto err = ka->FreeRegion((vaddr_t)ptr); EXPECT_EQ(ZX_OK, err, "unmapping object"); END_TEST; } // Creates a vm object, maps it, drops ref before unmapping. static bool vmo_dropped_ref_test() { BEGIN_TEST; static const size_t alloc_size = PAGE_SIZE * 16; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, alloc_size, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); auto ka = VmAspace::kernel_aspace(); void* ptr; auto ret = ka->MapObjectInternal(ktl::move(vmo), "test", 0, alloc_size, &ptr, 0, VmAspace::VMM_FLAG_COMMIT, kArchRwFlags); ASSERT_EQ(ret, ZX_OK, "mapping object"); EXPECT_NULL(vmo, "dropped ref to object"); // fill with known pattern and test if (!fill_and_test(ptr, alloc_size)) { all_ok = false; } auto err = ka->FreeRegion((vaddr_t)ptr); EXPECT_EQ(ZX_OK, err, "unmapping object"); END_TEST; } // Creates a vm object, maps it, fills it with data, unmaps, // maps again somewhere else. static bool vmo_remap_test() { BEGIN_TEST; static const size_t alloc_size = PAGE_SIZE * 16; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, alloc_size, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); auto ka = VmAspace::kernel_aspace(); void* ptr; auto ret = ka->MapObjectInternal(vmo, "test", 0, alloc_size, &ptr, 0, VmAspace::VMM_FLAG_COMMIT, kArchRwFlags); ASSERT_EQ(ZX_OK, ret, "mapping object"); // fill with known pattern and test if (!fill_and_test(ptr, alloc_size)) { all_ok = false; } auto err = ka->FreeRegion((vaddr_t)ptr); EXPECT_EQ(ZX_OK, err, "unmapping object"); // map it again ret = ka->MapObjectInternal(vmo, "test", 0, alloc_size, &ptr, 0, VmAspace::VMM_FLAG_COMMIT, kArchRwFlags); ASSERT_EQ(ret, ZX_OK, "mapping object"); // test that the pattern is still valid bool result = test_region((uintptr_t)ptr, ptr, alloc_size); EXPECT_TRUE(result, "testing region for corruption"); err = ka->FreeRegion((vaddr_t)ptr); EXPECT_EQ(ZX_OK, err, "unmapping object"); END_TEST; } // Creates a vm object, maps it, fills it with data, maps it a second time and // third time somwehere else. static bool vmo_double_remap_test() { BEGIN_TEST; static const size_t alloc_size = PAGE_SIZE * 16; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, alloc_size, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); auto ka = VmAspace::kernel_aspace(); void* ptr; auto ret = ka->MapObjectInternal(vmo, "test0", 0, alloc_size, &ptr, 0, 0, kArchRwFlags); ASSERT_EQ(ZX_OK, ret, "mapping object"); // fill with known pattern and test if (!fill_and_test(ptr, alloc_size)) { all_ok = false; } // map it again void* ptr2; ret = ka->MapObjectInternal(vmo, "test1", 0, alloc_size, &ptr2, 0, 0, kArchRwFlags); ASSERT_EQ(ret, ZX_OK, "mapping object second time"); EXPECT_NE(ptr, ptr2, "second mapping is different"); // test that the pattern is still valid bool result = test_region((uintptr_t)ptr, ptr2, alloc_size); EXPECT_TRUE(result, "testing region for corruption"); // map it a third time with an offset void* ptr3; static const size_t alloc_offset = PAGE_SIZE; ret = ka->MapObjectInternal(vmo, "test2", alloc_offset, alloc_size - alloc_offset, &ptr3, 0, 0, kArchRwFlags); ASSERT_EQ(ret, ZX_OK, "mapping object third time"); EXPECT_NE(ptr3, ptr2, "third mapping is different"); EXPECT_NE(ptr3, ptr, "third mapping is different"); // test that the pattern is still valid int mc = memcmp((uint8_t*)ptr + alloc_offset, ptr3, alloc_size - alloc_offset); EXPECT_EQ(0, mc, "testing region for corruption"); ret = ka->FreeRegion((vaddr_t)ptr3); EXPECT_EQ(ZX_OK, ret, "unmapping object third time"); ret = ka->FreeRegion((vaddr_t)ptr2); EXPECT_EQ(ZX_OK, ret, "unmapping object second time"); ret = ka->FreeRegion((vaddr_t)ptr); EXPECT_EQ(ZX_OK, ret, "unmapping object"); END_TEST; } static bool vmo_read_write_smoke_test() { BEGIN_TEST; static const size_t alloc_size = PAGE_SIZE * 16; // create object fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0, alloc_size, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); // create test buffer fbl::AllocChecker ac; fbl::Vector<uint8_t> a; a.reserve(alloc_size, &ac); ASSERT_TRUE(ac.check()); fill_region(99, a.data(), alloc_size); // write to it, make sure it seems to work with valid args zx_status_t err = vmo->Write(a.data(), 0, 0); EXPECT_EQ(ZX_OK, err, "writing to object"); err = vmo->Write(a.data(), 0, 37); EXPECT_EQ(ZX_OK, err, "writing to object"); err = vmo->Write(a.data(), 99, 37); EXPECT_EQ(ZX_OK, err, "writing to object"); // can't write past end err = vmo->Write(a.data(), 0, alloc_size + 47); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, err, "writing to object"); // can't write past end err = vmo->Write(a.data(), 31, alloc_size + 47); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, err, "writing to object"); // should return an error because out of range err = vmo->Write(a.data(), alloc_size + 99, 42); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, err, "writing to object"); // map the object auto ka = VmAspace::kernel_aspace(); uint8_t* ptr; err = ka->MapObjectInternal(vmo, "test", 0, alloc_size, (void**)&ptr, 0, 0, kArchRwFlags); ASSERT_EQ(ZX_OK, err, "mapping object"); // write to it at odd offsets err = vmo->Write(a.data(), 31, 4197); EXPECT_EQ(ZX_OK, err, "writing to object"); int cmpres = memcmp(ptr + 31, a.data(), 4197); EXPECT_EQ(0, cmpres, "reading from object"); // write to it, filling the object completely err = vmo->Write(a.data(), 0, alloc_size); EXPECT_EQ(ZX_OK, err, "writing to object"); // test that the data was actually written to it bool result = test_region(99, ptr, alloc_size); EXPECT_TRUE(result, "writing to object"); // unmap it ka->FreeRegion((vaddr_t)ptr); // test that we can read from it fbl::Vector<uint8_t> b; b.reserve(alloc_size, &ac); ASSERT_TRUE(ac.check(), "can't allocate buffer"); err = vmo->Read(b.data(), 0, alloc_size); EXPECT_EQ(ZX_OK, err, "reading from object"); // validate the buffer is valid cmpres = memcmp(b.data(), a.data(), alloc_size); EXPECT_EQ(0, cmpres, "reading from object"); // read from it at an offset err = vmo->Read(b.data(), 31, 4197); EXPECT_EQ(ZX_OK, err, "reading from object"); cmpres = memcmp(b.data(), a.data() + 31, 4197); EXPECT_EQ(0, cmpres, "reading from object"); END_TEST; } static bool vmo_cache_test() { BEGIN_TEST; paddr_t pa; vm_page_t* vm_page; zx_status_t status = pmm_alloc_page(0, &vm_page, &pa); auto ka = VmAspace::kernel_aspace(); uint32_t cache_policy = ARCH_MMU_FLAG_UNCACHED_DEVICE; uint32_t cache_policy_get; void* ptr; ASSERT_TRUE(vm_page); // Test that the flags set/get properly { fbl::RefPtr<VmObject> vmo; status = VmObjectPhysical::Create(pa, PAGE_SIZE, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); cache_policy_get = vmo->GetMappingCachePolicy(); EXPECT_NE(cache_policy, cache_policy_get, "check initial cache policy"); EXPECT_EQ(ZX_OK, vmo->SetMappingCachePolicy(cache_policy), "try set"); cache_policy_get = vmo->GetMappingCachePolicy(); EXPECT_EQ(cache_policy, cache_policy_get, "compare flags"); } // Test valid flags for (uint32_t i = 0; i <= ARCH_MMU_FLAG_CACHE_MASK; i++) { fbl::RefPtr<VmObject> vmo; status = VmObjectPhysical::Create(pa, PAGE_SIZE, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); EXPECT_EQ(ZX_OK, vmo->SetMappingCachePolicy(cache_policy), "try setting valid flags"); } // Test invalid flags for (uint32_t i = ARCH_MMU_FLAG_CACHE_MASK + 1; i < 32; i++) { fbl::RefPtr<VmObject> vmo; status = VmObjectPhysical::Create(pa, PAGE_SIZE, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, vmo->SetMappingCachePolicy(i), "try set with invalid flags"); } // Test valid flags with invalid flags { fbl::RefPtr<VmObject> vmo; status = VmObjectPhysical::Create(pa, PAGE_SIZE, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, vmo->SetMappingCachePolicy(cache_policy | 0x5), "bad 0x5"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, vmo->SetMappingCachePolicy(cache_policy | 0xA), "bad 0xA"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, vmo->SetMappingCachePolicy(cache_policy | 0x55), "bad 0x55"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, vmo->SetMappingCachePolicy(cache_policy | 0xAA), "bad 0xAA"); } // Test that changing policy while mapped is blocked { fbl::RefPtr<VmObject> vmo; status = VmObjectPhysical::Create(pa, PAGE_SIZE, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); ASSERT_EQ(ZX_OK, ka->MapObjectInternal(vmo, "test", 0, PAGE_SIZE, (void**)&ptr, 0, 0, kArchRwFlags), "map vmo"); EXPECT_EQ(ZX_ERR_BAD_STATE, vmo->SetMappingCachePolicy(cache_policy), "set flags while mapped"); EXPECT_EQ(ZX_OK, ka->FreeRegion((vaddr_t)ptr), "unmap vmo"); EXPECT_EQ(ZX_OK, vmo->SetMappingCachePolicy(cache_policy), "set flags after unmapping"); ASSERT_EQ(ZX_OK, ka->MapObjectInternal(vmo, "test", 0, PAGE_SIZE, (void**)&ptr, 0, 0, kArchRwFlags), "map vmo again"); EXPECT_EQ(ZX_OK, ka->FreeRegion((vaddr_t)ptr), "unmap vmo"); } pmm_free_page(vm_page); END_TEST; } static bool vmo_lookup_test() { BEGIN_TEST; AutoVmScannerDisable scanner_disable; static const size_t alloc_size = PAGE_SIZE * 16; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, alloc_size, &vmo); ASSERT_EQ(status, ZX_OK, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); size_t pages_seen = 0; auto lookup_fn = [](void* context, size_t offset, size_t index, paddr_t pa) { size_t* pages_seen = static_cast<size_t*>(context); (*pages_seen)++; return ZX_OK; }; status = vmo->Lookup(0, alloc_size, lookup_fn, &pages_seen); EXPECT_EQ(ZX_ERR_NO_MEMORY, status, "lookup on uncommitted pages\n"); EXPECT_EQ(0u, pages_seen, "lookup on uncommitted pages\n"); pages_seen = 0; status = vmo->CommitRange(PAGE_SIZE, PAGE_SIZE); EXPECT_EQ(ZX_OK, status, "committing vm object\n"); EXPECT_EQ(static_cast<size_t>(1), vmo->AttributedPages(), "committing vm object\n"); // Should fail, since first page isn't mapped status = vmo->Lookup(0, alloc_size, lookup_fn, &pages_seen); EXPECT_EQ(ZX_ERR_NO_MEMORY, status, "lookup on partially committed pages\n"); EXPECT_EQ(0u, pages_seen, "lookup on partially committed pages\n"); pages_seen = 0; // Should fail, but see the mapped page status = vmo->Lookup(PAGE_SIZE, alloc_size - PAGE_SIZE, lookup_fn, &pages_seen); EXPECT_EQ(ZX_ERR_NO_MEMORY, status, "lookup on partially committed pages\n"); EXPECT_EQ(1u, pages_seen, "lookup on partially committed pages\n"); pages_seen = 0; // Should succeed status = vmo->Lookup(PAGE_SIZE, PAGE_SIZE, lookup_fn, &pages_seen); EXPECT_EQ(ZX_OK, status, "lookup on partially committed pages\n"); EXPECT_EQ(1u, pages_seen, "lookup on partially committed pages\n"); pages_seen = 0; // Commit the rest status = vmo->CommitRange(0, alloc_size); EXPECT_EQ(ZX_OK, status, "committing vm object\n"); EXPECT_EQ(alloc_size, PAGE_SIZE * vmo->AttributedPages(), "committing vm object\n"); status = vmo->Lookup(0, alloc_size, lookup_fn, &pages_seen); EXPECT_EQ(ZX_OK, status, "lookup on partially committed pages\n"); EXPECT_EQ(alloc_size / PAGE_SIZE, pages_seen, "lookup on partially committed pages\n"); END_TEST; } static bool vmo_lookup_clone_test() { BEGIN_TEST; AutoVmScannerDisable scanner_disable; static const size_t page_count = 4; static const size_t alloc_size = PAGE_SIZE * page_count; fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0, alloc_size, &vmo); ASSERT_EQ(ZX_OK, status, "vmobject creation\n"); ASSERT_TRUE(vmo, "vmobject creation\n"); vmo->set_user_id(ZX_KOID_KERNEL); // Commit the whole original VMO and the first and last page of the clone. status = vmo->CommitRange(0, alloc_size); ASSERT_EQ(ZX_OK, status, "vmobject creation\n"); fbl::RefPtr<VmObject> clone; status = vmo->CreateClone(Resizability::NonResizable, CloneType::Snapshot, 0, alloc_size, false, &clone); ASSERT_EQ(ZX_OK, status, "vmobject creation\n"); ASSERT_TRUE(clone, "vmobject creation\n"); clone->set_user_id(ZX_KOID_KERNEL); status = clone->CommitRange(0, PAGE_SIZE); ASSERT_EQ(ZX_OK, status, "vmobject creation\n"); status = clone->CommitRange(alloc_size - PAGE_SIZE, PAGE_SIZE); ASSERT_EQ(ZX_OK, status, "vmobject creation\n"); // Lookup the paddrs for both VMOs. paddr_t vmo_lookup[page_count] = {}; paddr_t clone_lookup[page_count] = {}; auto lookup_func = [](void* ctx, size_t offset, size_t index, paddr_t pa) { static_cast<paddr_t*>(ctx)[index] = pa; return ZX_OK; }; status = vmo->Lookup(0, alloc_size, lookup_func, &vmo_lookup); EXPECT_EQ(ZX_OK, status, "vmo lookup\n"); status = clone->Lookup(0, alloc_size, lookup_func, &clone_lookup); EXPECT_EQ(ZX_OK, status, "vmo lookup\n"); // Check that lookup returns a valid paddr for each index and that // they match/don't match when appropriate. for (unsigned i = 0; i < page_count; i++) { EXPECT_NE(0ul, vmo_lookup[i], "Bad paddr\n"); EXPECT_NE(0ul, clone_lookup[i], "Bad paddr\n"); if (i == 0 || i == page_count - 1) { EXPECT_NE(vmo_lookup[i], clone_lookup[i], "paddr mismatch"); } else { EXPECT_EQ(vmo_lookup[i], clone_lookup[i], "paddr mismatch"); } } END_TEST; } static bool vmo_clone_removes_write_test() { BEGIN_TEST; // Create and map a VMO. fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(PMM_ALLOC_FLAG_ANY, 0u, PAGE_SIZE, &vmo); EXPECT_EQ(ZX_OK, status, "vmo create"); auto ka = VmAspace::kernel_aspace(); void* ptr; status = ka->MapObjectInternal(vmo, "test", 0, PAGE_SIZE, &ptr, 0, VmAspace::VMM_FLAG_COMMIT, kArchRwFlags); EXPECT_EQ(ZX_OK, status, "map vmo"); // Query the aspace and validate there is a writable mapping. paddr_t paddr_writable; uint mmu_flags; status = ka->arch_aspace().Query(reinterpret_cast<vaddr_t>(ptr), &paddr_writable, &mmu_flags); EXPECT_EQ(ZX_OK, status, "query aspace"); EXPECT_TRUE(mmu_flags & ARCH_MMU_FLAG_PERM_WRITE, "mapping is writable check"); // Clone the VMO, which causes the parent to have to downgrade any mappings to read-only so that // copy-on-write can take place. Need to set a fake user id so that the COW creation code is // happy. vmo->set_user_id(42); fbl::RefPtr<VmObject> clone; status = vmo->CreateClone(Resizability::NonResizable, CloneType::Snapshot, 0, PAGE_SIZE, true, &clone); EXPECT_EQ(ZX_OK, status, "create clone"); // Aspace should now have a read only mapping with the same underlying page. paddr_t paddr_readable; status = ka->arch_aspace().Query(reinterpret_cast<vaddr_t>(ptr), &paddr_readable, &mmu_flags); EXPECT_EQ(ZX_OK, status, "query aspace"); EXPECT_FALSE(mmu_flags & ARCH_MMU_FLAG_PERM_WRITE, "mapping is read only check"); EXPECT_EQ(paddr_writable, paddr_readable, "mapping has same page"); // Cleanup. status = ka->FreeRegion(reinterpret_cast<vaddr_t>(ptr)); EXPECT_EQ(ZX_OK, status, "unmapping object"); END_TEST; } static bool vmo_zero_scan_test() { BEGIN_TEST; AutoVmScannerDisable scanner_disable; auto mem = testing::UserMemory::Create(PAGE_SIZE); ASSERT_NONNULL(mem); const auto& user_aspace = mem->aspace(); ASSERT_NONNULL(user_aspace); ASSERT_TRUE(user_aspace->is_user()); // Initially uncommitted, which should not count as having zero pages. EXPECT_EQ(0u, mem->vmo()->ScanForZeroPages(false)); // Validate that this mapping reads as zeros EXPECT_EQ(ZX_OK, user_aspace->SoftFault(mem->base(), 0u)); EXPECT_EQ(0, mem->get<int32_t>()); // Reading from the page should not have committed anything, zero or otherwise. EXPECT_EQ(0u, mem->vmo()->ScanForZeroPages(false)); // IF we write to the page, this should make it committed. EXPECT_EQ(ZX_OK, user_aspace->SoftFault(mem->base(), VMM_PF_FLAG_WRITE)); mem->put<int32_t>(0); EXPECT_EQ(1u, mem->vmo()->ScanForZeroPages(false)); // Check that changing the contents effects the zero page count. EXPECT_EQ(ZX_OK, user_aspace->SoftFault(mem->base(), VMM_PF_FLAG_WRITE)); mem->put<int32_t>(42); EXPECT_EQ(0u, mem->vmo()->ScanForZeroPages(false)); EXPECT_EQ(ZX_OK, user_aspace->SoftFault(mem->base(), VMM_PF_FLAG_WRITE)); mem->put<int32_t>(0); EXPECT_EQ(1u, mem->vmo()->ScanForZeroPages(false)); // Scanning should drop permissions in the hardware page table from write to read-only. paddr_t paddr_readable; uint mmu_flags; EXPECT_EQ(ZX_OK, user_aspace->SoftFault(mem->base(), VMM_PF_FLAG_WRITE)); mem->put<int32_t>(0); zx_status_t status = user_aspace->arch_aspace().Query(mem->base(), &paddr_readable, &mmu_flags); EXPECT_EQ(ZX_OK, status); EXPECT_TRUE(mmu_flags & ARCH_MMU_FLAG_PERM_WRITE); mem->vmo()->ScanForZeroPages(false); status = user_aspace->arch_aspace().Query(mem->base(), &paddr_readable, &mmu_flags); EXPECT_EQ(ZX_OK, status); EXPECT_FALSE(mmu_flags & ARCH_MMU_FLAG_PERM_WRITE); // Pinning the page should prevent it from being counted. EXPECT_EQ(1u, mem->vmo()->ScanForZeroPages(false)); EXPECT_EQ(ZX_OK, mem->vmo()->CommitRangePinned(0, PAGE_SIZE)); EXPECT_EQ(0u, mem->vmo()->ScanForZeroPages(false)); mem->vmo()->Unpin(0, PAGE_SIZE); EXPECT_EQ(1u, mem->vmo()->ScanForZeroPages(false)); // Creating a kernel mapping should prevent any counting from occurring. VmAspace* kernel_aspace = VmAspace::kernel_aspace(); void* ptr; status = kernel_aspace->MapObjectInternal(mem->vmo(), "test", 0, PAGE_SIZE, &ptr, 0, VmAspace::VMM_FLAG_COMMIT, kArchRwFlags); EXPECT_EQ(ZX_OK, status); EXPECT_EQ(0u, mem->vmo()->ScanForZeroPages(false)); kernel_aspace->FreeRegion(reinterpret_cast<vaddr_t>(ptr)); EXPECT_EQ(1u, mem->vmo()->ScanForZeroPages(false)); END_TEST; } static bool vmo_move_pages_on_access_test() { BEGIN_TEST; AutoVmScannerDisable scanner_disable; fbl::RefPtr<VmObject> vmo; vm_page_t* page; zx_status_t status = make_committed_pager_vmo(&page, &vmo); ASSERT_EQ(ZX_OK, status); // Our page should now be in a pager backed page queue. EXPECT_TRUE(pmm_page_queues()->DebugPageIsPagerBacked(page)); PageRequest request; // If we lookup the page then it should be moved to specifically the first page queue. status = vmo->GetPage(0, VMM_PF_FLAG_SW_FAULT, nullptr, nullptr, nullptr, nullptr); EXPECT_EQ(ZX_OK, status); size_t queue; EXPECT_TRUE(pmm_page_queues()->DebugPageIsPagerBacked(page, &queue)); EXPECT_EQ(0u, queue); // Rotate the queues and check the page moves. pmm_page_queues()->RotatePagerBackedQueues(); EXPECT_TRUE(pmm_page_queues()->DebugPageIsPagerBacked(page, &queue)); EXPECT_EQ(1u, queue); // Touching the page should move it back to the first queue. status = vmo->GetPage(0, VMM_PF_FLAG_SW_FAULT, nullptr, nullptr, nullptr, nullptr); EXPECT_EQ(ZX_OK, status); EXPECT_TRUE(pmm_page_queues()->DebugPageIsPagerBacked(page, &queue)); EXPECT_EQ(0u, queue); // Touching pages in a child should also move the page to the front of the queues. fbl::RefPtr<VmObject> child; status = vmo->CreateClone(Resizability::NonResizable, CloneType::PrivatePagerCopy, 0, PAGE_SIZE, true, &child); ASSERT_EQ(ZX_OK, status); status = child->GetPage(0, VMM_PF_FLAG_SW_FAULT, nullptr, nullptr, nullptr, nullptr); EXPECT_EQ(ZX_OK, status); EXPECT_TRUE(pmm_page_queues()->DebugPageIsPagerBacked(page, &queue)); EXPECT_EQ(0u, queue); pmm_page_queues()->RotatePagerBackedQueues(); EXPECT_TRUE(pmm_page_queues()->DebugPageIsPagerBacked(page, &queue)); EXPECT_EQ(1u, queue); status = child->GetPage(0, VMM_PF_FLAG_SW_FAULT, nullptr, nullptr, nullptr, nullptr); EXPECT_EQ(ZX_OK, status); EXPECT_TRUE(pmm_page_queues()->DebugPageIsPagerBacked(page, &queue)); EXPECT_EQ(0u, queue); END_TEST; } static bool vmo_eviction_test() { BEGIN_TEST; // Disable the page scanner as this test would be flaky if our pages get evicted by someone else. scanner_push_disable_count(); auto pop_count = fbl::MakeAutoCall([] { scanner_pop_disable_count(); }); // Make two pager backed vmos fbl::RefPtr<VmObject> vmo; fbl::RefPtr<VmObject> vmo2; vm_page_t* page; vm_page_t* page2; zx_status_t status = make_committed_pager_vmo(&page, &vmo); ASSERT_EQ(ZX_OK, status); status = make_committed_pager_vmo(&page2, &vmo2); ASSERT_EQ(ZX_OK, status); // Shouldn't be able to evict pages from the wrong VMO. EXPECT_FALSE(vmo->EvictPage(page2, 0)); EXPECT_FALSE(vmo2->EvictPage(page, 0)); // Eviction should actually drop the number of committed pages. EXPECT_EQ(1u, vmo2->AttributedPages()); EXPECT_TRUE(vmo2->EvictPage(page2, 0)); EXPECT_EQ(0u, vmo2->AttributedPages()); pmm_free_page(page2); EXPECT_GT(vmo2->EvictedPagedCount(), 0u); // Pinned pages should not be evictable. status = vmo->CommitRangePinned(0, PAGE_SIZE); EXPECT_EQ(ZX_OK, status); EXPECT_FALSE(vmo->EvictPage(page, 0)); vmo->Unpin(0, PAGE_SIZE); END_TEST; } // This test exists to provide a location for VmObjectPaged::DebugValidatePageSplits to be // regularly called so that it doesn't bitrot. Additionally it *might* detect VMO object corruption, // but it's primary goal is to test the implementation of DebugValidatePageSplits static bool vmo_validate_page_splits_test() { BEGIN_TEST; zx_status_t status = VmObject::ForEach([](const VmObject& vmo) -> zx_status_t { if (vmo.is_paged()) { const VmObjectPaged& paged = static_cast<const VmObjectPaged&>(vmo); if (!paged.DebugValidatePageSplits()) { return ZX_ERR_INTERNAL; } } return ZX_OK; }); // Although DebugValidatePageSplits says to panic as soon as possible if it returns false, this // test errs on side of assuming that the validation is broken, and not the hierarchy, and so does // not panic. Either way the test still fails, this is just more graceful. EXPECT_EQ(ZX_OK, status); END_TEST; } // TODO(ZX-1431): The ARM code's error codes are always ZX_ERR_INTERNAL, so // special case that. #if ARCH_ARM64 #define MMU_EXPECT_EQ(exp, act, msg) EXPECT_EQ(ZX_ERR_INTERNAL, act, msg) #else #define MMU_EXPECT_EQ(exp, act, msg) EXPECT_EQ(exp, act, msg) #endif static bool arch_noncontiguous_map() { BEGIN_TEST; // Get some phys pages to test on paddr_t phys[3]; struct list_node phys_list = LIST_INITIAL_VALUE(phys_list); zx_status_t status = pmm_alloc_pages(ktl::size(phys), 0, &phys_list); ASSERT_EQ(ZX_OK, status, "non contig map alloc"); { size_t i = 0; vm_page_t* p; list_for_every_entry (&phys_list, p, vm_page_t, queue_node) { phys[i] = p->paddr(); ++i; } } { ArchVmAspace aspace; status = aspace.Init(USER_ASPACE_BASE, USER_ASPACE_SIZE, 0); ASSERT_EQ(ZX_OK, status, "failed to init aspace\n"); // Attempt to map a set of vm_page_t size_t mapped; vaddr_t base = USER_ASPACE_BASE + 10 * PAGE_SIZE; status = aspace.Map(base, phys, ktl::size(phys), ARCH_MMU_FLAG_PERM_READ, &mapped); ASSERT_EQ(ZX_OK, status, "failed first map\n"); EXPECT_EQ(ktl::size(phys), mapped, "weird first map\n"); for (size_t i = 0; i < ktl::size(phys); ++i) { paddr_t paddr; uint mmu_flags; status = aspace.Query(base + i * PAGE_SIZE, &paddr, &mmu_flags); EXPECT_EQ(ZX_OK, status, "bad first map\n"); EXPECT_EQ(phys[i], paddr, "bad first map\n"); EXPECT_EQ(ARCH_MMU_FLAG_PERM_READ, mmu_flags, "bad first map\n"); } // Attempt to map again, should fail status = aspace.Map(base, phys, ktl::size(phys), ARCH_MMU_FLAG_PERM_READ, &mapped); MMU_EXPECT_EQ(ZX_ERR_ALREADY_EXISTS, status, "double map\n"); // Attempt to map partially ovelapping, should fail status = aspace.Map(base + 2 * PAGE_SIZE, phys, ktl::size(phys), ARCH_MMU_FLAG_PERM_READ, &mapped); MMU_EXPECT_EQ(ZX_ERR_ALREADY_EXISTS, status, "double map\n"); status = aspace.Map(base - 2 * PAGE_SIZE, phys, ktl::size(phys), ARCH_MMU_FLAG_PERM_READ, &mapped); MMU_EXPECT_EQ(ZX_ERR_ALREADY_EXISTS, status, "double map\n"); // No entries should have been created by the partial failures status = aspace.Query(base - 2 * PAGE_SIZE, nullptr, nullptr); EXPECT_EQ(ZX_ERR_NOT_FOUND, status, "bad first map\n"); status = aspace.Query(base - PAGE_SIZE, nullptr, nullptr); EXPECT_EQ(ZX_ERR_NOT_FOUND, status, "bad first map\n"); status = aspace.Query(base + 3 * PAGE_SIZE, nullptr, nullptr); EXPECT_EQ(ZX_ERR_NOT_FOUND, status, "bad first map\n"); status = aspace.Query(base + 4 * PAGE_SIZE, nullptr, nullptr); EXPECT_EQ(ZX_ERR_NOT_FOUND, status, "bad first map\n"); status = aspace.Unmap(base, ktl::size(phys), &mapped); ASSERT_EQ(ZX_OK, status, "failed unmap\n"); EXPECT_EQ(ktl::size(phys), mapped, "weird unmap\n"); status = aspace.Destroy(); EXPECT_EQ(ZX_OK, status, "failed to destroy aspace\n"); } pmm_free(&phys_list); END_TEST; } // Test to make sure all the vm kernel regions (code, rodata, data, bss, etc.) is correctly mapped // in vm and has the correct arch_mmu_flags. This test also check that all gaps are contained within // a VMAR. static bool vm_kernel_region_test() { BEGIN_TEST; fbl::RefPtr<VmAddressRegionOrMapping> kernel_vmar = VmAspace::kernel_aspace()->RootVmar()->FindRegion(reinterpret_cast<vaddr_t>(__code_start)); EXPECT_NE(kernel_vmar.get(), nullptr); EXPECT_FALSE(kernel_vmar->is_mapping()); for (vaddr_t base = reinterpret_cast<vaddr_t>(__code_start); base < reinterpret_cast<vaddr_t>(_end); base += PAGE_SIZE) { bool within_region = false; for (const auto& kernel_region : kernel_regions) { // This would not overflow because the region base and size are hard-coded. if (base >= kernel_region.base && base + PAGE_SIZE <= kernel_region.base + kernel_region.size) { // If this page exists within a kernel region, then it should be within a VmMapping with // the correct arch MMU flags. within_region = true; fbl::RefPtr<VmAddressRegionOrMapping> region = kernel_vmar->as_vm_address_region()->FindRegion(base); // Every page from __code_start to _end should either be a VmMapping or a VMAR. EXPECT_NE(region.get(), nullptr); EXPECT_TRUE(region->is_mapping()); EXPECT_EQ(kernel_region.arch_mmu_flags, region->as_vm_mapping()->arch_mmu_flags()); break; } } if (!within_region) { auto region = VmAspace::kernel_aspace()->RootVmar()->FindRegion(base); EXPECT_EQ(region.get(), kernel_vmar.get()); } } END_TEST; } namespace { bool AddPage(VmPageList* pl, vm_page_t* page, uint64_t offset) { if (!pl) { return false; } VmPageOrMarker* slot = pl->LookupOrAllocate(offset); if (!slot) { return false; } if (!slot->IsEmpty()) { return false; } *slot = VmPageOrMarker::Page(page); return true; } bool AddMarker(VmPageList* pl, uint64_t offset) { if (!pl) { return false; } VmPageOrMarker* slot = pl->LookupOrAllocate(offset); if (!slot) { return false; } if (!slot->IsEmpty()) { return false; } *slot = VmPageOrMarker::Marker(); return true; } } // namespace // Basic test that checks adding/removing a page static bool vmpl_add_remove_page_test() { BEGIN_TEST; VmPageList pl; vm_page_t test_page{}; EXPECT_TRUE(AddPage(&pl, &test_page, 0)); EXPECT_EQ(&test_page, pl.Lookup(0)->Page(), "unexpected page\n"); EXPECT_FALSE(pl.IsEmpty()); EXPECT_FALSE(pl.HasNoPages()); vm_page* remove_page = pl.RemovePage(0).ReleasePage(); EXPECT_EQ(&test_page, remove_page, "unexpected page\n"); EXPECT_TRUE(pl.RemovePage(0).IsEmpty(), "unexpected page\n"); EXPECT_TRUE(pl.IsEmpty()); EXPECT_TRUE(pl.HasNoPages()); END_TEST; } // Basic test of setting and getting markers. static bool vmpl_basic_marker_test() { BEGIN_TEST; VmPageList pl; EXPECT_TRUE(pl.IsEmpty()); EXPECT_TRUE(pl.HasNoPages()); EXPECT_TRUE(AddMarker(&pl, 0)); EXPECT_TRUE(pl.Lookup(0)->IsMarker()); EXPECT_FALSE(pl.IsEmpty()); EXPECT_TRUE(pl.HasNoPages()); END_TEST; } // Test for freeing a range of pages static bool vmpl_free_pages_test() { BEGIN_TEST; VmPageList pl; constexpr uint32_t kCount = 3 * VmPageListNode::kPageFanOut; vm_page_t test_pages[kCount] = {}; // Install alternating pages and markers. for (uint32_t i = 0; i < kCount; i++) { EXPECT_TRUE(AddPage(&pl, test_pages + i, i * 2 * PAGE_SIZE)); EXPECT_TRUE(AddMarker(&pl, (i * 2 + 1) * PAGE_SIZE)); } list_node_t list; list_initialize(&list); pl.RemovePages( [&list](VmPageOrMarker* page_or_marker, uint64_t off) { if (page_or_marker->IsPage()) { vm_page_t* p = page_or_marker->ReleasePage(); list_add_tail(&list, &p->queue_node); } *page_or_marker = VmPageOrMarker::Empty(); }, PAGE_SIZE * 2, (kCount - 1) * 2 * PAGE_SIZE); for (unsigned i = 1; i < kCount - 2; i++) { EXPECT_TRUE(list_in_list(&test_pages[i].queue_node), "Not in free list"); } for (uint32_t i = 0; i < kCount; i++) { VmPageOrMarker remove_page = pl.RemovePage(i * 2 * PAGE_SIZE); VmPageOrMarker remove_marker = pl.RemovePage((i * 2 + 1) * PAGE_SIZE); if (i == 0 || i == kCount - 1) { EXPECT_TRUE(remove_page.IsPage(), "missing page\n"); EXPECT_TRUE(remove_marker.IsMarker(), "missing marker\n"); EXPECT_EQ(test_pages + i, remove_page.ReleasePage(), "unexpected page\n"); } else { EXPECT_TRUE(remove_page.IsEmpty(), "extra page\n"); EXPECT_TRUE(remove_marker.IsEmpty(), "extra marker\n"); } } END_TEST; } // Tests freeing the last page in a list static bool vmpl_free_pages_last_page_test() { BEGIN_TEST; vm_page_t page{}; VmPageList pl; EXPECT_TRUE(AddPage(&pl, &page, 0)); EXPECT_EQ(&page, pl.Lookup(0)->Page(), "unexpected page\n"); list_node_t list; list_initialize(&list); pl.RemoveAllPages([&list](vm_page_t* p) { list_add_tail(&list, &p->queue_node); }); EXPECT_TRUE(pl.IsEmpty(), "not empty\n"); EXPECT_EQ(list_length(&list), 1u, "too many pages"); EXPECT_EQ(list_remove_head_type(&list, vm_page_t, queue_node), &page, "wrong page"); END_TEST; } static bool vmpl_near_last_offset_free() { BEGIN_TEST; vm_page_t page = {}; bool at_least_one = false; for (uint64_t addr = 0xfffffffffff00000; addr != 0; addr += PAGE_SIZE) { VmPageList pl; if (AddPage(&pl, &page, addr)) { at_least_one = true; EXPECT_EQ(&page, pl.Lookup(addr)->Page(), "unexpected page\n"); list_node_t list; list_initialize(&list); pl.RemoveAllPages([&list](vm_page_t* p) { list_add_tail(&list, &p->queue_node); }); EXPECT_EQ(list_length(&list), 1u, "too many pages"); EXPECT_EQ(list_remove_head_type(&list, vm_page_t, queue_node), &page, "wrong page"); EXPECT_TRUE(pl.IsEmpty(), "non-empty list\n"); } } EXPECT_TRUE(at_least_one, "starting address too large"); VmPageList pl2; EXPECT_NULL(pl2.LookupOrAllocate(0xfffffffffffe0000), "unexpected offset addable\n"); END_TEST; } // Tests taking a page from the start of a VmPageListNode static bool vmpl_take_single_page_even_test() { BEGIN_TEST; VmPageList pl; vm_page_t test_page{}; vm_page_t test_page2{}; EXPECT_TRUE(AddPage(&pl, &test_page, 0)); EXPECT_TRUE(AddPage(&pl, &test_page2, PAGE_SIZE)); VmPageSpliceList splice = pl.TakePages(0, PAGE_SIZE); EXPECT_EQ(&test_page, splice.Pop().ReleasePage(), "wrong page\n"); EXPECT_TRUE(splice.IsDone(), "extra page\n"); EXPECT_TRUE(pl.Lookup(0) == nullptr || pl.Lookup(0)->IsEmpty(), "duplicate page\n"); EXPECT_EQ(&test_page2, pl.RemovePage(PAGE_SIZE).ReleasePage(), "remove failure\n"); END_TEST; } // Tests taking a page from the middle of a VmPageListNode static bool vmpl_take_single_page_odd_test() { BEGIN_TEST; VmPageList pl; vm_page_t test_page{}; vm_page_t test_page2{}; EXPECT_TRUE(AddPage(&pl, &test_page, 0)); EXPECT_TRUE(AddPage(&pl, &test_page2, PAGE_SIZE)); VmPageSpliceList splice = pl.TakePages(PAGE_SIZE, PAGE_SIZE); EXPECT_EQ(&test_page2, splice.Pop().ReleasePage(), "wrong page\n"); EXPECT_TRUE(splice.IsDone(), "extra page\n"); EXPECT_TRUE(pl.Lookup(PAGE_SIZE) == nullptr || pl.Lookup(PAGE_SIZE)->IsEmpty(), "duplicate page\n"); EXPECT_EQ(&test_page, pl.RemovePage(0).ReleasePage(), "remove failure\n"); END_TEST; } // Tests taking all the pages from a range of VmPageListNodes static bool vmpl_take_all_pages_test() { BEGIN_TEST; VmPageList pl; constexpr uint32_t kCount = 3 * VmPageListNode::kPageFanOut; vm_page_t test_pages[kCount] = {}; for (uint32_t i = 0; i < kCount; i++) { EXPECT_TRUE(AddPage(&pl, test_pages + i, i * 2 * PAGE_SIZE)); EXPECT_TRUE(AddMarker(&pl, (i * 2 + 1) * PAGE_SIZE)); } VmPageSpliceList splice = pl.TakePages(0, kCount * 2 * PAGE_SIZE); EXPECT_TRUE(pl.IsEmpty(), "non-empty list\n"); for (uint32_t i = 0; i < kCount; i++) { EXPECT_EQ(test_pages + i, splice.Pop().ReleasePage(), "wrong page\n"); EXPECT_TRUE(splice.Pop().IsMarker(), "expected marker\n"); } EXPECT_TRUE(splice.IsDone(), "extra pages\n"); END_TEST; } // Tests taking the middle pages from a range of VmPageListNodes static bool vmpl_take_middle_pages_test() { BEGIN_TEST; VmPageList pl; constexpr uint32_t kCount = 3 * VmPageListNode::kPageFanOut; vm_page_t test_pages[kCount] = {}; for (uint32_t i = 0; i < kCount; i++) { EXPECT_TRUE(AddPage(&pl, test_pages + i, i * PAGE_SIZE)); } constexpr uint32_t kTakeOffset = VmPageListNode::kPageFanOut - 1; constexpr uint32_t kTakeCount = VmPageListNode::kPageFanOut + 2; VmPageSpliceList splice = pl.TakePages(kTakeOffset * PAGE_SIZE, kTakeCount * PAGE_SIZE); EXPECT_FALSE(pl.IsEmpty(), "non-empty list\n"); for (uint32_t i = 0; i < kCount; i++) { if (kTakeOffset <= i && i < kTakeOffset + kTakeCount) { EXPECT_EQ(test_pages + i, splice.Pop().ReleasePage(), "wrong page\n"); } else { EXPECT_EQ(test_pages + i, pl.RemovePage(i * PAGE_SIZE).ReleasePage(), "remove failure\n"); } } EXPECT_TRUE(splice.IsDone(), "extra pages\n"); END_TEST; } // Tests that gaps are preserved in the list static bool vmpl_take_gap_test() { BEGIN_TEST; VmPageList pl; constexpr uint32_t kCount = VmPageListNode::kPageFanOut; constexpr uint32_t kGapSize = 2; vm_page_t test_pages[kCount] = {}; for (uint32_t i = 0; i < kCount; i++) { uint64_t offset = (i * (kGapSize + 1)) * PAGE_SIZE; EXPECT_TRUE(AddPage(&pl, test_pages + i, offset)); } constexpr uint32_t kListStart = PAGE_SIZE; constexpr uint32_t kListLen = (kCount * (kGapSize + 1) - 2) * PAGE_SIZE; VmPageSpliceList splice = pl.TakePages(kListStart, kListLen); EXPECT_EQ(test_pages, pl.RemovePage(0).ReleasePage(), "wrong page\n"); EXPECT_TRUE(pl.Lookup(kListLen) == nullptr || pl.Lookup(kListLen)->IsEmpty(), "wrong page\n"); for (uint64_t offset = kListStart; offset < kListStart + kListLen; offset += PAGE_SIZE) { auto page_idx = offset / PAGE_SIZE; if (page_idx % (kGapSize + 1) == 0) { EXPECT_EQ(test_pages + (page_idx / (kGapSize + 1)), splice.Pop().ReleasePage(), "wrong page\n"); } else { EXPECT_TRUE(splice.Pop().IsEmpty(), "wrong page\n"); } } EXPECT_TRUE(splice.IsDone(), "extra pages\n"); END_TEST; } // Tests that an empty page splice list can be created. static bool vmpl_take_empty_test() { BEGIN_TEST; VmPageList pl; VmPageSpliceList splice = pl.TakePages(PAGE_SIZE, PAGE_SIZE); EXPECT_FALSE(splice.IsDone()); EXPECT_TRUE(splice.Pop().IsEmpty()); EXPECT_TRUE(splice.IsDone()); END_TEST; } // Tests that cleaning up a splice list doesn't blow up static bool vmpl_take_cleanup_test() { BEGIN_TEST; paddr_t pa; vm_page_t* page; zx_status_t status = pmm_alloc_page(0, &page, &pa); ASSERT_EQ(ZX_OK, status, "pmm_alloc single page"); ASSERT_NONNULL(page, "pmm_alloc single page"); ASSERT_NE(0u, pa, "pmm_alloc single page"); page->set_state(VM_PAGE_STATE_OBJECT); page->object.pin_count = 0; VmPageList pl; EXPECT_TRUE(AddPage(&pl, page, 0)); VmPageSpliceList splice = pl.TakePages(0, PAGE_SIZE); EXPECT_TRUE(!splice.IsDone(), "missing page\n"); END_TEST; } // Helper function which takes an array of pages, builds a VmPageList, and then verifies that // ForEveryPageInRange is correct when ZX_ERR_NEXT is returned for the |stop_idx|th entry. static bool vmpl_page_gap_iter_test_body(vm_page_t** pages, uint32_t count, uint32_t stop_idx) { BEGIN_TEST; VmPageList list; for (uint32_t i = 0; i < count; i++) { if (pages[i]) { EXPECT_TRUE(AddPage(&list, pages[i], i * PAGE_SIZE)); } } uint32_t idx = 0; zx_status_t s = list.ForEveryPageAndGapInRange( [pages, stop_idx, &idx](const VmPageOrMarker& p, auto off) { if (off != idx * PAGE_SIZE || !p.IsPage() || pages[idx] != p.Page()) { return ZX_ERR_INTERNAL; } if (idx == stop_idx) { return ZX_ERR_STOP; } idx++; return ZX_ERR_NEXT; }, [pages, stop_idx, &idx](uint64_t gap_start, uint64_t gap_end) { for (auto o = gap_start; o < gap_end; o += PAGE_SIZE) { if (o != idx * PAGE_SIZE || pages[idx] != nullptr) { return ZX_ERR_INTERNAL; } if (idx == stop_idx) { return ZX_ERR_STOP; } idx++; } return ZX_ERR_NEXT; }, 0, count * PAGE_SIZE); ASSERT_EQ(ZX_OK, s); ASSERT_EQ(stop_idx, idx); list_node_t free_list; list_initialize(&free_list); list.RemoveAllPages([&free_list](vm_page_t* p) { list_add_tail(&free_list, &p->queue_node); }); ASSERT_TRUE(list.IsEmpty()); END_TEST; } // Test ForEveryPageInRange against all lists of size 4 static bool vmpl_page_gap_iter_test() { static constexpr uint32_t kCount = 4; static_assert((kCount & (kCount - 1)) == 0); vm_page_t pages[kCount] = {}; vm_page_t* list[kCount] = {}; for (unsigned i = 0; i < kCount; i++) { for (unsigned j = 0; j < (1 << kCount); j++) { for (unsigned k = 0; k < kCount; k++) { if (j & (1 << k)) { // Ensure pages are in an initialized state every iteration. pages[k] = (vm_page_t){}; list[k] = pages + k; } else { list[k] = nullptr; } } if (!vmpl_page_gap_iter_test_body(list, kCount, i)) { return false; } } } return true; } static bool vmpl_merge_offset_test_helper(uint64_t list1_offset, uint64_t list2_offset) { BEGIN_TEST; VmPageList list; list.InitializeSkew(0, list1_offset); vm_page_t test_pages[6] = {}; uint64_t offsets[6] = { VmPageListNode::kPageFanOut * PAGE_SIZE + list2_offset - PAGE_SIZE, VmPageListNode::kPageFanOut * PAGE_SIZE + list2_offset, 3 * VmPageListNode::kPageFanOut * PAGE_SIZE + list2_offset - PAGE_SIZE, 3 * VmPageListNode::kPageFanOut * PAGE_SIZE + list2_offset, 5 * VmPageListNode::kPageFanOut * PAGE_SIZE + list2_offset - PAGE_SIZE, 5 * VmPageListNode::kPageFanOut * PAGE_SIZE + list2_offset, }; for (unsigned i = 0; i < 6; i++) { EXPECT_TRUE(AddPage(&list, test_pages + i, offsets[i])); } VmPageList list2; list2.InitializeSkew(list1_offset, list2_offset); list_node_t free_list; list_initialize(&free_list); list2.MergeFrom( list, offsets[1], offsets[5], [&](vm_page* page, uint64_t offset) { DEBUG_ASSERT(page == test_pages || page == test_pages + 5); DEBUG_ASSERT(offset == offsets[0] || offset == offsets[5]); list_add_tail(&free_list, &page->queue_node); }, [&](VmPageOrMarker* page_or_marker, uint64_t offset) { DEBUG_ASSERT(page_or_marker->IsPage()); vm_page_t* page = page_or_marker->Page(); DEBUG_ASSERT(page == test_pages + 1 || page == test_pages + 2 || page == test_pages + 3 || page == test_pages + 4); DEBUG_ASSERT(offset == offsets[1] || offset == offsets[2] || offset == offsets[3] || offsets[4]); }); EXPECT_EQ(list_length(&free_list), 2ul); EXPECT_EQ(list2.RemovePage(0).ReleasePage(), test_pages + 1); EXPECT_EQ(list2.RemovePage(2 * VmPageListNode::kPageFanOut * PAGE_SIZE - PAGE_SIZE).ReleasePage(), test_pages + 2); EXPECT_EQ(list2.RemovePage(2 * VmPageListNode::kPageFanOut * PAGE_SIZE).ReleasePage(), test_pages + 3); EXPECT_EQ(list2.RemovePage(4 * VmPageListNode::kPageFanOut * PAGE_SIZE - PAGE_SIZE).ReleasePage(), test_pages + 4); EXPECT_TRUE(list2.HasNoPages()); END_TEST; } static bool vmpl_merge_offset_test() { for (unsigned i = 0; i < VmPageListNode::kPageFanOut; i++) { for (unsigned j = 0; j < VmPageListNode::kPageFanOut; j++) { if (!vmpl_merge_offset_test_helper(i * PAGE_SIZE, j * PAGE_SIZE)) { return false; } } } return true; } static bool vmpl_merge_overlap_test_helper(uint64_t list1_offset, uint64_t list2_offset) { BEGIN_TEST; VmPageList list; list.InitializeSkew(0, list1_offset); vm_page_t test_pages[4] = {}; EXPECT_TRUE(AddPage(&list, test_pages, list2_offset)); EXPECT_TRUE(AddPage(&list, test_pages + 1, list2_offset + 2 * PAGE_SIZE)); VmPageList list2; list2.InitializeSkew(list1_offset, list2_offset); EXPECT_TRUE(AddPage(&list2, test_pages + 2, 0)); EXPECT_TRUE(AddPage(&list2, test_pages + 3, PAGE_SIZE)); list_node_t free_list; list_initialize(&free_list); list2.MergeFrom( list, list2_offset, list2_offset + 4 * PAGE_SIZE, [&](vm_page* page, uint64_t offset) { DEBUG_ASSERT(page == test_pages); DEBUG_ASSERT(offset == list2_offset); list_add_tail(&free_list, &page->queue_node); }, [&](VmPageOrMarker* page_or_marker, uint64_t offset) { DEBUG_ASSERT(page_or_marker->IsPage()); vm_page_t* page = page_or_marker->Page(); DEBUG_ASSERT(page == test_pages + 1); DEBUG_ASSERT(offset == list2_offset + 2 * PAGE_SIZE); }); EXPECT_EQ(list_length(&free_list), 1ul); EXPECT_EQ(list2.RemovePage(0).ReleasePage(), test_pages + 2); EXPECT_EQ(list2.RemovePage(PAGE_SIZE).ReleasePage(), test_pages + 3); EXPECT_EQ(list2.RemovePage(2 * PAGE_SIZE).ReleasePage(), test_pages + 1); EXPECT_TRUE(list2.IsEmpty()); END_TEST; } static bool vmpl_merge_overlap_test() { for (unsigned i = 0; i < VmPageListNode::kPageFanOut; i++) { for (unsigned j = 0; j < VmPageListNode::kPageFanOut; j++) { if (!vmpl_merge_overlap_test_helper(i * PAGE_SIZE, j * PAGE_SIZE)) { return false; } } } return true; } static bool vmpl_for_every_page_test() { BEGIN_TEST; VmPageList list; list.InitializeSkew(0, PAGE_SIZE); vm_page_t test_pages[5] = {}; uint64_t offsets[ktl::size(test_pages)] = { 0, PAGE_SIZE, VmPageListNode::kPageFanOut * PAGE_SIZE - PAGE_SIZE, VmPageListNode::kPageFanOut * PAGE_SIZE, VmPageListNode::kPageFanOut * PAGE_SIZE + PAGE_SIZE, }; for (unsigned i = 0; i < ktl::size(test_pages); i++) { if (i % 2) { EXPECT_TRUE(AddPage(&list, test_pages + i, offsets[i])); } else { EXPECT_TRUE(AddMarker(&list, offsets[i])); } } uint32_t idx = 0; auto iter_fn = [&](const auto& p, uint64_t off) -> zx_status_t { EXPECT_EQ(off, offsets[idx]); if (idx % 2) { EXPECT_TRUE(p.IsPage()); EXPECT_EQ(p.Page(), test_pages + idx); } else { EXPECT_TRUE(p.IsMarker()); } idx++; return ZX_ERR_NEXT; }; list.ForEveryPage(iter_fn); ASSERT_EQ(idx, ktl::size(offsets)); idx = 1; list.ForEveryPageInRange(iter_fn, offsets[1], offsets[ktl::size(test_pages) - 1]); ASSERT_EQ(idx, ktl::size(offsets) - 1); list_node_t free_list; list_initialize(&free_list); list.RemoveAllPages([&free_list](vm_page_t* p) { list_add_tail(&free_list, &p->queue_node); }); END_TEST; } static bool vmpl_merge_onto_test() { BEGIN_TEST; VmPageList list1, list2; list1.InitializeSkew(0, 0); list2.InitializeSkew(0, 0); vm_page_t test_pages[4] = {}; EXPECT_TRUE(AddPage(&list1, test_pages + 0, 0)); EXPECT_TRUE( AddPage(&list1, test_pages + 1, VmPageListNode::kPageFanOut * PAGE_SIZE + 2 * PAGE_SIZE)); EXPECT_TRUE(AddPage(&list2, test_pages + 2, 0)); EXPECT_TRUE( AddPage(&list2, test_pages + 3, 2 * VmPageListNode::kPageFanOut * PAGE_SIZE + PAGE_SIZE)); list_node_t free_list; list_initialize(&free_list); list1.MergeOnto(list2, [&free_list](auto* p) { list_add_tail(&free_list, &p->queue_node); }); // (test_pages + 0) should have covered this page EXPECT_EQ(1ul, list_length(&free_list)); EXPECT_EQ(test_pages + 2, list_remove_head_type(&free_list, vm_page, queue_node)); EXPECT_EQ(test_pages + 0, list2.Lookup(0)->Page()); EXPECT_EQ(test_pages + 1, list2.Lookup(VmPageListNode::kPageFanOut * PAGE_SIZE + 2 * PAGE_SIZE)->Page()); EXPECT_EQ(test_pages + 3, list2.Lookup(2 * VmPageListNode::kPageFanOut * PAGE_SIZE + PAGE_SIZE)->Page()); list2.RemoveAllPages([&free_list](vm_page_t* p) { list_add_tail(&free_list, &p->queue_node); }); EXPECT_EQ(3ul, list_length(&free_list)); END_TEST; } void insert_region(RegionList* regions, vaddr_t base, size_t size) { fbl::AllocChecker ac; auto test_region = fbl::AdoptRef(new (&ac) VmAddressRegionDummy(base, size)); ASSERT(ac.check()); regions->InsertRegion(ktl::move(test_region)); } bool remove_region(RegionList* regions, vaddr_t base) { auto region = regions->FindRegion(base); if (region == nullptr) { return false; } regions->RemoveRegion(region.get()); return true; } static bool region_list_get_alloc_spot_test() { BEGIN_TEST; RegionList regions; vaddr_t base = 0xFFFF000000000000; vaddr_t size = 0x0001000000000000; vaddr_t alloc_spot = 0; // Set the align to be 0x1000. uint8_t align_pow2 = 12; // Allocate 1 page, should be allocated at [+0, +0x1000]. size_t alloc_size = 0x1000; zx_status_t status = regions.GetAllocSpot(&alloc_spot, align_pow2, /*entropy=*/0, alloc_size, base, size, /*prng=*/nullptr); EXPECT_EQ(ZX_OK, status); EXPECT_EQ(base, alloc_spot); insert_region(&regions, alloc_spot, alloc_size); // Manually insert a sub region at [+0x2000, 0x3000]. insert_region(&regions, base + 0x2000, alloc_size); // Try to allocate 2 page, since the gap is too small, we would allocate at [0x3000, 0x5000]. alloc_size = 0x2000; status = regions.GetAllocSpot(&alloc_spot, align_pow2, /*entropy=*/0, alloc_size, base, size, /*prng=*/nullptr); EXPECT_EQ(ZX_OK, status); EXPECT_EQ(base + 0x3000, alloc_spot); insert_region(&regions, alloc_spot, alloc_size); EXPECT_TRUE(remove_region(&regions, base + 0x2000)); // After we remove the region, we now have a gap at [0x1000, 0x3000]. alloc_size = 0x2000; status = regions.GetAllocSpot(&alloc_spot, align_pow2, /*entropy=*/0, alloc_size, base, size, /*prng=*/nullptr); EXPECT_EQ(ZX_OK, status); EXPECT_EQ(base + 0x1000, alloc_spot); insert_region(&regions, alloc_spot, alloc_size); // Now we have fill all the gaps, next region should start at 0x5000. alloc_size = 0x1000; status = regions.GetAllocSpot(&alloc_spot, align_pow2, /*entropy=*/0, alloc_size, base, size, /*prng=*/nullptr); EXPECT_EQ(ZX_OK, status); EXPECT_EQ(base + 0x5000, alloc_spot); insert_region(&regions, alloc_spot, alloc_size); // Test for possible overflow cases. We try to allocate all the rest of the spaces. The last // region should be from [0x6000, base + size - 1], we should be able to find this region and // allocate all the size from it. alloc_size = size - 0x6000; status = regions.GetAllocSpot(&alloc_spot, align_pow2, /*entropy=*/0, alloc_size, base, size, /*prng=*/nullptr); EXPECT_EQ(ZX_OK, status); EXPECT_EQ(base + 0x6000, alloc_spot); END_TEST; } static bool region_list_get_alloc_spot_no_memory_test() { BEGIN_TEST; RegionList regions; vaddr_t base = 0xFFFF000000000000; vaddr_t size = 0x0001000000000000; // Set the align to be 0x1000. uint8_t align_pow2 = 12; insert_region(&regions, base, size - 0x1000); size_t alloc_size = 0x2000; vaddr_t alloc_spot = 0; // There is only a 1 page gap, and we are asking for two pages, so ZX_ERR_NO_MEMORY should be // returned. zx_status_t status = regions.GetAllocSpot(&alloc_spot, align_pow2, /*entropy=*/0, alloc_size, base, size, /*prng=*/nullptr); EXPECT_EQ(ZX_ERR_NO_MEMORY, status); END_TEST; } static bool region_list_find_region_test() { BEGIN_TEST; RegionList regions; vaddr_t base = 0xFFFF000000000000; auto region = regions.FindRegion(base); EXPECT_EQ(region.get(), nullptr); insert_region(&regions, base + 0x1000, 0x1000); region = regions.FindRegion(base + 1); EXPECT_EQ(region.get(), nullptr); region = regions.FindRegion(base + 0x1001); EXPECT_NE(region.get(), nullptr); EXPECT_EQ(base + 0x1000, region->base()); EXPECT_EQ((size_t)0x1000, region->size()); END_TEST; } static bool region_list_include_or_higher_test() { BEGIN_TEST; RegionList regions; vaddr_t base = 0xFFFF000000000000; insert_region(&regions, base + 0x1000, 0x1000); auto itr = regions.IncludeOrHigher(base + 1); EXPECT_TRUE(itr.IsValid()); EXPECT_EQ(base + 0x1000, itr->base()); EXPECT_EQ((size_t)0x1000, itr->size()); itr = regions.IncludeOrHigher(base + 0x1001); EXPECT_TRUE(itr.IsValid()); EXPECT_EQ(base + 0x1000, itr->base()); EXPECT_EQ((size_t)0x1000, itr->size()); itr = regions.IncludeOrHigher(base + 0x2000); EXPECT_FALSE(itr.IsValid()); END_TEST; } static bool region_list_upper_bound_test() { BEGIN_TEST; RegionList regions; vaddr_t base = 0xFFFF000000000000; insert_region(&regions, base + 0x1000, 0x1000); auto itr = regions.UpperBound(base + 0xFFF); EXPECT_TRUE(itr.IsValid()); EXPECT_EQ(base + 0x1000, itr->base()); EXPECT_EQ((size_t)0x1000, itr->size()); itr = regions.UpperBound(base + 0x1000); EXPECT_FALSE(itr.IsValid()); END_TEST; } static bool region_list_is_range_available_test() { BEGIN_TEST; RegionList regions; vaddr_t base = 0xFFFF000000000000; insert_region(&regions, base + 0x1000, 0x1000); insert_region(&regions, base + 0x3000, 0x1000); EXPECT_TRUE(regions.IsRangeAvailable(base, 0x1000)); EXPECT_FALSE(regions.IsRangeAvailable(base, 0x1001)); EXPECT_FALSE(regions.IsRangeAvailable(base + 1, 0x1000)); EXPECT_TRUE(regions.IsRangeAvailable(base + 0x2000, 1)); EXPECT_FALSE(regions.IsRangeAvailable(base + 0x1FFF, 0x2000)); EXPECT_TRUE(regions.IsRangeAvailable(0xFFFFFFFFFFFFFFFF, 1)); EXPECT_FALSE(regions.IsRangeAvailable(base, 0x0001000000000000)); END_TEST; } static bool pq_add_remove() { BEGIN_TEST; PageQueues pq; // Pretend we have an allocated page vm_page_t test_page = {}; test_page.set_state(VM_PAGE_STATE_OBJECT); // Need a VMO to claim our pager backed page is in fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(0, 0, PAGE_SIZE, &vmo); ASSERT_EQ(ZX_OK, status); VmObjectPaged* vmop = VmObjectPaged::AsVmObjectPaged(vmo); ASSERT_NONNULL(vmop); // Put the page in each queue and make sure it shows up pq.SetWired(&test_page); EXPECT_TRUE(pq.DebugPageIsWired(&test_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0}, 0, 1, 0})); pq.Remove(&test_page); EXPECT_FALSE(pq.DebugPageIsWired(&test_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0}, 0, 0, 0})); pq.SetUnswappable(&test_page); EXPECT_TRUE(pq.DebugPageIsUnswappable(&test_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0}, 1, 0, 0})); pq.Remove(&test_page); EXPECT_FALSE(pq.DebugPageIsUnswappable(&test_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0}, 0, 0, 0})); // Pretend we have some kind of pointer to a VmObjectPaged (this will never get dereferenced) pq.SetPagerBacked(&test_page, vmop, 0); EXPECT_TRUE(pq.DebugPageIsPagerBacked(&test_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{1, 0, 0, 0}, 0, 0, 0})); pq.Remove(&test_page); EXPECT_FALSE(pq.DebugPageIsPagerBacked(&test_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0}, 0, 0, 0})); END_TEST; } static bool pq_move_queues() { BEGIN_TEST; PageQueues pq; // Pretend we have an allocated page vm_page_t test_page = {}; test_page.set_state(VM_PAGE_STATE_OBJECT); // Need a VMO to claim our pager backed page is in fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(0, 0, PAGE_SIZE, &vmo); ASSERT_EQ(ZX_OK, status); VmObjectPaged* vmop = VmObjectPaged::AsVmObjectPaged(vmo); ASSERT_NONNULL(vmop); // Move the page between queues. pq.SetWired(&test_page); EXPECT_TRUE(pq.DebugPageIsWired(&test_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0}, 0, 1, 0})); pq.MoveToUnswappable(&test_page); EXPECT_FALSE(pq.DebugPageIsWired(&test_page)); EXPECT_TRUE(pq.DebugPageIsUnswappable(&test_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0}, 1, 0, 0})); pq.MoveToPagerBacked(&test_page, vmop, 0); EXPECT_FALSE(pq.DebugPageIsUnswappable(&test_page)); EXPECT_TRUE(pq.DebugPageIsPagerBacked(&test_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{1, 0, 0, 0}, 0, 0, 0})); pq.MoveToWired(&test_page); EXPECT_FALSE(pq.DebugPageIsPagerBacked(&test_page)); EXPECT_TRUE(pq.DebugPageIsWired(&test_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0}, 0, 1, 0})); pq.Remove(&test_page); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0}, 0, 0, 0})); END_TEST; } static bool pq_move_self_queue() { BEGIN_TEST; PageQueues pq; // Pretend we have an allocated page vm_page_t test_page = {}; test_page.set_state(VM_PAGE_STATE_OBJECT); // Move the page into the queue it is already in. pq.SetWired(&test_page); EXPECT_TRUE(pq.DebugPageIsWired(&test_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0}, 0, 1, 0})); pq.MoveToWired(&test_page); EXPECT_TRUE(pq.DebugPageIsWired(&test_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0}, 0, 1, 0})); pq.Remove(&test_page); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0}, 0, 0, 0})); END_TEST; } static bool pq_rotate_queue() { BEGIN_TEST; PageQueues pq; // Pretend we have a couple of allocated pages. vm_page_t wired_page = {}; vm_page_t pager_page = {}; wired_page.set_state(VM_PAGE_STATE_OBJECT); pager_page.set_state(VM_PAGE_STATE_OBJECT); // Need a VMO to claim our pager backed page is in. fbl::RefPtr<VmObject> vmo; zx_status_t status = VmObjectPaged::Create(0, 0, PAGE_SIZE, &vmo); ASSERT_EQ(ZX_OK, status); VmObjectPaged* vmop = VmObjectPaged::AsVmObjectPaged(vmo); ASSERT_NONNULL(vmop); // Put the pages in and validate initial state. pq.SetWired(&wired_page); pq.SetPagerBacked(&pager_page, vmop, 0); EXPECT_TRUE(pq.DebugPageIsWired(&wired_page)); size_t queue; EXPECT_TRUE(pq.DebugPageIsPagerBacked(&pager_page, &queue)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{1, 0, 0, 0}, 0, 1, 0})); EXPECT_EQ(queue, 0u); // Gradually rotate the queue. pq.RotatePagerBackedQueues(); EXPECT_TRUE(pq.DebugPageIsWired(&wired_page)); EXPECT_TRUE(pq.DebugPageIsPagerBacked(&pager_page, &queue)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0, 1, 0, 0}, 0, 1, 0})); EXPECT_EQ(queue, 1u); pq.RotatePagerBackedQueues(); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0, 0, 1, 0}, 0, 1, 0})); pq.RotatePagerBackedQueues(); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0, 0, 0, 1}, 0, 1, 0})); // Further rotations should not move the page. pq.RotatePagerBackedQueues(); EXPECT_TRUE(pq.DebugPageIsWired(&wired_page)); EXPECT_TRUE(pq.DebugPageIsPagerBacked(&pager_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0, 0, 0, 1}, 0, 1, 0})); // Moving the page should bring it back to the first queue. pq.MoveToPagerBacked(&pager_page, vmop, 0); EXPECT_TRUE(pq.DebugPageIsWired(&wired_page)); EXPECT_TRUE(pq.DebugPageIsPagerBacked(&pager_page)); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{1, 0, 0, 0}, 0, 1, 0})); // Just double check one rotation. pq.RotatePagerBackedQueues(); EXPECT_TRUE(pq.DebugQueueCounts() == ((PageQueues::Counts){{0, 1, 0, 0}, 0, 1, 0})); pq.Remove(&wired_page); pq.Remove(&pager_page); END_TEST; } static bool physmap_for_each_gap_test() { BEGIN_TEST; struct Gap { vaddr_t base; size_t size; }; fbl::Vector<Gap> actual_gaps; fbl::AllocChecker ac; auto PushBack = [&](vaddr_t base, size_t size) { actual_gaps.push_back({base, size}, &ac); ASSERT(ac.check()); }; { // No arenas, [ ]. actual_gaps.reset(); physmap_for_each_gap(PushBack, nullptr, 0); // One gap covering the entire physmap. ASSERT_EQ(actual_gaps.size(), 1u); ASSERT_EQ(actual_gaps[0].base, PHYSMAP_BASE); ASSERT_EQ(actual_gaps[0].size, PHYSMAP_SIZE); } { // One arena, no gaps, [A]. actual_gaps.reset(); pmm_arena_info_t arenas[] = { {"test-arena", 0, PHYSMAP_BASE_PHYS, PHYSMAP_SIZE}, }; physmap_for_each_gap(PushBack, arenas, ktl::size(arenas)); // No gaps. ASSERT_EQ(actual_gaps.size(), 0u); } { // One arena, gap at bottom, [ A]. actual_gaps.reset(); const size_t gap_size = 0x1000; const size_t arena_size = PHYSMAP_SIZE - gap_size; pmm_arena_info_t arenas[] = { {"test-arena", 0, PHYSMAP_BASE_PHYS + gap_size, arena_size}, }; physmap_for_each_gap(PushBack, arenas, ktl::size(arenas)); // One gap. ASSERT_EQ(actual_gaps.size(), 1u); ASSERT_EQ(actual_gaps[0].base, PHYSMAP_BASE); ASSERT_EQ(actual_gaps[0].size, gap_size); } { // One arena, gap at top, [A ]. actual_gaps.reset(); const size_t gap_size = 0x5000; const size_t arena_size = PHYSMAP_SIZE - gap_size; pmm_arena_info_t arenas[] = { {"test-arena", 0, PHYSMAP_BASE_PHYS, arena_size}, }; physmap_for_each_gap(PushBack, arenas, ktl::size(arenas)); // One gap. ASSERT_EQ(actual_gaps.size(), 1u); ASSERT_EQ(actual_gaps[0].base, PHYSMAP_BASE + arena_size); ASSERT_EQ(actual_gaps[0].size, gap_size); } { // Two arenas, no gaps, [AA]. actual_gaps.reset(); const size_t size = PHYSMAP_SIZE / 2; pmm_arena_info_t arenas[] = { {"test-arena", 0, PHYSMAP_BASE_PHYS, size}, {"test-arena", 0, PHYSMAP_BASE_PHYS + size, size}, }; physmap_for_each_gap(PushBack, arenas, ktl::size(arenas)); // No gaps. ASSERT_EQ(actual_gaps.size(), 0u); } { // Two arenas, three gaps, [ A A ]. actual_gaps.reset(); const size_t gap1_size = 0x300000; const size_t arena1_offset = gap1_size; const size_t arena1_size = 0x1000000; const size_t gap2_size = 0x35000; const size_t arena2_offset = gap1_size + arena1_size + gap2_size; const size_t arena2_size = 0xff1000000; pmm_arena_info_t arenas[] = { {"test-arena", 0, PHYSMAP_BASE_PHYS + arena1_offset, arena1_size}, {"test-arena", 0, PHYSMAP_BASE_PHYS + arena2_offset, arena2_size}, }; physmap_for_each_gap(PushBack, arenas, ktl::size(arenas)); // Three gaps. ASSERT_EQ(actual_gaps.size(), 3u); ASSERT_EQ(actual_gaps[0].base, PHYSMAP_BASE); ASSERT_EQ(actual_gaps[0].size, gap1_size); ASSERT_EQ(actual_gaps[1].base, PHYSMAP_BASE + arena1_offset + arena1_size); ASSERT_EQ(actual_gaps[1].size, gap2_size); const size_t arena3_offset = gap1_size + arena1_size + gap2_size + arena2_size; ASSERT_EQ(actual_gaps[2].base, PHYSMAP_BASE + arena3_offset); ASSERT_EQ(actual_gaps[2].size, PHYSMAP_SIZE - arena3_offset); } END_TEST; } #if __has_feature(address_sanitizer) static bool kasan_detects_use_after_free() { BEGIN_TEST; ManagedPmmNode node; vm_page_t* page; paddr_t paddr; zx_status_t status = node.node().AllocPage(PMM_ALLOC_DELAY_OK, &page, &paddr); ASSERT_EQ(ZX_OK, status, "pmm_alloc_page one page"); ASSERT_NE(paddr, 0UL); EXPECT_EQ(0UL, asan_region_is_poisoned(reinterpret_cast<uintptr_t>(paddr_to_physmap(paddr)), PAGE_SIZE)); node.node().FreePage(page); EXPECT_TRUE(asan_entire_region_is_poisoned(reinterpret_cast<uintptr_t>(paddr_to_physmap(paddr)), PAGE_SIZE)); END_TEST; } #endif // __has_feature(address_sanitizer) // Use the function name as the test name #define VM_UNITTEST(fname) UNITTEST(#fname, fname) UNITTEST_START_TESTCASE(vm_tests) VM_UNITTEST(vmm_alloc_smoke_test) VM_UNITTEST(vmm_alloc_contiguous_smoke_test) VM_UNITTEST(multiple_regions_test) VM_UNITTEST(vmm_alloc_zero_size_fails) VM_UNITTEST(vmm_alloc_bad_specific_pointer_fails) VM_UNITTEST(vmm_alloc_contiguous_missing_flag_commit_fails) VM_UNITTEST(vmm_alloc_contiguous_zero_size_fails) VM_UNITTEST(vmaspace_create_smoke_test) VM_UNITTEST(vmaspace_alloc_smoke_test) VM_UNITTEST(vmaspace_accessed_test) VM_UNITTEST(vmaspace_usercopy_accessed_fault_test) VM_UNITTEST(vmo_create_test) VM_UNITTEST(vmo_create_maximum_size) VM_UNITTEST(vmo_pin_test) VM_UNITTEST(vmo_multiple_pin_test) VM_UNITTEST(vmo_commit_test) VM_UNITTEST(vmo_odd_size_commit_test) VM_UNITTEST(vmo_create_physical_test) VM_UNITTEST(vmo_create_contiguous_test) VM_UNITTEST(vmo_contiguous_decommit_test) VM_UNITTEST(vmo_precommitted_map_test) VM_UNITTEST(vmo_demand_paged_map_test) VM_UNITTEST(vmo_dropped_ref_test) VM_UNITTEST(vmo_remap_test) VM_UNITTEST(vmo_double_remap_test) VM_UNITTEST(vmo_read_write_smoke_test) VM_UNITTEST(vmo_cache_test) VM_UNITTEST(vmo_lookup_test) VM_UNITTEST(vmo_lookup_clone_test) VM_UNITTEST(vmo_clone_removes_write_test) VM_UNITTEST(vmo_zero_scan_test) VM_UNITTEST(vmo_move_pages_on_access_test) VM_UNITTEST(vmo_eviction_test) VM_UNITTEST(vmo_validate_page_splits_test) VM_UNITTEST(arch_noncontiguous_map) VM_UNITTEST(vm_kernel_region_test) VM_UNITTEST(region_list_get_alloc_spot_test) VM_UNITTEST(region_list_get_alloc_spot_no_memory_test) VM_UNITTEST(region_list_find_region_test) VM_UNITTEST(region_list_include_or_higher_test) VM_UNITTEST(region_list_upper_bound_test) VM_UNITTEST(region_list_is_range_available_test) // Uncomment for debugging // VM_UNITTEST(dump_all_aspaces) // Run last UNITTEST_END_TESTCASE(vm_tests, "vm", "Virtual memory tests") UNITTEST_START_TESTCASE(pmm_tests) VM_UNITTEST(pmm_smoke_test) VM_UNITTEST(pmm_alloc_contiguous_one_test) VM_UNITTEST(pmm_node_multi_alloc_test) VM_UNITTEST(pmm_node_singlton_list_test) VM_UNITTEST(pmm_node_oversized_alloc_test) VM_UNITTEST(pmm_node_watermark_level_test) VM_UNITTEST(pmm_node_multi_watermark_level_test) VM_UNITTEST(pmm_node_multi_watermark_level_test2) VM_UNITTEST(pmm_node_oom_sync_alloc_failure_test) VM_UNITTEST(pmm_node_delayed_alloc_test) VM_UNITTEST(pmm_node_delayed_alloc_no_lowmem_test) VM_UNITTEST(pmm_node_delayed_alloc_swap_early_test) VM_UNITTEST(pmm_node_delayed_alloc_swap_late_test) VM_UNITTEST(pmm_node_delayed_alloc_clear_early_test) VM_UNITTEST(pmm_node_delayed_alloc_clear_late_test) VM_UNITTEST(pmm_checker_test) VM_UNITTEST(pmm_checker_is_valid_fill_size_test) VM_UNITTEST(pmm_get_arena_info_test) UNITTEST_END_TESTCASE(pmm_tests, "pmm", "Physical memory manager tests") UNITTEST_START_TESTCASE(vm_page_list_tests) VM_UNITTEST(vmpl_add_remove_page_test) VM_UNITTEST(vmpl_basic_marker_test) VM_UNITTEST(vmpl_free_pages_test) VM_UNITTEST(vmpl_free_pages_last_page_test) VM_UNITTEST(vmpl_near_last_offset_free) VM_UNITTEST(vmpl_take_single_page_even_test) VM_UNITTEST(vmpl_take_single_page_odd_test) VM_UNITTEST(vmpl_take_all_pages_test) VM_UNITTEST(vmpl_take_middle_pages_test) VM_UNITTEST(vmpl_take_gap_test) VM_UNITTEST(vmpl_take_empty_test) VM_UNITTEST(vmpl_take_cleanup_test) VM_UNITTEST(vmpl_page_gap_iter_test) VM_UNITTEST(vmpl_merge_offset_test) VM_UNITTEST(vmpl_merge_overlap_test) VM_UNITTEST(vmpl_for_every_page_test) VM_UNITTEST(vmpl_merge_onto_test) UNITTEST_END_TESTCASE(vm_page_list_tests, "vmpl", "VmPageList tests") UNITTEST_START_TESTCASE(page_queues_tests) VM_UNITTEST(pq_add_remove) VM_UNITTEST(pq_move_queues) VM_UNITTEST(pq_move_self_queue) VM_UNITTEST(pq_rotate_queue) UNITTEST_END_TESTCASE(page_queues_tests, "pq", "PageQueues tests") UNITTEST_START_TESTCASE(physmap_tests) VM_UNITTEST(physmap_for_each_gap_test) UNITTEST_END_TESTCASE(physmap_tests, "physmap", "physmap tests") #if __has_feature(address_sanitizer) UNITTEST_START_TESTCASE(kasan_pmm_tests) VM_UNITTEST(kasan_detects_use_after_free) UNITTEST_END_TESTCASE(kasan_pmm_tests, "kasan_pmm", "kasan pmm tests") #endif // __has_feature(address_sanitizer)
33.57055
100
0.704971
oshunter
33684bb6b44f771fa38c699b33d5f8c05b88a25c
3,446
hpp
C++
Source/Matter/MatterCCZ4.impl.hpp
boxuange/GRChomboo
22cf6751a3be29776f35a39f433f6bb497280720
[ "BSD-3-Clause" ]
3
2019-11-25T17:21:28.000Z
2021-09-10T15:45:57.000Z
Source/Matter/MatterCCZ4.impl.hpp
boxuange/GRChomboo
22cf6751a3be29776f35a39f433f6bb497280720
[ "BSD-3-Clause" ]
null
null
null
Source/Matter/MatterCCZ4.impl.hpp
boxuange/GRChomboo
22cf6751a3be29776f35a39f433f6bb497280720
[ "BSD-3-Clause" ]
1
2022-02-24T23:01:02.000Z
2022-02-24T23:01:02.000Z
/* GRChombo * Copyright 2012 The GRChombo collaboration. * Please refer to LICENSE in GRChombo's root directory. */ #if !defined(MATTERCCZ4_HPP_) #error "This file should only be included through MatterCCZ4.hpp" #endif #ifndef MATTERCCZ4_IMPL_HPP_ #define MATTERCCZ4_IMPL_HPP_ #include "DimensionDefinitions.hpp" template <class matter_t> MatterCCZ4<matter_t>::MatterCCZ4(matter_t a_matter, params_t params, double dx, double sigma, int formulation, double G_Newton) : CCZ4(params, dx, sigma, formulation, 0.0 /*No cosmological constant*/), my_matter(a_matter), m_G_Newton(G_Newton) { } template <class matter_t> template <class data_t> void MatterCCZ4<matter_t>::compute(Cell<data_t> current_cell) const { // copy data from chombo gridpoint into local variables const auto matter_vars = current_cell.template load_vars<Vars>(); const auto d1 = m_deriv.template diff1<Vars>(current_cell); const auto d2 = m_deriv.template diff2<Diff2Vars>(current_cell); const auto advec = m_deriv.template advection<Vars>(current_cell, matter_vars.shift); // Call CCZ4 RHS - work out RHS without matter, no dissipation Vars<data_t> matter_rhs; rhs_equation(matter_rhs, matter_vars, d1, d2, advec); // add RHS matter terms from EM Tensor add_emtensor_rhs(matter_rhs, matter_vars, d1); // add evolution of matter fields themselves my_matter.add_matter_rhs(matter_rhs, matter_vars, d1, d2, advec); // Add dissipation to all terms m_deriv.add_dissipation(matter_rhs, current_cell, m_sigma); // Write the rhs into the output FArrayBox current_cell.store_vars(matter_rhs); } // Function to add in EM Tensor matter terms to CCZ4 rhs template <class matter_t> template <class data_t> void MatterCCZ4<matter_t>::add_emtensor_rhs( Vars<data_t> &matter_rhs, const Vars<data_t> &matter_vars, const Vars<Tensor<1, data_t>> &d1) const { using namespace TensorAlgebra; const auto h_UU = compute_inverse_sym(matter_vars.h); const auto chris = compute_christoffel(d1.h, h_UU); // Calculate elements of the decomposed stress energy tensor const auto emtensor = my_matter.compute_emtensor(matter_vars, d1, h_UU, chris.ULL); // Update RHS for K and Theta depending on formulation if (m_formulation == USE_BSSN) { matter_rhs.K += 4.0 * M_PI * m_G_Newton * matter_vars.lapse * (emtensor.S + emtensor.rho); matter_rhs.Theta += 0.0; } else { matter_rhs.K += 4.0 * M_PI * m_G_Newton * matter_vars.lapse * (emtensor.S - 3 * emtensor.rho); matter_rhs.Theta += -8.0 * M_PI * m_G_Newton * matter_vars.lapse * emtensor.rho; } // Update RHS for other variables Tensor<2, data_t> Sij_TF = emtensor.Sij; make_trace_free(Sij_TF, matter_vars.h, h_UU); FOR2(i, j) { matter_rhs.A[i][j] += -8.0 * M_PI * m_G_Newton * matter_vars.chi * matter_vars.lapse * Sij_TF[i][j]; } FOR1(i) { data_t matter_term_Gamma = 0.0; FOR1(j) { matter_term_Gamma += -16.0 * M_PI * m_G_Newton * matter_vars.lapse * h_UU[i][j] * emtensor.Si[j]; } matter_rhs.Gamma[i] += matter_term_Gamma; matter_rhs.B[i] += matter_term_Gamma; } } #endif /* MATTERCCZ4_IMPL_HPP_ */
32.509434
80
0.663378
boxuange
3369b7a724d1f8ff24bc30f97d6e4c348a0202a0
4,332
cpp
C++
src/main.cpp
stoneface86/trackerboy
68cbb4c56ec4bbccfd1fe172a57451bdaba91561
[ "MIT" ]
60
2019-11-30T00:30:33.000Z
2022-03-26T03:44:53.000Z
src/main.cpp
stoneface86/trackerboy
68cbb4c56ec4bbccfd1fe172a57451bdaba91561
[ "MIT" ]
8
2019-12-16T07:55:54.000Z
2022-03-09T21:01:02.000Z
src/main.cpp
stoneface86/trackerboy
68cbb4c56ec4bbccfd1fe172a57451bdaba91561
[ "MIT" ]
3
2021-08-06T07:17:15.000Z
2022-03-08T03:39:06.000Z
#include "forms/MainWindow.hpp" #include <QApplication> #include <QCommandLineParser> #include <QDateTime> #include <QFontDatabase> #include <QFile> #include <QFileInfo> #include <QElapsedTimer> #include <QMessageBox> #include <QPointer> #include <QStringBuilder> #include <QtDebug> #include <QTextStream> #include <iostream> #include <chrono> #include <memory> #include <new> #include <cstdio> #include "version.hpp" constexpr int EXIT_BAD_ARGUMENTS = -1; constexpr int EXIT_BAD_ALLOC = 1; // // Singleton class for a custom Qt message handler. This message handler wraps // the default handler and calls MainWindow::panic for QtFatalMsg messages. // class MessageHandler { public: static MessageHandler& instance() { static MessageHandler instance; return instance; } void setWindow(MainWindow *window) { mWindow = window; } private: MessageHandler() : mDefaultHandler(qInstallMessageHandler(message)) { } static void message(QtMsgType type, QMessageLogContext const& context, QString const& txt) { instance()._message(type, context, txt); } void _message(QtMsgType type, QMessageLogContext const& context, QString const& txt) { if (type == QtFatalMsg && mWindow) { // force the window to save a copy of the module if needed mWindow->panic(txt); } // let qt's default handler do everything else mDefaultHandler(type, context, txt); } QPointer<MainWindow> mWindow; QtMessageHandler mDefaultHandler; }; int main(int argc, char *argv[]) { int code; #ifndef QT_NO_INFO_OUTPUT QElapsedTimer timer; timer.start(); #endif QApplication app(argc, argv); QCoreApplication::setOrganizationName("Trackerboy"); QCoreApplication::setApplicationName("Trackerboy"); QCoreApplication::setApplicationVersion(VERSION_STR); // use INI on all systems, much easier to edit by hand QSettings::setDefaultFormat(QSettings::IniFormat); #define main_tr(str) QCoreApplication::translate("main", str) QCommandLineParser parser; parser.setApplicationDescription(main_tr("Game Boy music tracker")); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument("[module_file]", main_tr("(Optional) the module file to open")); parser.process(app); QString fileToOpen; auto const positionals = parser.positionalArguments(); switch (positionals.size()) { case 0: break; case 1: fileToOpen = positionals[0]; break; default: // we could just only take the first argument and ignore the rest // but I prefer to be strict fputs("too many arguments given\n", stderr); fputs(qPrintable(parser.helpText()), stderr); return EXIT_BAD_ARGUMENTS; } // register types for signals qRegisterMetaType<ChannelOutput::Flags>("ChannelOutput::Flags"); qRegisterMetaType<PatternModel::CursorChangeFlags>("CursorChangeFlags"); // instantiate the custom message handler for logging to file MessageHandler::instance(); // add the default font for the pattern editor QFontDatabase::addApplicationFont(":/CascadiaMono.ttf"); auto win = std::make_unique<MainWindow>(); MessageHandler::instance().setWindow(win.get()); win->show(); if (!fileToOpen.isEmpty()) { QFileInfo info(fileToOpen); if (!info.exists()) { QMessageBox::critical( win.get(), main_tr("File does not exist"), main_tr("The module could not be opened because the file does not exist") ); } else if (!info.isFile()) { QMessageBox::critical( win.get(), main_tr("Invalid filename"), main_tr("The module could not be opened because it is not a file") ); } else { win->openFile(fileToOpen); } } #ifndef QT_NO_INFO_OUTPUT qInfo() << "Launch time: " << timer.elapsed() << " ms"; #endif try { code = app.exec(); } catch (const std::bad_alloc &) { qCritical() << "out of memory"; return EXIT_BAD_ALLOC; } return code; }
26.414634
97
0.64012
stoneface86
336a96defe3ef94edeed2ef440f748d6a63e90e9
4,076
hpp
C++
ql/termstructures/volatility/equityfx/localvolsurface.hpp
urgu00/QuantLib
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
[ "BSD-3-Clause" ]
null
null
null
ql/termstructures/volatility/equityfx/localvolsurface.hpp
urgu00/QuantLib
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
[ "BSD-3-Clause" ]
null
null
null
ql/termstructures/volatility/equityfx/localvolsurface.hpp
urgu00/QuantLib
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
[ "BSD-3-Clause" ]
null
null
null
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2003 Ferdinando Ametrano This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file localvolsurface.hpp \brief Local volatility surface derived from a Black vol surface */ #ifndef quantlib_localvolsurface_hpp #define quantlib_localvolsurface_hpp #include <ql/termstructures/volatility/equityfx/localvoltermstructure.hpp> #include <ql/termstructures/volatility/equityfx/fixedlocalvolsurface.hpp> namespace QuantLib { class BlackVolTermStructure; class YieldTermStructure; class Quote; //! Local volatility surface derived from a Black vol surface /*! For details about this implementation refer to "Stochastic Volatility and Local Volatility," in "Case Studies and Financial Modelling Course Notes," by Jim Gatheral, Fall Term, 2003 see www.math.nyu.edu/fellows_fin_math/gatheral/Lecture1_Fall02.pdf \bug this class is untested, probably unreliable. */ class LocalVolSurface : public LocalVolTermStructure { public: LocalVolSurface(const Handle<BlackVolTermStructure>& blackTS, const Handle<YieldTermStructure>& riskFreeTS, const Handle<YieldTermStructure>& dividendTS, const Handle<Quote>& underlying); LocalVolSurface(const Handle<BlackVolTermStructure>& blackTS, const Handle<YieldTermStructure>& riskFreeTS, const Handle<YieldTermStructure>& dividendTS, Real underlying); //! \name TermStructure interface //@{ const Date& referenceDate() const; DayCounter dayCounter() const; Date maxDate() const; //@} //! \name VolatilityTermStructure interface //@{ Real minStrike() const; Real maxStrike() const; //@} //! \name Visitability //@{ virtual void accept(AcyclicVisitor&); //@} inline Handle<Quote> getUnderlying() { return underlying_; }; inline Handle<YieldTermStructure>& getDividendTS() { return dividendTS_; }; inline Handle<YieldTermStructure>& getInterestRateTS() { return riskFreeTS_; }; inline Handle<BlackVolTermStructure>& getBlackSurface() { return blackTS_; }; protected: Volatility localVolImpl(Time, Real) const; private: Handle<BlackVolTermStructure> blackTS_; Handle<YieldTermStructure> riskFreeTS_, dividendTS_; Handle<Quote> underlying_; }; class InterpolatedLocalVolSurface : public LocalVolSurface { public: InterpolatedLocalVolSurface(const Handle<BlackVolTermStructure>& blackTS, const Handle<YieldTermStructure>& riskFreeTS, const Handle<YieldTermStructure>& dividendTS, const Handle<Quote>& underlying, Size strikeGridAmt, Size timeStepsPerYear); inline Matrix getSurface() { Matrix mat(gridTimes_.size(), strikes_[0]->size()); for (size_t i = 0; i < mat.rows(); i++) { for (size_t j = 0; j < mat.columns(); j++) { mat[i][j] = surface_->localVol(gridTimes_[i], strikes_[i]->at(j), true); } } return mat; }; protected: Volatility localVolImpl(Time, Real) const; private: ext::shared_ptr<FixedLocalVolSurface> surface_; std::vector<Time> gridTimes_; std::vector<ext::shared_ptr<std::vector<Real> > > strikes_; }; } #endif
34.252101
81
0.685967
urgu00
336c2f274272c5e15bbb6787f56f08fb3be15f3c
316
cpp
C++
PAT (Advanced Level) Practice/1001 A+B Format (20).cpp
vuzway/PAT
5db8ca9295b51ad9e99c815a46e4ac764d7d06c1
[ "MIT" ]
5
2020-02-10T08:26:19.000Z
2020-07-09T00:11:16.000Z
PAT (Advanced Level) Practice/1001 A+B Format (20).cpp
Assassin2016/zju_data_structures_and_algorithms_in_MOOC
5db8ca9295b51ad9e99c815a46e4ac764d7d06c1
[ "MIT" ]
null
null
null
PAT (Advanced Level) Practice/1001 A+B Format (20).cpp
Assassin2016/zju_data_structures_and_algorithms_in_MOOC
5db8ca9295b51ad9e99c815a46e4ac764d7d06c1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int a, b; cin >> a >> b; int sum = a + b; if (sum < 0) printf("-"); string s = to_string(abs(sum)); for (int i = 0; i < s.length(); i++) { if ((s.length()-1-i+1) % 3 == 0 && i != s.length()-1 && i != 0) printf(","); printf("%c", s[i]); } return 0; }
21.066667
78
0.490506
vuzway
33702a11cb136b3de30662890faddeefc097626c
3,936
hpp
C++
engine_template/DebugEditor.hpp
grant-h/gfx
1ae200350f019fec23dfd7c17fdae74a2e587a57
[ "MIT" ]
1
2019-03-07T12:00:12.000Z
2019-03-07T12:00:12.000Z
engine_template/DebugEditor.hpp
grant-h/gfx
1ae200350f019fec23dfd7c17fdae74a2e587a57
[ "MIT" ]
null
null
null
engine_template/DebugEditor.hpp
grant-h/gfx
1ae200350f019fec23dfd7c17fdae74a2e587a57
[ "MIT" ]
null
null
null
#ifndef _DEBUG_EDITOR_H #define _DEBUG_EDITOR_H #include <vector> #include <memory> #include <Shader.hpp> #include <ResourceManager.hpp> #include <Renderer.hpp> #include <imgui.h> #include <TextEditor.h> extern const TextEditor::Palette custom_palette; class DebugEditor { private: TextEditor text_editor_; std::shared_ptr<Shader> current_shader_; std::string file_name_; public: DebugEditor() { auto lang = TextEditor::LanguageDefinition::GLSL(); current_shader_ = ResourceManager::instance()->get_shader("Phong.frag"); text_editor_.SetText(current_shader_->get_code()); text_editor_.SetLanguageDefinition(lang); text_editor_.SetPalette(custom_palette); } ~DebugEditor() = default; void draw() { auto cpos = text_editor_.GetCursorPosition(); ImGui::Begin("Text Editor Demo", nullptr, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_MenuBar); ImGui::SetWindowSize(ImVec2(800, 600), ImGuiCond_FirstUseEver); if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("Save", "Ctrl-S", nullptr, true)) { auto textToSave = text_editor_.GetText(); current_shader_->set_code(textToSave); ResourceManager::instance()->recompile_shader(current_shader_); } if (ImGui::MenuItem("Quit", "Alt-F4")) ; ImGui::EndMenu(); } if (ImGui::BeginMenu("Edit")) { bool ro = text_editor_.IsReadOnly(); if (ImGui::MenuItem("Read-only mode", nullptr, &ro)) text_editor_.SetReadOnly(ro); ImGui::Separator(); if (ImGui::MenuItem("Undo", "ALT-Backspace", nullptr, !ro && text_editor_.CanUndo())) text_editor_.Undo(); if (ImGui::MenuItem("Redo", "Ctrl-Y", nullptr, !ro && text_editor_.CanRedo())) text_editor_.Redo(); ImGui::Separator(); if (ImGui::MenuItem("Copy", "Ctrl-C", nullptr, text_editor_.HasSelection())) text_editor_.Copy(); if (ImGui::MenuItem("Cut", "Ctrl-X", nullptr, !ro && text_editor_.HasSelection())) text_editor_.Cut(); if (ImGui::MenuItem("Delete", "Del", nullptr, !ro && text_editor_.HasSelection())) text_editor_.Delete(); if (ImGui::MenuItem("Paste", "Ctrl-V", nullptr, !ro && ImGui::GetClipboardText() != nullptr)) text_editor_.Paste(); ImGui::Separator(); if (ImGui::MenuItem("Select all", nullptr, nullptr)) text_editor_.SetSelection(TextEditor::Coordinates(), TextEditor::Coordinates(text_editor_.GetTotalLines(), 0)); ImGui::EndMenu(); } if (ImGui::BeginMenu("View")) { if (ImGui::MenuItem("Dark palette")) text_editor_.SetPalette(TextEditor::GetDarkPalette()); if (ImGui::MenuItem("Light palette")) text_editor_.SetPalette(TextEditor::GetLightPalette()); if (ImGui::MenuItem("Retro blue palette")) text_editor_.SetPalette(TextEditor::GetRetroBluePalette()); ImGui::EndMenu(); } ImGui::EndMenuBar(); } ImGui::Text("%6d/%-6d %6d lines | %s | %s | %s | %s", cpos.mLine + 1, cpos.mColumn + 1, text_editor_.GetTotalLines(), text_editor_.IsOverwrite() ? "Ovr" : "Ins", text_editor_.CanUndo() ? "*" : " ", text_editor_.GetLanguageDefinition().mName.c_str(), file_name_.c_str()); float alpha_before = ImGui::GetStyle().Alpha; ImVec4* colors = ImGui::GetStyle().Colors; colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.70f); //ImGui::GetStyle().Alpha = 0.55f; //ImGui::GetStyle().WindowBG = 0.00f; text_editor_.Render("TextEditor"); ImGui::GetStyle().Alpha = alpha_before; ImGui::End(); } }; #endif // _DEBUG_EDITOR_H
35.142857
124
0.60747
grant-h
337044fb8f5ddb5b107fafd26b38f26f048fdad7
362
hpp
C++
include/framework/Curves.hpp
ThePythonator/Bucket-Inc
d8d4fc7c3b66cf6b3c96d2ed4612f9ffc4844ba9
[ "MIT" ]
2
2022-03-17T18:11:07.000Z
2022-03-17T19:55:35.000Z
include/framework/Curves.hpp
ThePythonator/Rocket-Manager
61489a9df2ac25b96ac337afd5cb58375533c748
[ "MIT" ]
null
null
null
include/framework/Curves.hpp
ThePythonator/Rocket-Manager
61489a9df2ac25b96ac337afd5cb58375533c748
[ "MIT" ]
null
null
null
#pragma once #include "Maths.hpp" namespace Framework { namespace Curves { // Linear interpolation, where t is from 0 to 1 int linear(int start, int end, float t); float linear(float start, float end, float t); vec2 linear(vec2 start, vec2 end, float t); // Bezier curve, where t is from 0 to 1 vec2 bezier(std::vector<vec2> nodes, float t); } }
24.133333
49
0.690608
ThePythonator
3372bcc8537467de772d82323dfede95a9170f38
3,017
cpp
C++
src/storage/NFS.cpp
varchar-io/nebula
5a892b32fa0419d8fb87bd1b8e9f010b8b83fa8b
[ "Apache-2.0" ]
96
2020-12-08T22:09:05.000Z
2022-03-29T21:43:33.000Z
src/storage/NFS.cpp
varchar-io/nebula
5a892b32fa0419d8fb87bd1b8e9f010b8b83fa8b
[ "Apache-2.0" ]
94
2020-10-31T00:26:11.000Z
2022-03-23T21:19:59.000Z
src/storage/NFS.cpp
varchar-io/nebula
5a892b32fa0419d8fb87bd1b8e9f010b8b83fa8b
[ "Apache-2.0" ]
9
2020-11-15T23:20:40.000Z
2022-03-22T16:23:39.000Z
/* * Copyright 2017-present varchar.io * * 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 <uriparser/Uri.h> #include "NFS.h" #include "common/Likely.h" /** * File system and related APIs */ namespace nebula { namespace storage { std::unique_ptr<NFileSystem> makeFS(const std::string& proto, const std::string& bucket) { if (proto == "local") { return std::make_unique<nebula::storage::local::File>(); } if (proto == "s3") { return std::make_unique<nebula::storage::aws::S3>(bucket); } if (proto == "gs") { return std::make_unique<nebula::storage::gcp::GCS>(bucket); } throw NException(fmt::format("unsupported file system: {0}", proto)); } UriInfo parse(const std::string& strUri) { UriUriA uri; UriParserStateA state; state.uri = &uri; if (uriParseUriA(&state, strUri.c_str()) != URI_SUCCESS) { throw NException(fmt::format("Error parsing {0} at {1}: {2}", strUri, state.errorPos, state.errorCode)); } // got uri parsed successfully #define UF_STR(F) std::string(uri.F.first, uri.F.afterLast - uri.F.first) UriInfo info; if (uri.scheme.first) { info.schema = UF_STR(scheme); } if (uri.hostText.first) { info.host = UF_STR(hostText); } // TODO(cao) - doesn't seem system compatible? probably remove // handle local path without starting '/' if (info.schema.empty() && info.host.empty() && strUri.at(0) != '/') { info.path = fmt::format("/{0}", strUri); } else if (uri.pathHead) { const UriPathSegmentA* p = uri.pathHead; const char* start = p->text.first; const char* end = nullptr; // locate the last position // why do we need a loop for the start and end, pathTail won't help if last character is "/" for (; p; p = p->next) { if (N_LIKELY(p->text.first != p->text.afterLast)) { end = p->text.afterLast; } } // if schema is empty, assume it's a local file. // allow it to carry the char before it. if (info.schema.empty() || info.host.empty()) { start -= 1; } info.path = std::string(start, end - start); // decode the data in place, and mark end position to be 0 char* head = info.path.data(); const char* tail = uriUnescapeInPlaceExA(head, false, UriBreakConversion::URI_BR_DONT_TOUCH); info.path.resize(tail - head); } #undef UF_STR // this is c-library requiring an explicit free uriFreeUriMembersA(&uri); // return the just constructed info return info; } } // namespace storage } // namespace nebula
29.009615
108
0.661584
varchar-io
3374a15076d2a5289401f1fa3ba1f8fc7816cb99
4,731
cpp
C++
mcrouter/lib/config/test/config_preprocessor_test.cpp
edenzik/mcrouter
6087962cd45530447c51f659a918862e4ad6acc0
[ "MIT" ]
2
2020-03-19T17:25:21.000Z
2020-03-19T17:25:29.000Z
mcrouter/lib/config/test/config_preprocessor_test.cpp
fakeNetflix/facebook-repo-mcrouter
cc9fb6ace9e21f174b2d620c3c9e57d99156df47
[ "MIT" ]
null
null
null
mcrouter/lib/config/test/config_preprocessor_test.cpp
fakeNetflix/facebook-repo-mcrouter
cc9fb6ace9e21f174b2d620c3c9e57d99156df47
[ "MIT" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ #include <string> #include <vector> #include <glog/logging.h> #include <gtest/gtest.h> #include <folly/FileUtil.h> #include <folly/Range.h> #include <folly/json.h> #include "mcrouter/lib/config/ConfigPreprocessor.h" #include "mcrouter/lib/config/ImportResolverIf.h" #include "mcrouter/lib/fbi/cpp/util.h" using facebook::memcache::ConfigPreprocessor; using facebook::memcache::ImportResolverIf; using facebook::memcache::parseJsonString; const std::string kTestFile = "mcrouter/lib/config/test/config_preprocessor_test_file.json"; const std::string kTestFileErrors = "mcrouter/lib/config/test/config_preprocessor_test_errors.json"; const std::string kTestFileComments = "mcrouter/lib/config/test/config_preprocessor_test_comments.json"; const folly::StringKeyedUnorderedMap<folly::dynamic> kGlobalParams = { {"testGlobal", "test"}, {"templGlobal", "templ"}}; class MockImportResolver : public ImportResolverIf { std::string import(folly::StringPiece path) final { if (path == "test") { return "\"mock_test\""; } if (path == "templ") { return "{ \"type\": \"macroDef\", \"result\": \"imported_macro\" }"; } if (path == "do_not_exist") { throw std::runtime_error(std::string("Can not import") + path.str()); } return ""; } }; void runCase( const folly::dynamic& consts, const folly::dynamic& macros, const std::string& caseName, const folly::dynamic& caseObj) { LOG(INFO) << " Case: " << caseName; auto orig = caseObj["orig"]; auto expand = caseObj["expand"]; folly::dynamic obj = folly::dynamic::object("consts", consts)("macros", macros)("orig", orig); MockImportResolver resolver; folly::json::metadata_map configMetadataMap; auto result = ConfigPreprocessor::getConfigWithoutMacros( folly::toJson(obj), resolver, kGlobalParams, &configMetadataMap); auto origExpand = result["orig"]; folly::json::serialization_opts opts; opts.sort_keys = true; opts.pretty_formatting = false; auto jsonExpand = folly::json::serialize(expand, opts); auto jsonOrigExpand = folly::json::serialize(origExpand, opts); ASSERT_EQ(jsonExpand, jsonOrigExpand) << "Case: " << caseName << " fail"; LOG(INFO) << " success"; } void runTest(const std::string& testName, const folly::dynamic& testObj) { LOG(INFO) << "Test: " << testName; if (!testObj.count("macros")) { throw std::logic_error("TestObj without macros"); } folly::dynamic consts = folly::dynamic::array; if (testObj.count("consts")) { consts = testObj["consts"]; } for (auto& it : testObj["cases"].items()) { auto caseName = it.first.asString(); auto caseObj = it.second; runCase(consts, testObj["macros"], testName + ":" + caseName, it.second); } } TEST(ConfigPreprocessorTest, macros) { std::string jsonStr; if (!folly::readFile(kTestFile.data(), jsonStr)) { FAIL() << "can not read test file " << kTestFile; } auto json = parseJsonString(jsonStr); for (auto& test : json.items()) { auto testName = test.first.asString(); auto testObj = test.second; runTest(testName, testObj); } } TEST(ConfigPreprocessorTest, errors) { MockImportResolver resolver; std::string jsonStr; if (!folly::readFile(kTestFileErrors.data(), jsonStr)) { FAIL() << "can not read test file " << kTestFileErrors; } auto json = parseJsonString(jsonStr); for (auto testCase : json.items()) { LOG(INFO) << "Case: " << testCase.first.asString(); auto caseStr = folly::toJson(testCase.second); try { folly::json::metadata_map configMetadataMap; ConfigPreprocessor::getConfigWithoutMacros( caseStr, resolver, kGlobalParams, &configMetadataMap); } catch (const std::logic_error& e) { LOG(INFO) << "success " << e.what(); continue; } FAIL() << "Case " << testCase.first.asString() << ": No error thrown"; } } TEST(ConfigPreprocessorTest, comments) { MockImportResolver resolver; std::string jsonStr; if (!folly::readFile(kTestFileComments.data(), jsonStr)) { FAIL() << "can not read test file " << kTestFileErrors; } folly::json::metadata_map configMetadataMap; auto json = ConfigPreprocessor::getConfigWithoutMacros( jsonStr, resolver, kGlobalParams, &configMetadataMap); folly::json::serialization_opts opts; opts.sort_keys = true; opts.pretty_formatting = false; auto orig = folly::json::serialize(json["orig"], opts); auto expand = folly::json::serialize(json["expand"], opts); EXPECT_EQ(orig, expand); }
29.754717
79
0.680194
edenzik
33765ddc9bbc26f99197006f4a4db6fe60adc2c3
2,549
cpp
C++
test/op/ScatterNdTest.cpp
JujuDel/MNN
8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a
[ "Apache-2.0" ]
6,958
2019-05-06T02:38:02.000Z
2022-03-31T18:08:48.000Z
test/op/ScatterNdTest.cpp
JujuDel/MNN
8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a
[ "Apache-2.0" ]
1,775
2019-05-06T04:40:19.000Z
2022-03-30T15:39:24.000Z
test/op/ScatterNdTest.cpp
JujuDel/MNN
8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a
[ "Apache-2.0" ]
1,511
2019-05-06T02:38:05.000Z
2022-03-31T16:59:39.000Z
// // ScatterNdTest.cpp // MNNTests // // Created by MNN on 2019/11/28. // Copyright © 2018, Alibaba Group Holding Limited // #include <MNN/expr/Expr.hpp> #include <MNN/expr/ExprCreator.hpp> #include "MNNTestSuite.h" #include "TestUtils.h" using namespace MNN::Express; class ScatterNdTest : public MNNTestCase { virtual ~ScatterNdTest() = default; virtual bool run(int precision) { { const int indicesData[] = {4, 3, 1, 7}; const float updatesData[] = {9, 10, 11, 12}; const int shapeData[] = {8}; const float expectedResult[] = {0, 11, 0, 10, 9, 0, 0, 12}; auto indices = _Const(indicesData, {4, 1}, NHWC, halide_type_of<int>()); auto updates = _Const(updatesData, {4}, NHWC, halide_type_of<float>()); auto shape = _Const(shapeData, {1}, NHWC, halide_type_of<float>()); auto result = _ScatterNd(indices, updates, shape); auto resultData = result->readMap<float>(); const int size = result->getInfo()->size; if (!checkVector<float>(resultData, expectedResult, size, 0.001)) { return false; } } { const int indicesData[] = {0, 2}; const float updatesData[] = {5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8}; const int shapeData[] = {4, 4, 4}; auto indices = _Const(indicesData, {2, 1}, NHWC, halide_type_of<int>()); auto updates = _Const(updatesData, {2, 4, 4}, NHWC, halide_type_of<float>()); auto shape = _Const(shapeData, {3}, NHWC, halide_type_of<int>()); const float expectedResult[] = {5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto result = _ScatterNd(indices, updates, shape); auto resultData = result->readMap<float>(); const int size = result->getInfo()->size; if (!checkVector<float>(resultData, expectedResult, size, 0.001)) { return false; } } return true; } }; MNNTestSuiteRegister(ScatterNdTest, "op/ScatterNdTest");
40.460317
109
0.490781
JujuDel
337b9cd5b80093d14bfe28fc84d231c77c260445
2,109
hpp
C++
src/shard_port_calculator.hpp
jtcarnes/cpp-driver
2bdfa2b90c2050b56c0572ba039f576fb5f1a922
[ "Apache-2.0" ]
11
2020-07-27T10:17:29.000Z
2022-03-12T10:41:41.000Z
src/shard_port_calculator.hpp
jtcarnes/cpp-driver
2bdfa2b90c2050b56c0572ba039f576fb5f1a922
[ "Apache-2.0" ]
40
2020-07-27T09:15:07.000Z
2022-03-29T11:23:05.000Z
src/shard_port_calculator.hpp
jtcarnes/cpp-driver
2bdfa2b90c2050b56c0572ba039f576fb5f1a922
[ "Apache-2.0" ]
15
2020-07-29T20:40:24.000Z
2022-03-29T06:34:34.000Z
/* * Copyright (C) 2020 ScyllaDB * * 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 DATASTAX_INTERNAL_SHARD_PORT_CALCULATOR_HPP #define DATASTAX_INTERNAL_SHARD_PORT_CALCULATOR_HPP #include "optional.hpp" #include <uv.h> #include <map> #include <stddef.h> namespace datastax { namespace internal { namespace core { /** * Server can be configured to route the client connections to specific shards, * based on their local port numbers. This class calculates outgoing port numbers * for such a case. It is intended to have 1 instance of this class per Cluster. */ class ShardPortCalculator final { public: ShardPortCalculator(int local_port_range_lo, int local_port_range_hi); ShardPortCalculator(const ShardPortCalculator&) = delete; ShardPortCalculator& operator=(const ShardPortCalculator&) = delete; ~ShardPortCalculator(); /** * Calculate a possible ephemeral port number, such that the targeted shard is * `port % shard_cnt` and `port` resides within the range [lo, hi). Thread-safe. */ int calc_outgoing_port_num(int shard_cnt, int32_t desired_shard_id) const; private: int local_port_range_lo_, local_port_range_hi_; /* * Map keeps track of used client-side ports. E.g. `port_states_[32000] == true` * means "port 32000 can be bound to local socket". It is NOT guaranteed that this * port will be available, but it gets us fewer unsuccessful connection attempts. */ mutable std::map<int, bool> port_states_; mutable uv_mutex_t mutex_; }; }}} // namespace datastax::internal::core #endif // DATASTAX_INTERNAL_SHARD_PORT_CALCULATOR_HPP
35.15
84
0.757231
jtcarnes
337e6e2c8337686849a847dd6d37ea8db7b1b90e
5,619
cpp
C++
extra/facs/gui/lengthprofile/ProfilePane.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/facs/gui/lengthprofile/ProfilePane.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/facs/gui/lengthprofile/ProfilePane.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
// // license___here #include "ProfilePane.h" #include "ProfileView.h" #include "FacsanaduProject.h" #include "../gates/GateSet.h" #include "MainWindow.h" #include "../resource/ImgResource.h" #include "../data/ProfChannel.h" // package facsanadu.gui.lengthprofile; ProfilePane::ProfilePane(MainWindow* mw) : mw_(mw) { bPrevProf_ = new QPushButton(QIcon(ImgResource::moveLeft()), ""); bNextProf_ = new QPushButton(QIcon(ImgResource::moveRight()), ""); tfID_ = new QLineEdit("0"); cbNormalizeLength_ = new QCheckBox(); cbShowAll_ = new QCheckBox(); laychans_ = new QGridLayout(); //cbShowChannel_ = new QList<QCheckBox*>; //sScaleChannel_ = new QList<QSlider*>; view_ = new ProfileView(mw); //? tfID.setValidator(new QIntValidator(this)); tfID_->setMaximumWidth(100); for(int i=0; i<10; i++) { QCheckBox* cb = new QCheckBox(); //cb.stateChanged.connect(this,"updateViews()"); cb->setChecked(true); cbShowChannel_.push_back(cb); laychans_->addWidget(cb, i, 0); QSlider* s = new QSlider(); s->setOrientation(Qt::Horizontal); s->setMaximum(10000); s->setValue(2000); laychans_->addWidget(s, i, 1); sScaleChannel_.append(s); //?s.sliderMoved.connect(this,"updateViews()"); } QHBoxLayout* blay = new QHBoxLayout(); blay->addWidget(new QLabel(tr("Show all"))); blay->addWidget(cbShowAll_); blay->addWidget(new QLabel(tr("Normalize length"))); blay->addWidget(cbNormalizeLength_); blay->addStretch(); blay->addWidget(new QLabel(tr("Event ID:"))); blay->addWidget(tfID_); blay->addWidget(bPrevProf_); blay->addWidget(bNextProf_); QVBoxLayout* lay = new QVBoxLayout(); lay->addLayout(blay); lay->addWidget(view_); lay->addLayout(laychans_); //tfID_->editingFinished.connect(this,"updateViews()"); //bNextProf.clicked.connect(this,"actionNextProf()"); //bPrevProf.clicked.connect(this,"actionPrevProf()"); //cbNormalizeLength.stateChanged.connect(this,"cbNormalizeLength()"); //cbShowAll.stateChanged.connect(this,"updateViews()"); setLayout(lay); } void ProfilePane::cbNormalizeLength() { if(view_->curchannel()) view_->curchannel()->set_forNormalized( cbNormalizeLength_->isChecked() ); updateViews(); } Gate* ProfilePane::getCurrentGate() { QList<Gate*> gates = mw_->getSelectedGates(); Gate* g; if(gates.isEmpty()) g = mw_->project()->gateset()->getRootGate(); else g = gates.first(); return g; } /* void ProfilePane::actionPrevProf() { int id=getCurrentID(); Dataset ds=getCurrentDataset(); if(ds!=null) { GatingResult gres=mw.project.getGatingResult(ds); IntArray arr=gres.getAcceptedFromGate(getCurrentGate()); for(int i=arr.size()-1;i>=0;i--) if(arr.get(i)<id) { setEventID(arr.get(i)); break; } } } void ProfilePane::actionNextProf() { int id=getCurrentID(); Dataset ds=getCurrentDataset(); if(ds!=null) { GatingResult gres=mw.project.getGatingResult(ds); IntArray arr=gres.getAcceptedFromGate(getCurrentGate()); for(int i=0;i<arr.size();i++) if(arr.get(i)>id) { setEventID(arr.get(i)); break; } } } List<Integer> ProfilePane::getAllFromGate() { Dataset ds=getCurrentDataset(); if(ds!=null) { GatingResult gres=mw.project.getGatingResult(ds); IntArray arr=gres.getAcceptedFromGate(getCurrentGate()); ArrayList<Integer> list=new ArrayList<Integer>(arr.size()); for(int i=0;i<arr.size();i++) list.add(arr.get(i)); return list; } else return new ArrayList<Integer>(); } void ProfilePane::setEventID(int id) { tfID.setText(""+id); updateViews(); } Dataset ProfilePane::getCurrentDataset() { List<Dataset> listds=mw.getSelectedDatasets(); if(!listds.isEmpty()) return listds.get(0); else return null; } int ProfilePane::getCurrentID() { int id=-1; try { id=Integer.parseInt(tfID.text()); } catch (NumberFormatException e) { e.printStackTrace(); } return id; } */ void ProfilePane::updateViews() { /* Dataset ds=getCurrentDataset(); if(ds!=null) { ArrayList<Boolean> showchan=new ArrayList<Boolean>(); ArrayList<Double> scale=new ArrayList<Double>(); for(int i=0;i<ds.getNumLengthProfiles();i++) { showchan.add(cbShowChannel.get(i).isChecked()); double pos=sScaleChannel.get(i).value()/1000.0; scale.add(pos/400000.0); } view.showchan=showchan; view.scale=scale; view.normalizeLength=cbNormalizeLength.isChecked(); if(cbShowAll.isChecked()) { view.setevent(ds, getAllFromGate()); } else { int id=getCurrentID(); view.setevent(ds, id); } } else { view.setevent(null, 0); ds=new Dataset(); } //Update name and visibility of checkboxes for channels for(int i=0;i<cbShowChannel.size();i++) { QCheckBox cb=cbShowChannel.get(i); QSlider s=sScaleChannel.get(i); boolean visible=i<ds.lengthprofsInfo.size(); cb.setVisible(visible); s.setVisible(visible); if(visible) cb.setText(ds.lengthprofsInfo.get(i).name); } */ } QList<int> ProfilePane::getSelChans() { return {}; } /* ArrayList<Integer> ProfilePane::getSelChans() { Dataset ds=getCurrentDataset(); ArrayList<Integer> showchan=new ArrayList<Integer>(); if(ds!=null) for(int i=0;i<ds.getNumLengthProfiles();i++) { if(cbShowChannel.get(i).isChecked()) showchan.add(i); } return showchan; } void ProfilePane::setCurChan(ProfChannel pc) { view.curchannel=pc; view.repaint(); } */ void ProfilePane::setCurChan(ProfChannel* pc) { view_->set_curchannel(pc); view_->repaint(); }
21.203774
77
0.668446
scignscape
3380798e50a5cbdbabe57f552792c922b4ccf40a
1,055
cpp
C++
matrix/src/op/Convolution1DGradOp.cpp
Jarlene/Matrix
7b2e07a46f8d0477243d49c76db575280096e247
[ "Apache-2.0" ]
2
2017-07-22T05:20:57.000Z
2018-07-08T08:48:33.000Z
matrix/src/op/Convolution1DGradOp.cpp
Jarlene/Matrix
7b2e07a46f8d0477243d49c76db575280096e247
[ "Apache-2.0" ]
null
null
null
matrix/src/op/Convolution1DGradOp.cpp
Jarlene/Matrix
7b2e07a46f8d0477243d49c76db575280096e247
[ "Apache-2.0" ]
null
null
null
// // Created by Jarlene on 2017/11/5. // #include "matrix/include/op/Convolution1DGradOp.h" namespace matrix { template<class T, class xpu> Convolution1DGradOp<T, xpu>::Convolution1DGradOp(Parameter &param) { INIT_PARAMS } template<class T, class Context> bool Convolution1DGradOp<T, Context>::Run() { return true; } template<class T, class Context> void Convolution1DGradOp<T, Context>::AsyncRun() { if (Context::mode == RunMode::kCpu) { Run(); } else { if (!RunOnDevice()) { Run(); } } } template<class T, class Context> Convolution1DGradOp<T, Context>::~Convolution1DGradOp() { } template<class T, class Context> bool Convolution1DGradOp<T, Context>::RunOnDevice() { return false; } void Convolution1DGradOpProp::InferShape(std::vector<Shape *> &inShape, Shape *outShape) { } INIT_OPERATOR_PROPERTY_CREATE(Convolution1DGradOpProp, Convolution1DGradOp, true); }
19.90566
94
0.616114
Jarlene
3382cd8b729c454f1780e8f2ebf2b97a206ae1af
458
cpp
C++
Move Zeroes.cpp
durgirajesh/Leetcode
18b11cd90e8a5ce33f4029d5b7edf9502273bc76
[ "MIT" ]
2
2020-06-25T12:46:13.000Z
2021-07-06T06:34:33.000Z
Move Zeroes.cpp
durgirajesh/Leetcode
18b11cd90e8a5ce33f4029d5b7edf9502273bc76
[ "MIT" ]
null
null
null
Move Zeroes.cpp
durgirajesh/Leetcode
18b11cd90e8a5ce33f4029d5b7edf9502273bc76
[ "MIT" ]
null
null
null
class Solution { public: void moveZeroes(vector<int>& nums) { int n=nums.size(); int i=0, j=0; while(j < n){ if(nums[j] == 0){ j++; } else{ nums[i]=nums[j]; i++; j++; } } for(int k=i;k<n;k++){ nums[k]=0; } } };
17.615385
41
0.248908
durgirajesh
338643254d305d8be40e4fdeb983031cef85bbee
44,260
hxx
C++
include/Clothoids/BaseCurve.hxx
MatteoRagni/Clothoids-1
b7fa270e65ba291a67ff3a3612810595fa436d0f
[ "BSD-2-Clause" ]
null
null
null
include/Clothoids/BaseCurve.hxx
MatteoRagni/Clothoids-1
b7fa270e65ba291a67ff3a3612810595fa436d0f
[ "BSD-2-Clause" ]
null
null
null
include/Clothoids/BaseCurve.hxx
MatteoRagni/Clothoids-1
b7fa270e65ba291a67ff3a3612810595fa436d0f
[ "BSD-2-Clause" ]
null
null
null
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * @file BaseCurve.hxx * @author Matteo Ragni (info@ragni.me) * * @copyright Copyright (c) 2022 Matteo Ragni * * 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. * * Based on the work of: * Enrico Bertolazzi http://ebertolazzi.github.io/Clothoids/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #pragma once #include <utility> #include <vector> #include "G2lib.hxx" #include "Constants.hxx" #include "Triangle2D.hxx" namespace G2lib { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /*\ | ____ ____ | | __ ) __ _ ___ ___ / ___| _ _ ____ _____ | | _ \ / _` / __|/ _ \ | | | | | '__\ \ / / _ \ | | |_) | (_| \__ \ __/ |__| |_| | | \ V / __/ | |____/ \__,_|___/\___|\____\__,_|_| \_/ \___| \*/ typedef enum { G2LIB_LINE = 0, G2LIB_POLYLINE, G2LIB_CIRCLE, G2LIB_BIARC, G2LIB_BIARC_LIST, G2LIB_CLOTHOID, G2LIB_CLOTHOID_LIST } CurveType; extern char const * CurveType_name[]; typedef std::pair<real_type, real_type> Ipair; typedef std::vector<Ipair> IntersectList; /*\ | _ _ _ | (_)_ __ | |_ ___ _ __ ___ ___ ___| |_ | | | '_ \| __/ _ \ '__/ __|/ _ \/ __| __| | | | | | | || __/ | \__ \ __/ (__| |_ | |_|_| |_|\__\___|_| |___/\___|\___|\__| \*/ class BaseCurve; //! //! Return `true` if the two curves intersect. //! //! \param[in] C1 first curve //! \param[in] C2 second curve //! bool collision(BaseCurve const & C1, BaseCurve const & C2); //! //! Return `true` the the two curves intersect. //! //! \param[in] C1 first curve //! \param[in] offs_C1 offset of the first curve //! \param[in] C2 second curve //! \param[in] offs_C2 offset of the second curve //! bool collision_ISO(BaseCurve const & C1, real_type offs_C1, BaseCurve const & C2, real_type offs_C2); //! //! Return `true` the the two curves intersect. //! //! \param[in] C1 first curve //! \param[in] offs_C1 offset of the first curve //! \param[in] C2 second curve //! \param[in] offs_C2 offset of the second curve //! inline bool collision_SAE(BaseCurve const & C1, real_type offs_C1, BaseCurve const & C2, real_type offs_C2) { return collision_ISO(C1, -offs_C1, C2, -offs_C2); } //! //! Collect the intersection of the two curve. //! //! \param[in] C1 first curve //! \param[in] C2 second curve //! \param[out] ilist list of the intersection (as parameter on the curves) //! \param[out] swap_s_vals if true store `(s2,s1)` instead of `(s1,s2)` for each //! intersection //! void intersect(BaseCurve const & C1, BaseCurve const & C2, IntersectList & ilist, bool swap_s_vals); //! //! Collect the intersections of the two curve. //! //! \param[in] C1 first curve //! \param[in] offs_C1 offset of the first curve //! \param[in] C2 second curve //! \param[in] offs_C2 offset of the second curve //! \param[out] ilist list of the intersection (as parameter on the curves) //! \param[out] swap_s_vals if true store `(s2,s1)` instead of `(s1,s2)` for each //! intersection //! void intersect_ISO( BaseCurve const & C1, real_type offs_C1, BaseCurve const & C2, real_type offs_C2, IntersectList & ilist, bool swap_s_vals); //! //! Collect the intersections of the two curve. //! //! \param[in] C1 first curve //! \param[in] offs_C1 offset of the first curve //! \param[in] C2 second curve //! \param[in] offs_C2 offset of the second curve //! \param[out] ilist list of the intersection (as parameter on the curves) //! \param[out] swap_s_vals if true store `(s2,s1)` instead of `(s1,s2)` for each //! intersection //! inline void intersect_SAE( BaseCurve const & C1, real_type offs_C1, BaseCurve const & C2, real_type offs_C2, IntersectList & ilist, bool swap_s_vals) { intersect_ISO(C1, -offs_C1, C2, -offs_C2, ilist, swap_s_vals); } //! //! Base classe for all the curve ìn in the library. //! class BaseCurve { // block default constructor BaseCurve(BaseCurve const &) = delete; BaseCurve const & operator=(BaseCurve const &) = delete; protected: CurveType m_type; public: //! //! Initialize the class storing the curve type. //! BaseCurve(CurveType const & type) : m_type(type) {} virtual ~BaseCurve() {} //! //! The name of the curve type //! CurveType type() const { return m_type; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . //! //! The length of the curve //! virtual real_type length() const = 0; //! //! The length of the curve with offset (ISO) //! virtual real_type length_ISO(real_type offs) const = 0; //! //! The length of the curve with offset (SAE) //! real_type length_SAE(real_type offs) const { return this->length_ISO(-offs); } /*\ | _ _ | | |__ | |__ _____ __ | | '_ \| '_ \ / _ \ \/ / | | |_) | |_) | (_) > < | |_.__/|_.__/ \___/_/\_\ \*/ //! //! Compute the bounding box of the curve. //! //! \param[out] xmin left bottom //! \param[out] ymin left bottom //! \param[out] xmax right top //! \param[out] ymax right top //! virtual void bbox(real_type & xmin, real_type & ymin, real_type & xmax, real_type & ymax) const = 0; //! //! Compute the bounding box of the curve with offset (ISO). //! //! \param[in] offs curve offset //! \param[out] xmin left bottom //! \param[out] ymin left bottom //! \param[out] xmax right top //! \param[out] ymax right top //! virtual void bbox_ISO( real_type offs, real_type & xmin, real_type & ymin, real_type & xmax, real_type & ymax) const = 0; //! //! Compute the bounding box of the curve (SAE). //! //! \param[in] offs curve offset //! \param[out] xmin left bottom //! \param[out] ymin left bottom //! \param[out] xmax right top //! \param[out] ymax right top //! void bbox_SAE(real_type offs, real_type & xmin, real_type & ymin, real_type & xmax, real_type & ymax) const { this->bbox_ISO(-offs, xmin, ymin, xmax, ymax); } /*\ | _ _ _____ _ _ | | |__| |_|_ _| _(_)__ _ _ _ __ _| |___ | | '_ \ '_ \| || '_| / _` | ' \/ _` | / -_) | |_.__/_.__/|_||_| |_\__,_|_||_\__, |_\___| | |___/ \*/ //! //! Build a cover with triangles of the curve. //! //! \param[out] tvec list of covering triangles //! \param[out] max_angle maximum angle variation of the curve covered by a triangle //! \param[out] max_size maximum admissible size of the covering tirnagles //! \param[out] icurve index of the covering triangles //! //! \rst //! //! .. image:: ../../images/biarc_cover.jpg //! :width: 80% //! :align: center //! //! \endrst //! virtual void bbTriangles( std::vector<Triangle2D> & tvec, real_type max_angle = Utils::m_pi / 18, real_type max_size = 1e100, int_type icurve = 0) const = 0; //! //! Build a cover with triangles of the curve with offset (ISO). //! //! \param[out] offs curve offset //! \param[out] tvec list of covering triangles //! \param[out] max_angle maximum angle variation of the curve covered by a triangle //! \param[out] max_size maximum admissible size of the covering tirnagles //! \param[out] icurve index of the covering triangles //! virtual void bbTriangles_ISO( real_type offs, std::vector<Triangle2D> & tvec, real_type max_angle = Utils::m_pi / 18, real_type max_size = 1e100, int_type icurve = 0) const = 0; //! //! Build a cover with triangles of the curve with offset (SAE). //! //! \param[out] offs curve offset //! \param[out] tvec list of covering triangles //! \param[out] max_angle maximum angle variation of the arc covered by a triangle //! \param[out] max_size maximum admissible size of the covering tirnagles //! \param[out] icurve index of the covering triangles //! virtual void bbTriangles_SAE( real_type offs, std::vector<Triangle2D> & tvec, real_type max_angle = Utils::m_pi / 18, real_type max_size = 1e100, int_type icurve = 0) const = 0; /*\ | ____ _ _______ _ | | __ ) ___ __ _(_)_ __ / / ____|_ __ __| | | | _ \ / _ \/ _` | | '_ \ / /| _| | '_ \ / _` | | | |_) | __/ (_| | | | | |/ / | |___| | | | (_| | | |____/ \___|\__, |_|_| |_/_/ |_____|_| |_|\__,_| | |___/ \*/ //! //! Initial angle of the curve. //! virtual real_type theta_begin() const { return this->theta(0); } //! //! Final angle of the curve. //! virtual real_type theta_end() const { return this->theta(this->length()); } //! //! Initial curvature. //! virtual real_type kappa_begin() const { return this->kappa(0); } //! //! Final curvature. //! virtual real_type kappa_end() const { return this->kappa(this->length()); } //! //! Initial x-coordinate. //! virtual real_type x_begin() const { return this->X(0); } //! //! Initial y-coordinate. //! virtual real_type y_begin() const { return this->Y(0); } //! //! Final x-coordinate. //! virtual real_type x_end() const { return this->X(this->length()); } //! //! Final y-coordinate. //! virtual real_type y_end() const { return this->Y(this->length()); } //! //! Initial x-coordinate with offset (ISO standard). //! virtual real_type x_begin_ISO(real_type offs) const { return this->X_ISO(0, offs); } //! //! Initial y-coordinate with offset (ISO standard). //! virtual real_type y_begin_ISO(real_type offs) const { return this->Y_ISO(0, offs); } //! //! Final x-coordinate with offset (ISO standard). //! virtual real_type x_end_ISO(real_type offs) const { return this->X_ISO(this->length(), offs); } //! //! Final y-coordinate with offset (ISO standard). //! virtual real_type y_end_ISO(real_type offs) const { return this->Y_ISO(this->length(), offs); } //! //! Initial x-coordinate with offset (SAE standard). //! real_type x_begin_SAE(real_type offs) const { return this->x_begin_ISO(-offs); } //! //! Initial y-coordinate with offset (SAE standard). //! real_type y_begin_SAE(real_type offs) const { return this->y_begin_ISO(-offs); } //! //! Final y-coordinate with offset (SAE standard). //! real_type x_end_SAE(real_type offs) const { return this->x_end_ISO(-offs); } //! //! Final y-coordinate with offset (ISO standard). //! real_type y_end_SAE(real_type offs) const { return this->y_end_ISO(-offs); } //! //! Initial tangent x-coordinate. //! virtual real_type tx_Begin() const { return this->tx(0); } //! //! Initial tangent y-coordinate. //! virtual real_type ty_Begin() const { return this->ty(0); } //! //! Final tangent x-coordinate. //! virtual real_type tx_End() const { return this->tx(this->length()); } //! //! Final tangent y-coordinate. //! virtual real_type ty_End() const { return this->ty(this->length()); } //! //! Intial normal x-coordinate (ISO). //! virtual real_type nx_Begin_ISO() const { return -this->ty(0); } //! //! Intial normal y-coordinate (ISO). //! virtual real_type ny_Begin_ISO() const { return this->tx(0); } //! //! Final normal x-coordinate (ISO). //! virtual real_type nx_End_ISO() const { return -this->ty(this->length()); } //! //! Final normal y-coordinate (ISO). //! virtual real_type ny_End_ISO() const { return this->tx(this->length()); } //! //! Intial normal x-coordinate (SAE). //! real_type nx_Begin_SAE() const { return -nx_Begin_ISO(); } //! //! Intial normal y-coordinate (SAE). //! real_type ny_Begin_SAE() const { return -ny_Begin_ISO(); } //! //! Final normal x-coordinate (SAE). //! real_type nx_End_SAE() const { return -nx_End_ISO(); } //! //! Intial normal y-coordinate (SAE). //! real_type ny_End_SAE() const { return -ny_End_ISO(); } /*\ | _ _ _ | | |_| |__ ___| |_ __ _ | | __| '_ \ / _ \ __/ _` | | | |_| | | | __/ || (_| | | \__|_| |_|\___|\__\__,_| \*/ //! //! Angle at curvilinear coodinate `s`. //! virtual real_type theta(real_type s) const = 0; //! //! Angle derivative (curvature) at curvilinear coodinate `s`. //! virtual real_type theta_D(real_type s) const = 0; //! //! Angle second derivative (devitive of curvature) at curvilinear coodinate `s`. //! virtual real_type theta_DD(real_type s) const = 0; //! //! Angle third derivative at curvilinear coodinate `s`. //! virtual real_type theta_DDD(real_type s) const = 0; /*\ | _ | | | ____ _ _ __ _ __ __ _ | | |/ / _` | '_ \| '_ \ / _` | | | < (_| | |_) | |_) | (_| | | |_|\_\__,_| .__/| .__/ \__,_| | |_| |_| \*/ //! //! Ccurvature at curvilinear coodinate `s`. //! real_type kappa(real_type s) const { return theta_D(s); } //! //! Curvature derivative at curvilinear coodinate `s`. //! real_type kappa_D(real_type s) const { return theta_DD(s); } //! //! Curvature second derivative at curvilinear coodinate `s`. //! real_type kappa_DD(real_type s) const { return theta_DDD(s); } /*\ | _____ _ _ _ | |_ _| __ _ _ __ __| | | \ | | | | | / _` | '_ \ / _` | | \| | | | | | (_| | | | | (_| | | |\ | | |_| \__,_|_| |_|\__,_| |_| \_| \*/ //! //! Tangent x-coordinate at curvilinear coodinate `s`. //! virtual real_type tx(real_type s) const; //! //! Tangent y-coordinate at curvilinear coodinate `s`. //! virtual real_type ty(real_type s) const; //! //! Tangent derivative x-coordinate at curvilinear coodinate `s`. //! virtual real_type tx_D(real_type s) const; //! //! Tangent derivative y-coordinate at curvilinear coodinate `s`. //! virtual real_type ty_D(real_type s) const; //! //! Tangent second derivative x-coordinate at curvilinear coodinate `s`. //! virtual real_type tx_DD(real_type s) const; //! //! Tangent second derivative y-coordinate at curvilinear coodinate `s`. //! virtual real_type ty_DD(real_type s) const; //! //! Tangent third derivative x-coordinate at curvilinear coodinate `s`. //! virtual real_type tx_DDD(real_type s) const; //! //! Tangent third derivative y-coordinate at curvilinear coodinate `s`. //! virtual real_type ty_DDD(real_type s) const; // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . //! //! Normal x-coordinate at curvilinear coodinate `s` (ISO). //! real_type nx_ISO(real_type s) const { return -ty(s); } //! //! Normal derivative x-coordinate at curvilinear coodinate `s` (ISO). //! real_type nx_ISO_D(real_type s) const { return -ty_D(s); } //! //! Normal second derivative x-coordinate at curvilinear coodinate `s` (ISO). //! real_type nx_ISO_DD(real_type s) const { return -ty_DD(s); } //! //! Normal third derivative x-coordinate at curvilinear coodinate `s` (ISO). //! real_type nx_ISO_DDD(real_type s) const { return -ty_DDD(s); } //! //! Normal y-coordinate at curvilinear coodinate `s` (ISO). //! real_type ny_ISO(real_type s) const { return tx(s); } //! //! Normal derivative y-coordinate at curvilinear coodinate `s` (ISO). //! real_type ny_ISO_D(real_type s) const { return tx_D(s); } //! //! Normal second derivative y-coordinate at curvilinear coodinate `s` (ISO). //! real_type ny_ISO_DD(real_type s) const { return tx_DD(s); } //! //! Normal third derivative y-coordinate at curvilinear coodinate `s` (ISO). //! real_type ny_ISO_DDD(real_type s) const { return tx_DDD(s); } //! //! Normal x-coordinate at curvilinear coodinate `s` (SAE). //! real_type nx_SAE(real_type s) const { return ty(s); } //! //! Normal derivative x-coordinate at curvilinear coodinate `s` (SAE). //! real_type nx_SAE_D(real_type s) const { return ty_D(s); } //! //! Normal second derivative x-coordinate at curvilinear coodinate `s` (SAE). //! real_type nx_SAE_DD(real_type s) const { return ty_DD(s); } //! //! Normal third derivative x-coordinate at curvilinear coodinate `s` (SAE). //! real_type nx_SAE_DDD(real_type s) const { return ty_DDD(s); } //! //! Normal y-coordinate at curvilinear coodinate `s` (ISO) //! real_type ny_SAE(real_type s) const { return -tx(s); } //! //! Normal derivative y-coordinate at curvilinear coodinate `s` (SAE). //! real_type ny_SAE_D(real_type s) const { return -tx_D(s); } //! //! Normal second derivative x-coordinate at curvilinear coodinate `s` (SAE). //! real_type ny_SAE_DD(real_type s) const { return -tx_DD(s); } //! //! Normal third derivative y-coordinate at curvilinear coodinate `s` (SAE). //! real_type ny_SAE_DDD(real_type s) const { return -tx_DDD(s); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . //! //! Tangent at curvilinear coodinate `s`. //! virtual void tg(real_type s, real_type & tg_x, real_type & tg_y) const { tg_x = this->tx(s); tg_y = this->ty(s); } //! //! Tangent derivative at curvilinear coodinate `s`. //! virtual void tg_D(real_type s, real_type & tg_x_D, real_type & tg_y_D) const { tg_x_D = this->tx_D(s); tg_y_D = this->ty_D(s); } //! //! Tangent second derivative at curvilinear coodinate `s`. //! virtual void tg_DD(real_type s, real_type & tg_x_DD, real_type & tg_y_DD) const { tg_x_DD = this->tx_DD(s); tg_y_DD = this->ty_DD(s); } //! //! Tangent third derivative at curvilinear coodinate `s`. //! virtual void tg_DDD(real_type s, real_type & tg_x_DDD, real_type & tg_y_DDD) const { tg_x_DDD = this->tx_DDD(s); tg_y_DDD = this->ty_DDD(s); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . //! //! Normal at curvilinear coodinate `s` (ISO). //! void nor_ISO(real_type s, real_type & nx, real_type & ny) const { tg(s, ny, nx); nx = -nx; } //! //! Normal derivative at curvilinear coodinate `s` (ISO). //! void nor_ISO_D(real_type s, real_type & nx_D, real_type & ny_D) const { tg_D(s, ny_D, nx_D); nx_D = -nx_D; } //! //! Normal second derivative at curvilinear coodinate `s` (ISO). //! void nor_ISO_DD(real_type s, real_type & nx_DD, real_type & ny_DD) const { tg_DD(s, ny_DD, nx_DD); nx_DD = -nx_DD; } //! //! Normal third derivative at curvilinear coodinate `s` (ISO). //! void nor_ISO_DDD(real_type s, real_type & nx_DDD, real_type & ny_DDD) const { tg_DDD(s, ny_DDD, nx_DDD); nx_DDD = -nx_DDD; } //! //! Normal at curvilinear coodinate `s` (SAE). //! void nor_SAE(real_type s, real_type & nx, real_type & ny) const { tg(s, ny, nx); ny = -ny; } //! //! Normal derivative at curvilinear coodinate `s` (SAE). //! void nor_SAE_D(real_type s, real_type & nx_D, real_type & ny_D) const { tg_D(s, ny_D, nx_D); ny_D = -ny_D; } //! //! Normal second derivative at curvilinear coodinate `s` (SAE). //! void nor_SAE_DD(real_type s, real_type & nx_DD, real_type & ny_DD) const { tg_DD(s, ny_DD, nx_DD); ny_DD = -ny_DD; } //! //! Normal third at curvilinear coodinate `s` (SAE). //! void nor_SAE_DDD(real_type s, real_type & nx_DDD, real_type & ny_DDD) const { tg_DDD(s, ny_DDD, nx_DDD); ny_DDD = -ny_DDD; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . //! //! Evaluate curve at curvilinear coordinate `s`. //! //! \param[in] s curvilinear coordinate //! \param[out] th angle //! \param[out] k curvature //! \param[out] x x-coordinate //! \param[out] y y-coordinate //! virtual void evaluate(real_type s, real_type & th, real_type & k, real_type & x, real_type & y) const { eval(s, x, y); th = theta(s); k = theta_D(s); } //! //! Evaluate curve with offset at curvilinear coordinate `s` (ISO). //! //! \param[in] s curvilinear coordinate //! \param[in] offs offset //! \param[out] th angle //! \param[out] k curvature //! \param[out] x x-coordinate //! \param[out] y y-coordinate //! virtual void evaluate_ISO( real_type s, real_type offs, real_type & th, real_type & k, real_type & x, real_type & y) const { eval_ISO(s, offs, x, y); th = theta(s); k = theta_D(s); k /= 1 + offs * k; // scale curvature } //! //! Evaluate curve with offset at curvilinear coordinate `s` (SAE). //! //! \param[in] s curvilinear coordinate //! \param[in] offs offset //! \param[out] th angle //! \param[out] k curvature //! \param[out] x x-coordinate //! \param[out] y y-coordinate //! virtual void evaluate_SAE( real_type s, real_type offs, real_type & th, real_type & k, real_type & x, real_type & y) const { eval_SAE(s, offs, x, y); th = theta(s); k = theta_D(s); k /= 1 - offs * k; // scale curvature } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . //! //! x-coordinate at curvilinear coordinate `s`. //! virtual real_type X(real_type s) const = 0; //! //! y-coordinate at curvilinear coordinate `s`. //! virtual real_type Y(real_type s) const = 0; //! //! x-coordinate derivative at curvilinear coordinate `s`. //! virtual real_type X_D(real_type s) const = 0; //! //! y-coordinate derivative at curvilinear coordinate `s`. //! virtual real_type Y_D(real_type s) const = 0; //! //! x-coordinate second derivative at curvilinear coordinate `s`. //! virtual real_type X_DD(real_type s) const = 0; //! //! y-coordinate second derivative at curvilinear coordinate `s`. //! virtual real_type Y_DD(real_type s) const = 0; //! //! x-coordinate third derivative at curvilinear coordinate `s`. //! virtual real_type X_DDD(real_type s) const = 0; //! //! y-coordinate third derivative at curvilinear coordinate `s`. //! virtual real_type Y_DDD(real_type s) const = 0; // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . //! //! x and y-coordinate at curvilinear coordinate `s`. //! virtual void eval(real_type s, real_type & x, real_type & y) const = 0; //! //! x and y-coordinate derivative at curvilinear coordinate `s`. //! virtual void eval_D(real_type s, real_type & x_D, real_type & y_D) const = 0; //! //! x and y-coordinate second derivative at curvilinear coordinate `s`. //! virtual void eval_DD(real_type s, real_type & x_DD, real_type & y_DD) const = 0; //! //! x and y-coordinate third derivative at curvilinear coordinate `s`. //! virtual void eval_DDD(real_type s, real_type & x_DDD, real_type & y_DDD) const = 0; /*\ | __ __ _ | ___ / _|/ _|___ ___| |_ | / _ \| |_| |_/ __|/ _ \ __| | | (_) | _| _\__ \ __/ |_ | \___/|_| |_| |___/\___|\__| \*/ //! //! x-coordinate at curvilinear coordinate `s` with offset `offs` (ISO). //! virtual real_type X_ISO(real_type s, real_type offs) const; //! //! y-coordinate at curvilinear coordinate `s` with offset `offs` (ISO). //! virtual real_type Y_ISO(real_type s, real_type offs) const; //! //! x-coordinate derivative at curvilinear coordinate `s` with offset `offs` (ISO). //! virtual real_type X_ISO_D(real_type s, real_type offs) const; //! //! y-coordinate derivative at curvilinear coordinate `s` with offset `offs` (ISO). //! virtual real_type Y_ISO_D(real_type s, real_type offs) const; //! //! x-coordinate second derivative at curvilinear coordinate `s` with offset `offs` (ISO). //! virtual real_type X_ISO_DD(real_type s, real_type offs) const; //! //! y-coordinate second derivative at curvilinear coordinate `s` with offset `offs` (ISO). //! virtual real_type Y_ISO_DD(real_type s, real_type offs) const; //! //! x-coordinate third derivative at curvilinear coordinate `s` with offset `offs` (ISO). //! virtual real_type X_ISO_DDD(real_type s, real_type offs) const; //! //! y-coordinate third derivative at curvilinear coordinate `s` with offset `offs` (ISO). //! virtual real_type Y_ISO_DDD(real_type s, real_type offs) const; //! //! x-coordinate at curvilinear coordinate `s` with offset `offs` (SAE). //! real_type X_SAE(real_type s, real_type offs) const { return this->X_ISO(s, -offs); } //! //! y-coordinate at curvilinear coordinate `s` with offset `offs` (SAE). //! real_type Y_SAE(real_type s, real_type offs) const { return this->Y_ISO(s, -offs); } //! //! x-coordinate derivative at curvilinear coordinate `s` with offset `offs` (SAE). //! real_type X_SAE_D(real_type s, real_type offs) const { return this->X_ISO_D(s, -offs); } //! //! y-coordinate derivative at curvilinear coordinate `s` with offset `offs` (SAE). //! real_type Y_SAE_D(real_type s, real_type offs) const { return this->Y_ISO_D(s, -offs); } //! //! x-coordinate second derivative at curvilinear coordinate `s` with offset `offs` (SAE). //! real_type X_SAE_DD(real_type s, real_type offs) const { return this->X_ISO_DD(s, -offs); } //! //! y-coordinate second derivative at curvilinear coordinate `s` with offset `offs` (SAE). //! real_type Y_SAE_DD(real_type s, real_type offs) const { return this->Y_ISO_DD(s, -offs); } //! //! x-coordinate third derivative at curvilinear coordinate `s` with offset `offs` (SAE). //! real_type X_SAE_DDD(real_type s, real_type offs) const { return this->X_ISO_DDD(s, -offs); } //! //! y-coordinate third derivative at curvilinear coordinate `s` with offset `offs` (SAE). //! real_type Y_SAE_DDD(real_type s, real_type offs) const { return this->Y_ISO_DDD(s, -offs); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . //! //! Compute curve at position `s` with offset `offs` (ISO). //! //! \param[in] s parameter on the curve //! \param[in] offs offset of the curve //! \param[out] x coordinate //! \param[out] y coordinate //! virtual void eval_ISO(real_type s, real_type offs, real_type & x, real_type & y) const; //! //! Compute curve at position `s` with offset `offs` (SAE). //! //! \param[in] s parameter on the curve //! \param[in] offs offset of the curve //! \param[out] x coordinate //! \param[out] y coordinate //! void eval_SAE(real_type s, real_type offs, real_type & x, real_type & y) const { this->eval_ISO(s, -offs, x, y); } //! //! Compute derivative curve at position `s` with offset `offs` (ISO). //! //! \param[in] s parameter on the curve //! \param[in] offs offset of the curve //! \param[out] x_D x-coordinate //! \param[out] y_D y-coordinate //! virtual void eval_ISO_D(real_type s, real_type offs, real_type & x_D, real_type & y_D) const; //! //! Compute derivative curve at position `s` with offset `offs` (SAE). //! //! \param[in] s parameter on the curve //! \param[in] offs offset of the curve //! \param[out] x_D x-coordinate first derivative //! \param[out] y_D y-coordinate first derivative //! void eval_SAE_D(real_type s, real_type offs, real_type & x_D, real_type & y_D) const { this->eval_ISO_D(s, -offs, x_D, y_D); } //! //! Compute second derivative curve at position `s` with offset `offs` (ISO). //! //! \param[in] s parameter on the curve //! \param[in] offs offset of the curve //! \param[out] x_DD x-coordinate second derivative //! \param[out] y_DD y-coordinate second derivative //! virtual void eval_ISO_DD(real_type s, real_type offs, real_type & x_DD, real_type & y_DD) const; //! //! Compute second derivative curve at position `s` with offset `offs` (SAE). //! //! \param[in] s parameter on the curve //! \param[in] offs offset of the curve //! \param[out] x_DD x-coordinate second derivative //! \param[out] y_DD y-coordinate second derivative //! void eval_SAE_DD(real_type s, real_type offs, real_type & x_DD, real_type & y_DD) const { this->eval_ISO_DD(s, -offs, x_DD, y_DD); } //! //! Compute third derivative curve at position `s` with offset `offs` (ISO). //! //! \param[in] s parameter on the curve //! \param[in] offs offset of the curve //! \param[out] x_DDD x-coordinate third derivative //! \param[out] y_DDD y-coordinate third derivative //! virtual void eval_ISO_DDD(real_type s, real_type offs, real_type & x_DDD, real_type & y_DDD) const; //! //! Compute third derivative curve at position `s` with offset `offs` (SAE). //! //! \param[in] s parameter on the curve //! \param[in] offs offset of the curve //! \param[out] x_DDD x-coordinate third derivative //! \param[out] y_DDD y-coordinate third derivative //! void eval_SAE_DDD(real_type s, real_type offs, real_type & x_DDD, real_type & y_DDD) const { this->eval_ISO_DDD(s, -offs, x_DDD, y_DDD); } /*\ | _ __ | | |_ _ __ __ _ _ __ ___ / _| ___ _ __ _ __ ___ | | __| '__/ _` | '_ \/ __| |_ / _ \| '__| '_ ` _ \ | | |_| | | (_| | | | \__ \ _| (_) | | | | | | | | | \__|_| \__,_|_| |_|___/_| \___/|_| |_| |_| |_| \*/ //! translate curve by \f$ (t_x,t_y) \f$ virtual void translate(real_type tx, real_type ty) = 0; //! //! Rotate curve by angle \f$ theta \f$ centered at point \f$ (c_x,c_y)\f$. //! //! \param[in] angle angle \f$ theta \f$ //! \param[in] cx \f$ c_x\f$ //! \param[in] cy \f$ c_y\f$ //! virtual void rotate(real_type angle, real_type cx, real_type cy) = 0; //! //! Scale curve by factor `sc`. //! virtual void scale(real_type sc) = 0; //! //! Reverse curve parameterization. //! virtual void reverse() = 0; //! //! Translate curve so that origin will be (`newx0`, `newy0`). //! virtual void change_origin(real_type newx0, real_type newy0) = 0; //! //! Cut curve at parametrix coordinate `s_begin` and `s_end`. //! virtual void trim(real_type s_begin, real_type s_end) = 0; /*\ | _ _ _ | (_)_ __ | |_ ___ _ __ ___ ___ ___| |_ | | | '_ \| __/ _ \ '__/ __|/ _ \/ __| __| | | | | | | || __/ | \__ \ __/ (__| |_ | |_|_| |_|\__\___|_| |___/\___|\___|\__| \*/ //! //! Check collision with another curve. //! bool collision(BaseCurve const & C) const { return G2lib::collision(*this, C); } //! //! Check collision with another curve with offset (ISO). //! //! \param[in] offs curve offset //! \param[in] C second curve to check collision //! \param[in] offs_C curve offset of the second curve //! \return true if collision is detected //! bool collision_ISO(real_type offs, BaseCurve const & C, real_type offs_C) const { return G2lib::collision_ISO(*this, offs, C, offs_C); } //! //! Check collision with another curve with offset (SAE). //! //! \param[in] offs curve offset //! \param[in] C second curve to check collision //! \param[in] offs_C curve offset of the second curve //! \return true if collision is detected //! bool collision_SAE(real_type offs, BaseCurve const & C, real_type offs_C) const { return G2lib::collision_SAE(*this, offs, C, offs_C); } //! //! Intersect the curve with another curve. //! //! \param[in] C second curve intersect //! \param[out] ilist list of the intersection (as parameter on the curves) //! \param[in] swap_s_vals if true store `(s2,s1)` instead of `(s1,s2)` for each //! intersection //! void intersect(BaseCurve const & C, IntersectList & ilist, bool swap_s_vals) const { G2lib::intersect(*this, C, ilist, swap_s_vals); } //! //! Intersect the curve with another curve with offset (ISO) //! //! \param[in] offs offset first curve //! \param[in] C second curve intersect //! \param[in] offs_C offset second curve //! \param[out] ilist list of the intersection (as parameter on the curves) //! \param[in] swap_s_vals if true store `(s2,s1)` instead of `(s1,s2)` for each //! intersection //! void intersect_ISO( real_type offs, BaseCurve const & C, real_type offs_C, IntersectList & ilist, bool swap_s_vals) const { G2lib::intersect_ISO(*this, offs, C, offs_C, ilist, swap_s_vals); } //! //! Intersect the curve with another curve with offset (SAE). //! //! \param[in] offs offset first curve //! \param[in] C second curve intersect //! \param[in] offs_C offset second curve //! \param[out] ilist list of the intersection (as parameter on the curves) //! \param[in] swap_s_vals if true store `(s2,s1)` instead of `(s1,s2)` for each //! intersection //! void intersect_SAE( real_type offs, BaseCurve const & C, real_type offs_C, IntersectList & ilist, bool swap_s_vals) const { G2lib::intersect_SAE(*this, offs, C, offs_C, ilist, swap_s_vals); } /*\ | _ _ _ | __| (_)___| |_ __ _ _ __ ___ ___ | / _` | / __| __/ _` | '_ \ / __/ _ \ | | (_| | \__ \ || (_| | | | | (_| __/ | \__,_|_|___/\__\__,_|_| |_|\___\___| \*/ //! //! Given a point find closest point on the curve. //! //! \param qx x-coordinate of the point //! \param qy y-coordinate of the point //! \param x x-coordinate of the projected point on the curve //! \param y y-coordinate of the projected point on the curve //! \param s parameter on the curve of the projection //! \param t curvilinear coordinate of the point x,y (if orthogonal projection) //! \param dst distance point projected point //! \return 1 = point is projected orthogonal //! 0 = more than one projection (first returned) //! -1 = minimum point is not othogonal projection to curve //! virtual int_type closest_point_ISO( real_type qx, real_type qy, real_type & x, real_type & y, real_type & s, real_type & t, real_type & dst) const = 0; //! //! Given a point find closest point on the curve. //! //! \param qx x-coordinate of the point //! \param qy y-coordinate of the point //! \param x x-coordinate of the projected point on the curve //! \param y y-coordinate of the projected point on the curve //! \param s parameter on the curve of the projection //! \param t curvilinear coordinate of the point x,y (if orthogonal projection) //! \param dst distance point projected point //! \return 1 = point is projected orthogonal //! 0 = more than one projection (first returned) //! -1 = minimum point is not othogonal projection to curve //! int_type closest_point_SAE( real_type qx, real_type qy, real_type & x, real_type & y, real_type & s, real_type & t, real_type & dst) const { int_type res = this->closest_point_ISO(qx, qy, x, y, s, t, dst); t = -t; return res; } //! //! Given a point find closest point on the curve. //! //! \param qx x-coordinate of the point //! \param qy y-coordinate of the point //! \param offs offset of the curve //! \param x x-coordinate of the projected point on the curve //! \param y y-coordinate of the projected point on the curve //! \param s parameter on the curve of the projection //! \param t curvilinear coordinate of the point x,y (if orthogonal projection) //! \param dst distance point projected point //! \return 1 = point is projected orthogonal //! 0 = more than one projection (first returned) //! -1 = minimum point is not othogonal projection to curve //! virtual int_type // true if projection is unique and orthogonal closest_point_ISO( real_type qx, real_type qy, real_type offs, real_type & x, real_type & y, real_type & s, real_type & t, real_type & dst) const = 0; //! //! Given a point find closest point on the curve. //! //! \param qx x-coordinate of the point //! \param qy y-coordinate of the point //! \param offs offset of the curve //! \param x x-coordinate of the projected point on the curve //! \param y y-coordinate of the projected point on the curve //! \param s parameter on the curve of the projection //! \param t curvilinear coordinate of the point x,y (if orthogonal projection) //! \param dst distance point projected point //! \return 1 = point is projected orthogonal //! 0 = more than one projection (first returned) //! -1 = minimum point is not othogonal projection to curve //! int_type closest_point_SAE( real_type qx, real_type qy, real_type offs, real_type & x, real_type & y, real_type & s, real_type & t, real_type & dst) const { int_type res = this->closest_point_ISO(qx, qy, -offs, x, y, s, t, dst); t = -t; return res; } //! //! Compute the distance between a point \f$ q=(q_x,q_y) \f$ and the curve. //! //! \param[in] qx component \f$ q_x \f$ //! \param[in] qy component \f$ q_y \f$ //! \return the computed distance //! virtual real_type distance(real_type qx, real_type qy) const { real_type x, y, s, t, dst; closest_point_ISO(qx, qy, x, y, s, t, dst); return dst; } //! //! Compute the distance between a point \f$ q=(q_x,q_y) \f$ and the curve with offset (ISO). //! //! \param[in] qx component \f$ q_x \f$ //! \param[in] qy component \f$ q_y \f$ //! \param[in] offs offset of the curve //! \return the computed distance //! real_type distance_ISO(real_type qx, real_type qy, real_type offs) const { real_type x, y, s, t, dst; this->closest_point_ISO(qx, qy, offs, x, y, s, t, dst); return dst; } //! //! Compute the distance between a point \f$ q=(q_x,q_y) \f$ and the curve with offset (SAE). //! //! \param[in] qx component \f$ q_x \f$ //! \param[in] qy component \f$ q_y \f$ //! \param[in] offs offset of the curve //! \return the computed distance //! real_type distance_SAE(real_type qx, real_type qy, real_type offs) const { real_type x, y, s, t, dst; this->closest_point_SAE(qx, qy, offs, x, y, s, t, dst); return dst; } /*\ | __ _ _ ____ _____ | / _(_)_ __ __| / ___|_ _| | | |_| | '_ \ / _` \___ \ | | | | _| | | | | (_| |___) || | | |_| |_|_| |_|\__,_|____/ |_| \*/ //! //! Find the curvilinear coordinate of point \f$ P=(x,y) \f$ //! respect to the curve (ISO), i.e. //! //! \f[ //! P = C(s)+N(s)t //! \f] //! //! where \f$ C(s) \f$ is the curve position respect to the curvilinear coordinates //! and \f$ C(s) \f$ is the normal at the point \f$ C(s) \f$. //! //! \param[in] x component \f$ x \f$ //! \param[in] y component \f$ y \f$ //! \param[out] s curvilinear coordinate //! \param[out] t offset respect to the curve of \f$ (x,y) \f$ //! \return true if the coordinate are found //! bool findST_ISO(real_type x, real_type y, real_type & s, real_type & t) const { real_type X, Y, dst; int_type icode = this->closest_point_ISO(x, y, X, Y, s, t, dst); return icode >= 0; } //! //! Find the curvilinear coordinate of point \f$ (x,y) \f$ //! respect to the curve (SAE), i.e. //! //! \f[ //! P = C(s)+N(s)t //! \f] //! //! where \f$ C(s) \f$ is the curve position respect to the curvilinear coordinates //! and \f$ C(s) \f$ is the normal at the point \f$ C(s) \f$. //! //! \param[in] x component \f$ x \f$ //! \param[in] y component \f$ y \f$ //! \param[out] s curvilinear coordinate //! \param[out] t offset respect to the curve of \f$ (x,y) \f$ //! \return true if the coordinate are found //! bool findST_SAE(real_type x, real_type y, real_type & s, real_type & t) const { real_type X, Y, dst; int_type icode = this->closest_point_SAE(x, y, X, Y, s, t, dst); return icode >= 0; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //! //! Pretty print of the curve data. //! virtual void info(ostream_type & stream) const = 0; }; } // namespace G2lib /// /// eof: BaseCurve.hh ///
32.760918
120
0.561975
MatteoRagni
338775da5154d852759b7f2256d7ceebabd14b54
2,611
ipp
C++
ThirdParty/oglplus-develop/implement/eglplus/enums/renderable_type_bit_def.ipp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
24
2015-01-31T15:30:49.000Z
2022-01-29T08:36:42.000Z
ThirdParty/oglplus-develop/implement/eglplus/enums/renderable_type_bit_def.ipp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
4
2015-08-21T02:29:15.000Z
2020-05-02T13:50:36.000Z
ThirdParty/oglplus-develop/implement/eglplus/enums/renderable_type_bit_def.ipp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
9
2015-06-08T22:04:15.000Z
2021-08-16T03:52:11.000Z
/* * .file eglplus/enums/renderable_type_bit_def.ipp * * Automatically generated header file. DO NOT modify manually, * edit 'source/enums/eglplus/renderable_type_bit.txt' instead. * * Copyright 2010-2014 Matus Chochlik. 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) */ #ifdef EGLPLUS_LIST_NEEDS_COMMA # undef EGLPLUS_LIST_NEEDS_COMMA #endif #if defined EGL_OPENGL_BIT # if EGLPLUS_LIST_NEEDS_COMMA EGLPLUS_ENUM_CLASS_COMMA # endif # if defined OpenGL # pragma push_macro("OpenGL") # undef OpenGL EGLPLUS_ENUM_CLASS_VALUE(OpenGL, EGL_OPENGL_BIT) # pragma pop_macro("OpenGL") # else EGLPLUS_ENUM_CLASS_VALUE(OpenGL, EGL_OPENGL_BIT) # endif # ifndef EGLPLUS_LIST_NEEDS_COMMA # define EGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined EGL_OPENGL_ES_BIT # if EGLPLUS_LIST_NEEDS_COMMA EGLPLUS_ENUM_CLASS_COMMA # endif # if defined OpenGL_ES # pragma push_macro("OpenGL_ES") # undef OpenGL_ES EGLPLUS_ENUM_CLASS_VALUE(OpenGL_ES, EGL_OPENGL_ES_BIT) # pragma pop_macro("OpenGL_ES") # else EGLPLUS_ENUM_CLASS_VALUE(OpenGL_ES, EGL_OPENGL_ES_BIT) # endif # ifndef EGLPLUS_LIST_NEEDS_COMMA # define EGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined EGL_OPENGL_ES2_BIT # if EGLPLUS_LIST_NEEDS_COMMA EGLPLUS_ENUM_CLASS_COMMA # endif # if defined OpenGL_ES2 # pragma push_macro("OpenGL_ES2") # undef OpenGL_ES2 EGLPLUS_ENUM_CLASS_VALUE(OpenGL_ES2, EGL_OPENGL_ES2_BIT) # pragma pop_macro("OpenGL_ES2") # else EGLPLUS_ENUM_CLASS_VALUE(OpenGL_ES2, EGL_OPENGL_ES2_BIT) # endif # ifndef EGLPLUS_LIST_NEEDS_COMMA # define EGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined EGL_OPENGL_ES3_BIT # if EGLPLUS_LIST_NEEDS_COMMA EGLPLUS_ENUM_CLASS_COMMA # endif # if defined OpenGL_ES3 # pragma push_macro("OpenGL_ES3") # undef OpenGL_ES3 EGLPLUS_ENUM_CLASS_VALUE(OpenGL_ES3, EGL_OPENGL_ES3_BIT) # pragma pop_macro("OpenGL_ES3") # else EGLPLUS_ENUM_CLASS_VALUE(OpenGL_ES3, EGL_OPENGL_ES3_BIT) # endif # ifndef EGLPLUS_LIST_NEEDS_COMMA # define EGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined EGL_OPENVG_BIT # if EGLPLUS_LIST_NEEDS_COMMA EGLPLUS_ENUM_CLASS_COMMA # endif # if defined OpenVG # pragma push_macro("OpenVG") # undef OpenVG EGLPLUS_ENUM_CLASS_VALUE(OpenVG, EGL_OPENVG_BIT) # pragma pop_macro("OpenVG") # else EGLPLUS_ENUM_CLASS_VALUE(OpenVG, EGL_OPENVG_BIT) # endif # ifndef EGLPLUS_LIST_NEEDS_COMMA # define EGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #ifdef EGLPLUS_LIST_NEEDS_COMMA # undef EGLPLUS_LIST_NEEDS_COMMA #endif
26.11
68
0.801226
vif
3389ba5c097cd3304e8c34983a2adaea0416e7c9
5,905
cpp
C++
dft.cpp
mtctr/ufrn-pdi
55c2de9d6ad574d50d05b864b85acf253c4048cf
[ "MIT" ]
null
null
null
dft.cpp
mtctr/ufrn-pdi
55c2de9d6ad574d50d05b864b85acf253c4048cf
[ "MIT" ]
null
null
null
dft.cpp
mtctr/ufrn-pdi
55c2de9d6ad574d50d05b864b85acf253c4048cf
[ "MIT" ]
null
null
null
#include <iostream> #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> #define RADIUS 20 using namespace cv; using namespace std; // troca os quadrantes da imagem da DFT void deslocaDFT(Mat& image ){ Mat tmp, A, B, C, D; // se a imagem tiver tamanho impar, recorta a regiao para // evitar cópias de tamanho desigual image = image(Rect(0, 0, image.cols & -2, image.rows & -2)); int cx = image.cols/2; int cy = image.rows/2; // reorganiza os quadrantes da transformada // A B -> D C // C D B A A = image(Rect(0, 0, cx, cy)); B = image(Rect(cx, 0, cx, cy)); C = image(Rect(0, cy, cx, cy)); D = image(Rect(cx, cy, cx, cy)); // A <-> D A.copyTo(tmp); D.copyTo(A); tmp.copyTo(D); // C <-> B C.copyTo(tmp); B.copyTo(C); tmp.copyTo(B); } int main(int argc , char** argv){ VideoCapture cap; Mat imaginaryInput, complexImage, multsp; Mat padded, filter, mag; Mat image, imagegray, tmp; Mat_<float> realInput, zeros; vector<Mat> planos; //parâmetros do filtro homomórfico float yl = 1.0, yh = 7.0; float d, d0 = 10.0, c = 1.0; // habilita/desabilita ruido int noise=0; // frequencia do ruido int freq=10; // ganho inicial do ruido float gain=1; // valor do ruido float mean; // guarda tecla capturada char key; // valores ideais dos tamanhos da imagem // para calculo da DFT int dft_M, dft_N; // abre a câmera default cap.open(0); if(!cap.isOpened()) return -1; // captura uma imagem para recuperar as // informacoes de gravação cap >> image; // identifica os tamanhos otimos para // calculo do FFT dft_M = getOptimalDFTSize(image.rows); dft_N = getOptimalDFTSize(image.cols); // realiza o padding da imagem copyMakeBorder(image, padded, 0, dft_M - image.rows, 0, dft_N - image.cols, BORDER_CONSTANT, Scalar::all(0)); // parte imaginaria da matriz complexa (preenchida com zeros) zeros = Mat_<float>::zeros(padded.size()); // prepara a matriz complexa para ser preenchida complexImage = Mat(padded.size(), CV_32FC2, Scalar(0)); // a função de transferencia (filtro frequencial) deve ter o // mesmo tamanho e tipo da matriz complexa filter = complexImage.clone(); // cria uma matriz temporária para criar as componentes real // e imaginaria do filtro homomórfico tmp = Mat(dft_M, dft_N, CV_32F); //filtro Homomórfico for(int i = 0; i<dft_M; i++){ for(int j = 0; j<dft_N; j++){ d = sqrt(pow(i - (dft_M/2),2) + pow(j - (dft_N/2),2)); tmp.at<float>(i,j)=(yh - yl)*(1-exp(-c*(pow(d,2)/pow(d0,2))))+yl; } } // cria a matriz com as componentes do filtro e junta // ambas em uma matriz multicanal complexa Mat comps[]= {tmp, tmp}; merge(comps, 2, filter); for(;;){ cap >> image; cvtColor(image, imagegray, CV_BGR2GRAY); imshow("original", imagegray); // realiza o padding da imagem copyMakeBorder(imagegray, padded, 0, dft_M - image.rows, 0, dft_N - image.cols, BORDER_CONSTANT, Scalar::all(0)); // limpa o array de matrizes que vao compor a // imagem complexa planos.clear(); // cria a compoente real realInput = Mat_<float>(padded); // insere as duas componentes no array de matrizes planos.push_back(realInput); planos.push_back(zeros); // combina o array de matrizes em uma unica // componente complexa merge(planos, complexImage); //log para realizar a dft for(int i = 0; i< dft_M; i++){ for(int j = 0; j< dft_N; j++){ complexImage.at<char>(i,j) = log(complexImage.at<char>(i,j)+1); } } // calcula o dft dft(complexImage, complexImage); // realiza a troca de quadrantes deslocaDFT(complexImage); // aplica o filtro frequencial mulSpectrums(complexImage,filter,complexImage,0); // limpa o array de planos planos.clear(); // separa as partes real e imaginaria para modifica-las split(complexImage, planos); // usa o valor medio do espectro para dosar o ruido mean = abs(planos[0].at<float> (dft_M/2,dft_N/2)); // insere ruido coerente, se habilitado if(noise){ // F(u,v) recebe ganho proporcional a F(0,0) planos[0].at<float>(dft_M/2 +freq, dft_N/2 +freq) += gain*mean; planos[1].at<float>(dft_M/2 +freq, dft_N/2 +freq) += gain*mean; // F*(-u,-v) = F(u,v) planos[0].at<float>(dft_M/2 -freq, dft_N/2 -freq) = planos[0].at<float>(dft_M/2 +freq, dft_N/2 +freq); planos[1].at<float>(dft_M/2 -freq, dft_N/2 -freq) = -planos[1].at<float>(dft_M/2 +freq, dft_N/2 +freq); } // recompoe os planos em uma unica matriz complexa merge(planos, complexImage); // troca novamente os quadrantes deslocaDFT(complexImage); cout << complexImage.size().height << endl; // calcula a DFT inversa idft(complexImage, complexImage); // limpa o array de planos planos.clear(); // separa as partes real e imaginaria da // imagem filtrada split(complexImage, planos); // normaliza a parte real para exibicao normalize(planos[0], planos[0], 0, 1, CV_MINMAX); imshow("filtrada", planos[0]); key = (char) waitKey(10); if( key == 27 ) break; // esc pressed! switch(key){ // aumenta a frequencia do ruido case 'q': freq=freq+1; if(freq > dft_M/2-1) freq = dft_M/2-1; break; // diminui a frequencia do ruido case 'a': freq=freq-1; if(freq < 1) freq = 1; break; // amplifica o ruido case 'x': gain += 0.1; break; // atenua o ruido case 'z': gain -= 0.1; if(gain < 0) gain=0; break; // insere/remove ruido case 'e': noise=!noise; break; } } return 0; }
25.343348
71
0.605588
mtctr
338d6d7907b07ef9a6e4398077b27ee2238a7d6d
3,838
cpp
C++
packages/arb-avm-cpp/avm_values/src/codepoint.cpp
tahmed4/arbitrum
423adb4a21935b4470a68d0d9b073d7da3e82a7e
[ "Apache-2.0" ]
1
2022-03-26T05:16:22.000Z
2022-03-26T05:16:22.000Z
packages/arb-avm-cpp/avm_values/src/codepoint.cpp
tahmed4/arbitrum
423adb4a21935b4470a68d0d9b073d7da3e82a7e
[ "Apache-2.0" ]
4
2022-02-18T21:35:24.000Z
2022-03-31T07:15:09.000Z
packages/arb-avm-cpp/avm_values/src/codepoint.cpp
tahmed4/arbitrum
423adb4a21935b4470a68d0d9b073d7da3e82a7e
[ "Apache-2.0" ]
1
2022-02-24T09:01:44.000Z
2022-02-24T09:01:44.000Z
/* * Copyright 2019-2020, Offchain Labs, 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 <avm_values/codepoint.hpp> #include <avm_values/tuple.hpp> #include <avm_values/value.hpp> #include <ethash/keccak.hpp> #include <iostream> Operation::Operation(OpCode opcode_, Value immediate_) : opcode(opcode_), immediate(std::make_unique<Value>(std::move(immediate_))) {} void Operation::marshalForProof(std::vector<unsigned char>& buf, size_t marshal_level, const Code& code) const { if (immediate) { buf.push_back(1); buf.push_back(static_cast<uint8_t>(opcode)); ::marshalForProof(*immediate, marshal_level, buf, code); } else { buf.push_back(0); buf.push_back(static_cast<uint8_t>(opcode)); } } bool operator==(const Operation& val1, const Operation& val2) { if (val1.opcode != val2.opcode) { return false; } if (!val1.immediate && !val2.immediate) { return true; } if (!val1.immediate || !val2.immediate) { return false; } return values_equal(*val1.immediate, *val2.immediate); } bool operator!=(const Operation& val1, const Operation& val2) { return !(val1 == val2); } bool operator==(const CodePoint& val1, const CodePoint& val2) { if (hash(val1) != hash(val2)) { return false; } else { return true; } } uint256_t hash(const CodePoint& cp) { if (cp.op.immediate) { std::array<unsigned char, 66> valData{}; valData[0] = CODEPT; valData[1] = static_cast<unsigned char>(cp.op.opcode); auto immHash = hash_value(*cp.op.immediate); auto it = valData.begin() + 2; it = to_big_endian(immHash, it); to_big_endian(cp.nextHash, it); auto hash_val = ethash::keccak256(valData.data(), valData.size()); return intx::be::load<uint256_t>(hash_val); } else { std::array<unsigned char, 34> valData{}; valData[0] = CODEPT; valData[1] = static_cast<unsigned char>(cp.op.opcode); to_big_endian(cp.nextHash, valData.begin() + 2); auto hash_val = ethash::keccak256(valData.data(), valData.size()); return intx::be::load<uint256_t>(hash_val); } } std::ostream& operator<<(std::ostream& os, const Operation& val) { auto opcode_name = [&]() -> std::string { auto it = InstructionNames.find(val.opcode); if (it != InstructionNames.end()) { return it->second; } else { return "InvalidOpcode"; } }(); if (val.immediate) { os << "Immediate(" << opcode_name << ", " << *val.immediate << ")"; } else { os << "Basic(" << opcode_name << ")"; } return os; } std::ostream& operator<<(std::ostream& os, const CodePoint& val) { os << "CodePoint(" << val.op << ", " << intx::to_string(val.nextHash, 16) << ")"; return os; } const Operation& getErrOperation() { Operation static errop(static_cast<OpCode>(0)); return errop; } const CodePoint& getErrCodePoint() { CodePoint static errcp(Operation{static_cast<OpCode>(0)}, 0); return errcp; } const uint256_t& getErrCodePointHash() { uint256_t static errpc_hash = hash(getErrCodePoint()); return errpc_hash; }
30.220472
77
0.621939
tahmed4
338ffde3f5b7f4117086baac1e5bf9b996ba0bf5
194,267
cpp
C++
src/locale.cpp
JacobW92/libcxx
19cd3fd00f0a21023a32da67f134b076ad0c48fe
[ "MIT" ]
6
2019-06-29T07:45:50.000Z
2021-07-10T20:19:18.000Z
system/lib/libcxx/locale.cpp
binji/emscripten
7d09ea2eeb1fa424c1c5d96a7ab130f6a7de4e69
[ "MIT" ]
2
2019-09-29T00:17:39.000Z
2019-11-05T01:47:03.000Z
system/lib/libcxx/locale.cpp
binji/emscripten
7d09ea2eeb1fa424c1c5d96a7ab130f6a7de4e69
[ "MIT" ]
4
2019-08-12T16:08:47.000Z
2022-01-17T00:08:59.000Z
//===------------------------- locale.cpp ---------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // On Solaris, we need to define something to make the C99 parts of localeconv // visible. #ifdef __sun__ #define _LCONV_C99 #endif #include "string" #include "locale" #include "codecvt" #include "vector" #include "algorithm" #include "typeinfo" #ifndef _LIBCPP_NO_EXCEPTIONS # include "type_traits" #endif #include "clocale" #include "cstring" #if defined(_LIBCPP_MSVCRT) #define _CTYPE_DISABLE_MACROS #endif #include "cwctype" #include "__sso_allocator" #if defined(_LIBCPP_MSVCRT) || defined(__MINGW32__) #include "support/win32/locale_win32.h" #elif !defined(__BIONIC__) #include <langinfo.h> #endif #include <stdlib.h> #include <stdio.h> // On Linux, wint_t and wchar_t have different signed-ness, and this causes // lots of noise in the build log, but no bugs that I know of. #if defined(__clang__) #pragma clang diagnostic ignored "-Wsign-conversion" #endif _LIBCPP_BEGIN_NAMESPACE_STD #ifdef __cloc_defined locale_t __cloc() { // In theory this could create a race condition. In practice // the race condition is non-fatal since it will just create // a little resource leak. Better approach would be appreciated. static locale_t result = newlocale(LC_ALL_MASK, "C", 0); return result; } #endif // __cloc_defined namespace { struct release { void operator()(locale::facet* p) {p->__release_shared();} }; template <class T, class A0> inline T& make(A0 a0) { static typename aligned_storage<sizeof(T)>::type buf; ::new (&buf) T(a0); return *reinterpret_cast<T*>(&buf); } template <class T, class A0, class A1> inline T& make(A0 a0, A1 a1) { static typename aligned_storage<sizeof(T)>::type buf; ::new (&buf) T(a0, a1); return *reinterpret_cast<T*>(&buf); } template <class T, class A0, class A1, class A2> inline T& make(A0 a0, A1 a1, A2 a2) { static typename aligned_storage<sizeof(T)>::type buf; ::new (&buf) T(a0, a1, a2); return *reinterpret_cast<T*>(&buf); } template <typename T, size_t N> inline _LIBCPP_CONSTEXPR size_t countof(const T (&)[N]) { return N; } template <typename T> inline _LIBCPP_CONSTEXPR size_t countof(const T * const begin, const T * const end) { return static_cast<size_t>(end - begin); } _LIBCPP_NORETURN static void __throw_runtime_error(const string &msg) { #ifndef _LIBCPP_NO_EXCEPTIONS throw runtime_error(msg); #else (void)msg; _VSTD::abort(); #endif } } #if defined(_AIX) // Set priority to INT_MIN + 256 + 150 # pragma priority ( -2147483242 ) #endif const locale::category locale::none; const locale::category locale::collate; const locale::category locale::ctype; const locale::category locale::monetary; const locale::category locale::numeric; const locale::category locale::time; const locale::category locale::messages; const locale::category locale::all; class _LIBCPP_HIDDEN locale::__imp : public facet { enum {N = 28}; #if defined(_LIBCPP_COMPILER_MSVC) // FIXME: MSVC doesn't support aligned parameters by value. // I can't get the __sso_allocator to work here // for MSVC I think for this reason. vector<facet*> facets_; #else vector<facet*, __sso_allocator<facet*, N> > facets_; #endif string name_; public: explicit __imp(size_t refs = 0); explicit __imp(const string& name, size_t refs = 0); __imp(const __imp&); __imp(const __imp&, const string&, locale::category c); __imp(const __imp& other, const __imp& one, locale::category c); __imp(const __imp&, facet* f, long id); ~__imp(); const string& name() const {return name_;} bool has_facet(long id) const {return static_cast<size_t>(id) < facets_.size() && facets_[static_cast<size_t>(id)];} const locale::facet* use_facet(long id) const; static const locale& make_classic(); static locale& make_global(); private: void install(facet* f, long id); template <class F> void install(F* f) {install(f, f->id.__get());} template <class F> void install_from(const __imp& other); }; locale::__imp::__imp(size_t refs) : facet(refs), facets_(N), name_("C") { facets_.clear(); install(&make<_VSTD::collate<char> >(1u)); install(&make<_VSTD::collate<wchar_t> >(1u)); install(&make<_VSTD::ctype<char> >(nullptr, false, 1u)); install(&make<_VSTD::ctype<wchar_t> >(1u)); install(&make<codecvt<char, char, mbstate_t> >(1u)); install(&make<codecvt<wchar_t, char, mbstate_t> >(1u)); install(&make<codecvt<char16_t, char, mbstate_t> >(1u)); install(&make<codecvt<char32_t, char, mbstate_t> >(1u)); install(&make<numpunct<char> >(1u)); install(&make<numpunct<wchar_t> >(1u)); install(&make<num_get<char> >(1u)); install(&make<num_get<wchar_t> >(1u)); install(&make<num_put<char> >(1u)); install(&make<num_put<wchar_t> >(1u)); install(&make<moneypunct<char, false> >(1u)); install(&make<moneypunct<char, true> >(1u)); install(&make<moneypunct<wchar_t, false> >(1u)); install(&make<moneypunct<wchar_t, true> >(1u)); install(&make<money_get<char> >(1u)); install(&make<money_get<wchar_t> >(1u)); install(&make<money_put<char> >(1u)); install(&make<money_put<wchar_t> >(1u)); install(&make<time_get<char> >(1u)); install(&make<time_get<wchar_t> >(1u)); install(&make<time_put<char> >(1u)); install(&make<time_put<wchar_t> >(1u)); install(&make<_VSTD::messages<char> >(1u)); install(&make<_VSTD::messages<wchar_t> >(1u)); } locale::__imp::__imp(const string& name, size_t refs) : facet(refs), facets_(N), name_(name) { #ifndef _LIBCPP_NO_EXCEPTIONS try { #endif // _LIBCPP_NO_EXCEPTIONS facets_ = locale::classic().__locale_->facets_; for (unsigned i = 0; i < facets_.size(); ++i) if (facets_[i]) facets_[i]->__add_shared(); install(new collate_byname<char>(name_)); install(new collate_byname<wchar_t>(name_)); install(new ctype_byname<char>(name_)); install(new ctype_byname<wchar_t>(name_)); install(new codecvt_byname<char, char, mbstate_t>(name_)); install(new codecvt_byname<wchar_t, char, mbstate_t>(name_)); install(new codecvt_byname<char16_t, char, mbstate_t>(name_)); install(new codecvt_byname<char32_t, char, mbstate_t>(name_)); install(new numpunct_byname<char>(name_)); install(new numpunct_byname<wchar_t>(name_)); install(new moneypunct_byname<char, false>(name_)); install(new moneypunct_byname<char, true>(name_)); install(new moneypunct_byname<wchar_t, false>(name_)); install(new moneypunct_byname<wchar_t, true>(name_)); install(new time_get_byname<char>(name_)); install(new time_get_byname<wchar_t>(name_)); install(new time_put_byname<char>(name_)); install(new time_put_byname<wchar_t>(name_)); install(new messages_byname<char>(name_)); install(new messages_byname<wchar_t>(name_)); #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { for (unsigned i = 0; i < facets_.size(); ++i) if (facets_[i]) facets_[i]->__release_shared(); throw; } #endif // _LIBCPP_NO_EXCEPTIONS } // NOTE avoid the `base class should be explicitly initialized in the // copy constructor` warning emitted by GCC #if defined(__clang__) || _GNUC_VER >= 406 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wextra" #endif locale::__imp::__imp(const __imp& other) : facets_(max<size_t>(N, other.facets_.size())), name_(other.name_) { facets_ = other.facets_; for (unsigned i = 0; i < facets_.size(); ++i) if (facets_[i]) facets_[i]->__add_shared(); } #if defined(__clang__) || _GNUC_VER >= 406 #pragma GCC diagnostic pop #endif locale::__imp::__imp(const __imp& other, const string& name, locale::category c) : facets_(N), name_("*") { facets_ = other.facets_; for (unsigned i = 0; i < facets_.size(); ++i) if (facets_[i]) facets_[i]->__add_shared(); #ifndef _LIBCPP_NO_EXCEPTIONS try { #endif // _LIBCPP_NO_EXCEPTIONS if (c & locale::collate) { install(new collate_byname<char>(name)); install(new collate_byname<wchar_t>(name)); } if (c & locale::ctype) { install(new ctype_byname<char>(name)); install(new ctype_byname<wchar_t>(name)); install(new codecvt_byname<char, char, mbstate_t>(name)); install(new codecvt_byname<wchar_t, char, mbstate_t>(name)); install(new codecvt_byname<char16_t, char, mbstate_t>(name)); install(new codecvt_byname<char32_t, char, mbstate_t>(name)); } if (c & locale::monetary) { install(new moneypunct_byname<char, false>(name)); install(new moneypunct_byname<char, true>(name)); install(new moneypunct_byname<wchar_t, false>(name)); install(new moneypunct_byname<wchar_t, true>(name)); } if (c & locale::numeric) { install(new numpunct_byname<char>(name)); install(new numpunct_byname<wchar_t>(name)); } if (c & locale::time) { install(new time_get_byname<char>(name)); install(new time_get_byname<wchar_t>(name)); install(new time_put_byname<char>(name)); install(new time_put_byname<wchar_t>(name)); } if (c & locale::messages) { install(new messages_byname<char>(name)); install(new messages_byname<wchar_t>(name)); } #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { for (unsigned i = 0; i < facets_.size(); ++i) if (facets_[i]) facets_[i]->__release_shared(); throw; } #endif // _LIBCPP_NO_EXCEPTIONS } template<class F> inline void locale::__imp::install_from(const locale::__imp& one) { long id = F::id.__get(); install(const_cast<F*>(static_cast<const F*>(one.use_facet(id))), id); } locale::__imp::__imp(const __imp& other, const __imp& one, locale::category c) : facets_(N), name_("*") { facets_ = other.facets_; for (unsigned i = 0; i < facets_.size(); ++i) if (facets_[i]) facets_[i]->__add_shared(); #ifndef _LIBCPP_NO_EXCEPTIONS try { #endif // _LIBCPP_NO_EXCEPTIONS if (c & locale::collate) { install_from<_VSTD::collate<char> >(one); install_from<_VSTD::collate<wchar_t> >(one); } if (c & locale::ctype) { install_from<_VSTD::ctype<char> >(one); install_from<_VSTD::ctype<wchar_t> >(one); install_from<_VSTD::codecvt<char, char, mbstate_t> >(one); install_from<_VSTD::codecvt<char16_t, char, mbstate_t> >(one); install_from<_VSTD::codecvt<char32_t, char, mbstate_t> >(one); install_from<_VSTD::codecvt<wchar_t, char, mbstate_t> >(one); } if (c & locale::monetary) { install_from<moneypunct<char, false> >(one); install_from<moneypunct<char, true> >(one); install_from<moneypunct<wchar_t, false> >(one); install_from<moneypunct<wchar_t, true> >(one); install_from<money_get<char> >(one); install_from<money_get<wchar_t> >(one); install_from<money_put<char> >(one); install_from<money_put<wchar_t> >(one); } if (c & locale::numeric) { install_from<numpunct<char> >(one); install_from<numpunct<wchar_t> >(one); install_from<num_get<char> >(one); install_from<num_get<wchar_t> >(one); install_from<num_put<char> >(one); install_from<num_put<wchar_t> >(one); } if (c & locale::time) { install_from<time_get<char> >(one); install_from<time_get<wchar_t> >(one); install_from<time_put<char> >(one); install_from<time_put<wchar_t> >(one); } if (c & locale::messages) { install_from<_VSTD::messages<char> >(one); install_from<_VSTD::messages<wchar_t> >(one); } #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { for (unsigned i = 0; i < facets_.size(); ++i) if (facets_[i]) facets_[i]->__release_shared(); throw; } #endif // _LIBCPP_NO_EXCEPTIONS } locale::__imp::__imp(const __imp& other, facet* f, long id) : facets_(max<size_t>(N, other.facets_.size()+1)), name_("*") { f->__add_shared(); unique_ptr<facet, release> hold(f); facets_ = other.facets_; for (unsigned i = 0; i < other.facets_.size(); ++i) if (facets_[i]) facets_[i]->__add_shared(); install(hold.get(), id); } locale::__imp::~__imp() { for (unsigned i = 0; i < facets_.size(); ++i) if (facets_[i]) facets_[i]->__release_shared(); } void locale::__imp::install(facet* f, long id) { f->__add_shared(); unique_ptr<facet, release> hold(f); if (static_cast<size_t>(id) >= facets_.size()) facets_.resize(static_cast<size_t>(id+1)); if (facets_[static_cast<size_t>(id)]) facets_[static_cast<size_t>(id)]->__release_shared(); facets_[static_cast<size_t>(id)] = hold.release(); } const locale::facet* locale::__imp::use_facet(long id) const { #ifndef _LIBCPP_NO_EXCEPTIONS if (!has_facet(id)) throw bad_cast(); #endif // _LIBCPP_NO_EXCEPTIONS return facets_[static_cast<size_t>(id)]; } // locale const locale& locale::__imp::make_classic() { // only one thread can get in here and it only gets in once static aligned_storage<sizeof(locale)>::type buf; locale* c = reinterpret_cast<locale*>(&buf); c->__locale_ = &make<__imp>(1u); return *c; } const locale& locale::classic() { static const locale& c = __imp::make_classic(); return c; } locale& locale::__imp::make_global() { // only one thread can get in here and it only gets in once static aligned_storage<sizeof(locale)>::type buf; ::new (&buf) locale(locale::classic()); return *reinterpret_cast<locale*>(&buf); } locale& locale::__global() { static locale& g = __imp::make_global(); return g; } locale::locale() _NOEXCEPT : __locale_(__global().__locale_) { __locale_->__add_shared(); } locale::locale(const locale& l) _NOEXCEPT : __locale_(l.__locale_) { __locale_->__add_shared(); } locale::~locale() { __locale_->__release_shared(); } const locale& locale::operator=(const locale& other) _NOEXCEPT { other.__locale_->__add_shared(); __locale_->__release_shared(); __locale_ = other.__locale_; return *this; } locale::locale(const char* name) #ifndef _LIBCPP_NO_EXCEPTIONS : __locale_(name ? new __imp(name) : throw runtime_error("locale constructed with null")) #else // _LIBCPP_NO_EXCEPTIONS : __locale_(new __imp(name)) #endif { __locale_->__add_shared(); } locale::locale(const string& name) : __locale_(new __imp(name)) { __locale_->__add_shared(); } locale::locale(const locale& other, const char* name, category c) #ifndef _LIBCPP_NO_EXCEPTIONS : __locale_(name ? new __imp(*other.__locale_, name, c) : throw runtime_error("locale constructed with null")) #else // _LIBCPP_NO_EXCEPTIONS : __locale_(new __imp(*other.__locale_, name, c)) #endif { __locale_->__add_shared(); } locale::locale(const locale& other, const string& name, category c) : __locale_(new __imp(*other.__locale_, name, c)) { __locale_->__add_shared(); } locale::locale(const locale& other, const locale& one, category c) : __locale_(new __imp(*other.__locale_, *one.__locale_, c)) { __locale_->__add_shared(); } string locale::name() const { return __locale_->name(); } void locale::__install_ctor(const locale& other, facet* f, long id) { if (f) __locale_ = new __imp(*other.__locale_, f, id); else __locale_ = other.__locale_; __locale_->__add_shared(); } locale locale::global(const locale& loc) { locale& g = __global(); locale r = g; g = loc; #ifndef __CloudABI__ if (g.name() != "*") setlocale(LC_ALL, g.name().c_str()); #endif return r; } bool locale::has_facet(id& x) const { return __locale_->has_facet(x.__get()); } const locale::facet* locale::use_facet(id& x) const { return __locale_->use_facet(x.__get()); } bool locale::operator==(const locale& y) const { return (__locale_ == y.__locale_) || (__locale_->name() != "*" && __locale_->name() == y.__locale_->name()); } // locale::facet locale::facet::~facet() { } void locale::facet::__on_zero_shared() _NOEXCEPT { delete this; } // locale::id int32_t locale::id::__next_id = 0; namespace { class __fake_bind { locale::id* id_; void (locale::id::* pmf_)(); public: __fake_bind(void (locale::id::* pmf)(), locale::id* id) : id_(id), pmf_(pmf) {} void operator()() const { (id_->*pmf_)(); } }; } long locale::id::__get() { call_once(__flag_, __fake_bind(&locale::id::__init, this)); return __id_ - 1; } void locale::id::__init() { __id_ = __sync_add_and_fetch(&__next_id, 1); } // template <> class collate_byname<char> collate_byname<char>::collate_byname(const char* n, size_t refs) : collate<char>(refs), __l(newlocale(LC_ALL_MASK, n, 0)) { if (__l == 0) __throw_runtime_error("collate_byname<char>::collate_byname" " failed to construct for " + string(n)); } collate_byname<char>::collate_byname(const string& name, size_t refs) : collate<char>(refs), __l(newlocale(LC_ALL_MASK, name.c_str(), 0)) { if (__l == 0) __throw_runtime_error("collate_byname<char>::collate_byname" " failed to construct for " + name); } collate_byname<char>::~collate_byname() { freelocale(__l); } int collate_byname<char>::do_compare(const char_type* __lo1, const char_type* __hi1, const char_type* __lo2, const char_type* __hi2) const { string_type lhs(__lo1, __hi1); string_type rhs(__lo2, __hi2); int r = strcoll_l(lhs.c_str(), rhs.c_str(), __l); if (r < 0) return -1; if (r > 0) return 1; return r; } collate_byname<char>::string_type collate_byname<char>::do_transform(const char_type* lo, const char_type* hi) const { const string_type in(lo, hi); string_type out(strxfrm_l(0, in.c_str(), 0, __l), char()); strxfrm_l(const_cast<char*>(out.c_str()), in.c_str(), out.size()+1, __l); return out; } // template <> class collate_byname<wchar_t> collate_byname<wchar_t>::collate_byname(const char* n, size_t refs) : collate<wchar_t>(refs), __l(newlocale(LC_ALL_MASK, n, 0)) { if (__l == 0) __throw_runtime_error("collate_byname<wchar_t>::collate_byname(size_t refs)" " failed to construct for " + string(n)); } collate_byname<wchar_t>::collate_byname(const string& name, size_t refs) : collate<wchar_t>(refs), __l(newlocale(LC_ALL_MASK, name.c_str(), 0)) { if (__l == 0) __throw_runtime_error("collate_byname<wchar_t>::collate_byname(size_t refs)" " failed to construct for " + name); } collate_byname<wchar_t>::~collate_byname() { freelocale(__l); } int collate_byname<wchar_t>::do_compare(const char_type* __lo1, const char_type* __hi1, const char_type* __lo2, const char_type* __hi2) const { string_type lhs(__lo1, __hi1); string_type rhs(__lo2, __hi2); int r = wcscoll_l(lhs.c_str(), rhs.c_str(), __l); if (r < 0) return -1; if (r > 0) return 1; return r; } collate_byname<wchar_t>::string_type collate_byname<wchar_t>::do_transform(const char_type* lo, const char_type* hi) const { const string_type in(lo, hi); string_type out(wcsxfrm_l(0, in.c_str(), 0, __l), wchar_t()); wcsxfrm_l(const_cast<wchar_t*>(out.c_str()), in.c_str(), out.size()+1, __l); return out; } // template <> class ctype<wchar_t>; const ctype_base::mask ctype_base::space; const ctype_base::mask ctype_base::print; const ctype_base::mask ctype_base::cntrl; const ctype_base::mask ctype_base::upper; const ctype_base::mask ctype_base::lower; const ctype_base::mask ctype_base::alpha; const ctype_base::mask ctype_base::digit; const ctype_base::mask ctype_base::punct; const ctype_base::mask ctype_base::xdigit; const ctype_base::mask ctype_base::blank; const ctype_base::mask ctype_base::alnum; const ctype_base::mask ctype_base::graph; locale::id ctype<wchar_t>::id; ctype<wchar_t>::~ctype() { } bool ctype<wchar_t>::do_is(mask m, char_type c) const { return isascii(c) ? (ctype<char>::classic_table()[c] & m) != 0 : false; } const wchar_t* ctype<wchar_t>::do_is(const char_type* low, const char_type* high, mask* vec) const { for (; low != high; ++low, ++vec) *vec = static_cast<mask>(isascii(*low) ? ctype<char>::classic_table()[*low] : 0); return low; } const wchar_t* ctype<wchar_t>::do_scan_is(mask m, const char_type* low, const char_type* high) const { for (; low != high; ++low) if (isascii(*low) && (ctype<char>::classic_table()[*low] & m)) break; return low; } const wchar_t* ctype<wchar_t>::do_scan_not(mask m, const char_type* low, const char_type* high) const { for (; low != high; ++low) if (!(isascii(*low) && (ctype<char>::classic_table()[*low] & m))) break; return low; } wchar_t ctype<wchar_t>::do_toupper(char_type c) const { #ifdef _LIBCPP_HAS_DEFAULTRUNELOCALE return isascii(c) ? _DefaultRuneLocale.__mapupper[c] : c; #elif defined(__GLIBC__) || defined(__EMSCRIPTEN__) || \ defined(__NetBSD__) return isascii(c) ? ctype<char>::__classic_upper_table()[c] : c; #else return (isascii(c) && iswlower_l(c, _LIBCPP_GET_C_LOCALE)) ? c-L'a'+L'A' : c; #endif } const wchar_t* ctype<wchar_t>::do_toupper(char_type* low, const char_type* high) const { for (; low != high; ++low) #ifdef _LIBCPP_HAS_DEFAULTRUNELOCALE *low = isascii(*low) ? _DefaultRuneLocale.__mapupper[*low] : *low; #elif defined(__GLIBC__) || defined(__EMSCRIPTEN__) || \ defined(__NetBSD__) *low = isascii(*low) ? ctype<char>::__classic_upper_table()[*low] : *low; #else *low = (isascii(*low) && islower_l(*low, _LIBCPP_GET_C_LOCALE)) ? (*low-L'a'+L'A') : *low; #endif return low; } wchar_t ctype<wchar_t>::do_tolower(char_type c) const { #ifdef _LIBCPP_HAS_DEFAULTRUNELOCALE return isascii(c) ? _DefaultRuneLocale.__maplower[c] : c; #elif defined(__GLIBC__) || defined(__EMSCRIPTEN__) || \ defined(__NetBSD__) return isascii(c) ? ctype<char>::__classic_lower_table()[c] : c; #else return (isascii(c) && isupper_l(c, _LIBCPP_GET_C_LOCALE)) ? c-L'A'+'a' : c; #endif } const wchar_t* ctype<wchar_t>::do_tolower(char_type* low, const char_type* high) const { for (; low != high; ++low) #ifdef _LIBCPP_HAS_DEFAULTRUNELOCALE *low = isascii(*low) ? _DefaultRuneLocale.__maplower[*low] : *low; #elif defined(__GLIBC__) || defined(__EMSCRIPTEN__) || \ defined(__NetBSD__) *low = isascii(*low) ? ctype<char>::__classic_lower_table()[*low] : *low; #else *low = (isascii(*low) && isupper_l(*low, _LIBCPP_GET_C_LOCALE)) ? *low-L'A'+L'a' : *low; #endif return low; } wchar_t ctype<wchar_t>::do_widen(char c) const { return c; } const char* ctype<wchar_t>::do_widen(const char* low, const char* high, char_type* dest) const { for (; low != high; ++low, ++dest) *dest = *low; return low; } char ctype<wchar_t>::do_narrow(char_type c, char dfault) const { if (isascii(c)) return static_cast<char>(c); return dfault; } const wchar_t* ctype<wchar_t>::do_narrow(const char_type* low, const char_type* high, char dfault, char* dest) const { for (; low != high; ++low, ++dest) if (isascii(*low)) *dest = static_cast<char>(*low); else *dest = dfault; return low; } // template <> class ctype<char>; locale::id ctype<char>::id; ctype<char>::ctype(const mask* tab, bool del, size_t refs) : locale::facet(refs), __tab_(tab), __del_(del) { if (__tab_ == 0) __tab_ = classic_table(); } ctype<char>::~ctype() { if (__tab_ && __del_) delete [] __tab_; } char ctype<char>::do_toupper(char_type c) const { #ifdef _LIBCPP_HAS_DEFAULTRUNELOCALE return isascii(c) ? static_cast<char>(_DefaultRuneLocale.__mapupper[static_cast<ptrdiff_t>(c)]) : c; #elif defined(__NetBSD__) return static_cast<char>(__classic_upper_table()[static_cast<unsigned char>(c)]); #elif defined(__GLIBC__) || defined(__EMSCRIPTEN__) return isascii(c) ? static_cast<char>(__classic_upper_table()[static_cast<unsigned char>(c)]) : c; #else return (isascii(c) && islower_l(c, _LIBCPP_GET_C_LOCALE)) ? c-'a'+'A' : c; #endif } const char* ctype<char>::do_toupper(char_type* low, const char_type* high) const { for (; low != high; ++low) #ifdef _LIBCPP_HAS_DEFAULTRUNELOCALE *low = isascii(*low) ? static_cast<char>(_DefaultRuneLocale.__mapupper[static_cast<ptrdiff_t>(*low)]) : *low; #elif defined(__NetBSD__) *low = static_cast<char>(__classic_upper_table()[static_cast<unsigned char>(*low)]); #elif defined(__GLIBC__) || defined(__EMSCRIPTEN__) *low = isascii(*low) ? static_cast<char>(__classic_upper_table()[static_cast<size_t>(*low)]) : *low; #else *low = (isascii(*low) && islower_l(*low, _LIBCPP_GET_C_LOCALE)) ? *low-'a'+'A' : *low; #endif return low; } char ctype<char>::do_tolower(char_type c) const { #ifdef _LIBCPP_HAS_DEFAULTRUNELOCALE return isascii(c) ? static_cast<char>(_DefaultRuneLocale.__maplower[static_cast<ptrdiff_t>(c)]) : c; #elif defined(__NetBSD__) return static_cast<char>(__classic_lower_table()[static_cast<unsigned char>(c)]); #elif defined(__GLIBC__) || defined(__EMSCRIPTEN__) return isascii(c) ? static_cast<char>(__classic_lower_table()[static_cast<size_t>(c)]) : c; #else return (isascii(c) && isupper_l(c, _LIBCPP_GET_C_LOCALE)) ? c-'A'+'a' : c; #endif } const char* ctype<char>::do_tolower(char_type* low, const char_type* high) const { for (; low != high; ++low) #ifdef _LIBCPP_HAS_DEFAULTRUNELOCALE *low = isascii(*low) ? static_cast<char>(_DefaultRuneLocale.__maplower[static_cast<ptrdiff_t>(*low)]) : *low; #elif defined(__NetBSD__) *low = static_cast<char>(__classic_lower_table()[static_cast<unsigned char>(*low)]); #elif defined(__GLIBC__) || defined(__EMSCRIPTEN__) *low = isascii(*low) ? static_cast<char>(__classic_lower_table()[static_cast<size_t>(*low)]) : *low; #else *low = (isascii(*low) && isupper_l(*low, _LIBCPP_GET_C_LOCALE)) ? *low-'A'+'a' : *low; #endif return low; } char ctype<char>::do_widen(char c) const { return c; } const char* ctype<char>::do_widen(const char* low, const char* high, char_type* dest) const { for (; low != high; ++low, ++dest) *dest = *low; return low; } char ctype<char>::do_narrow(char_type c, char dfault) const { if (isascii(c)) return static_cast<char>(c); return dfault; } const char* ctype<char>::do_narrow(const char_type* low, const char_type* high, char dfault, char* dest) const { for (; low != high; ++low, ++dest) if (isascii(*low)) *dest = *low; else *dest = dfault; return low; } #if defined(__EMSCRIPTEN__) extern "C" const unsigned short ** __ctype_b_loc(); extern "C" const int ** __ctype_tolower_loc(); extern "C" const int ** __ctype_toupper_loc(); #endif #ifdef _LIBCPP_PROVIDES_DEFAULT_RUNE_TABLE const ctype<char>::mask* ctype<char>::classic_table() _NOEXCEPT { static _LIBCPP_CONSTEXPR const ctype<char>::mask builtin_table[table_size] = { cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl | space | blank, cntrl | space, cntrl | space, cntrl | space, cntrl | space, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, cntrl, space | blank | print, punct | print, punct | print, punct | print, punct | print, punct | print, punct | print, punct | print, punct | print, punct | print, punct | print, punct | print, punct | print, punct | print, punct | print, punct | print, digit | print | xdigit, digit | print | xdigit, digit | print | xdigit, digit | print | xdigit, digit | print | xdigit, digit | print | xdigit, digit | print | xdigit, digit | print | xdigit, digit | print | xdigit, digit | print | xdigit, punct | print, punct | print, punct | print, punct | print, punct | print, punct | print, punct | print, upper | xdigit | print | alpha, upper | xdigit | print | alpha, upper | xdigit | print | alpha, upper | xdigit | print | alpha, upper | xdigit | print | alpha, upper | xdigit | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, upper | print | alpha, punct | print, punct | print, punct | print, punct | print, punct | print, punct | print, lower | xdigit | print | alpha, lower | xdigit | print | alpha, lower | xdigit | print | alpha, lower | xdigit | print | alpha, lower | xdigit | print | alpha, lower | xdigit | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, lower | print | alpha, punct | print, punct | print, punct | print, punct | print, cntrl, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; return builtin_table; } #else const ctype<char>::mask* ctype<char>::classic_table() _NOEXCEPT { #if defined(__APPLE__) || defined(__FreeBSD__) return _DefaultRuneLocale.__runetype; #elif defined(__NetBSD__) return _C_ctype_tab_ + 1; #elif defined(__GLIBC__) return _LIBCPP_GET_C_LOCALE->__ctype_b; #elif __sun__ return __ctype_mask; #elif defined(_LIBCPP_MSVCRT) || defined(__MINGW32__) #if _VC_CRT_MAJOR_VERSION < 14 // This is assumed to be safe, which is a nonsense assumption because we're // going to end up dereferencing it later... return _ctype+1; // internal ctype mask table defined in msvcrt.dll #else return __pctype_func(); #endif #elif defined(__EMSCRIPTEN__) return *__ctype_b_loc(); #elif defined(_NEWLIB_VERSION) // Newlib has a 257-entry table in ctype_.c, where (char)0 starts at [1]. return _ctype_ + 1; #elif defined(_AIX) return (const unsigned int *)__lc_ctype_ptr->obj->mask; #else // Platform not supported: abort so the person doing the port knows what to // fix # warning ctype<char>::classic_table() is not implemented printf("ctype<char>::classic_table() is not implemented\n"); abort(); return NULL; #endif } #endif #if defined(__GLIBC__) const int* ctype<char>::__classic_lower_table() _NOEXCEPT { return _LIBCPP_GET_C_LOCALE->__ctype_tolower; } const int* ctype<char>::__classic_upper_table() _NOEXCEPT { return _LIBCPP_GET_C_LOCALE->__ctype_toupper; } #elif __NetBSD__ const short* ctype<char>::__classic_lower_table() _NOEXCEPT { return _C_tolower_tab_ + 1; } const short* ctype<char>::__classic_upper_table() _NOEXCEPT { return _C_toupper_tab_ + 1; } #elif defined(__EMSCRIPTEN__) const int* ctype<char>::__classic_lower_table() _NOEXCEPT { return *__ctype_tolower_loc(); } const int* ctype<char>::__classic_upper_table() _NOEXCEPT { return *__ctype_toupper_loc(); } #endif // __GLIBC__ || __NETBSD__ || __EMSCRIPTEN__ // template <> class ctype_byname<char> ctype_byname<char>::ctype_byname(const char* name, size_t refs) : ctype<char>(0, false, refs), __l(newlocale(LC_ALL_MASK, name, 0)) { if (__l == 0) __throw_runtime_error("ctype_byname<char>::ctype_byname" " failed to construct for " + string(name)); } ctype_byname<char>::ctype_byname(const string& name, size_t refs) : ctype<char>(0, false, refs), __l(newlocale(LC_ALL_MASK, name.c_str(), 0)) { if (__l == 0) __throw_runtime_error("ctype_byname<char>::ctype_byname" " failed to construct for " + name); } ctype_byname<char>::~ctype_byname() { freelocale(__l); } char ctype_byname<char>::do_toupper(char_type c) const { return static_cast<char>(toupper_l(static_cast<unsigned char>(c), __l)); } const char* ctype_byname<char>::do_toupper(char_type* low, const char_type* high) const { for (; low != high; ++low) *low = static_cast<char>(toupper_l(static_cast<unsigned char>(*low), __l)); return low; } char ctype_byname<char>::do_tolower(char_type c) const { return static_cast<char>(tolower_l(static_cast<unsigned char>(c), __l)); } const char* ctype_byname<char>::do_tolower(char_type* low, const char_type* high) const { for (; low != high; ++low) *low = static_cast<char>(tolower_l(static_cast<unsigned char>(*low), __l)); return low; } // template <> class ctype_byname<wchar_t> ctype_byname<wchar_t>::ctype_byname(const char* name, size_t refs) : ctype<wchar_t>(refs), __l(newlocale(LC_ALL_MASK, name, 0)) { if (__l == 0) __throw_runtime_error("ctype_byname<wchar_t>::ctype_byname" " failed to construct for " + string(name)); } ctype_byname<wchar_t>::ctype_byname(const string& name, size_t refs) : ctype<wchar_t>(refs), __l(newlocale(LC_ALL_MASK, name.c_str(), 0)) { if (__l == 0) __throw_runtime_error("ctype_byname<wchar_t>::ctype_byname" " failed to construct for " + name); } ctype_byname<wchar_t>::~ctype_byname() { freelocale(__l); } bool ctype_byname<wchar_t>::do_is(mask m, char_type c) const { #ifdef _LIBCPP_WCTYPE_IS_MASK return static_cast<bool>(iswctype_l(c, m, __l)); #else bool result = false; wint_t ch = static_cast<wint_t>(c); if ((m & space) == space) result |= (iswspace_l(ch, __l) != 0); if ((m & print) == print) result |= (iswprint_l(ch, __l) != 0); if ((m & cntrl) == cntrl) result |= (iswcntrl_l(ch, __l) != 0); if ((m & upper) == upper) result |= (iswupper_l(ch, __l) != 0); if ((m & lower) == lower) result |= (iswlower_l(ch, __l) != 0); if ((m & alpha) == alpha) result |= (iswalpha_l(ch, __l) != 0); if ((m & digit) == digit) result |= (iswdigit_l(ch, __l) != 0); if ((m & punct) == punct) result |= (iswpunct_l(ch, __l) != 0); if ((m & xdigit) == xdigit) result |= (iswxdigit_l(ch, __l) != 0); if ((m & blank) == blank) result |= (iswblank_l(ch, __l) != 0); return result; #endif } const wchar_t* ctype_byname<wchar_t>::do_is(const char_type* low, const char_type* high, mask* vec) const { for (; low != high; ++low, ++vec) { if (isascii(*low)) *vec = static_cast<mask>(ctype<char>::classic_table()[*low]); else { *vec = 0; wint_t ch = static_cast<wint_t>(*low); if (iswspace_l(ch, __l)) *vec |= space; #ifndef _LIBCPP_CTYPE_MASK_IS_COMPOSITE_PRINT if (iswprint_l(ch, __l)) *vec |= print; #endif if (iswcntrl_l(ch, __l)) *vec |= cntrl; if (iswupper_l(ch, __l)) *vec |= upper; if (iswlower_l(ch, __l)) *vec |= lower; #ifndef _LIBCPP_CTYPE_MASK_IS_COMPOSITE_ALPHA if (iswalpha_l(ch, __l)) *vec |= alpha; #endif if (iswdigit_l(ch, __l)) *vec |= digit; if (iswpunct_l(ch, __l)) *vec |= punct; #ifndef _LIBCPP_CTYPE_MASK_IS_COMPOSITE_XDIGIT if (iswxdigit_l(ch, __l)) *vec |= xdigit; #endif #if !defined(__sun__) if (iswblank_l(ch, __l)) *vec |= blank; #endif } } return low; } const wchar_t* ctype_byname<wchar_t>::do_scan_is(mask m, const char_type* low, const char_type* high) const { for (; low != high; ++low) { #ifdef _LIBCPP_WCTYPE_IS_MASK if (iswctype_l(*low, m, __l)) break; #else wint_t ch = static_cast<wint_t>(*low); if ((m & space) == space && iswspace_l(ch, __l)) break; if ((m & print) == print && iswprint_l(ch, __l)) break; if ((m & cntrl) == cntrl && iswcntrl_l(ch, __l)) break; if ((m & upper) == upper && iswupper_l(ch, __l)) break; if ((m & lower) == lower && iswlower_l(ch, __l)) break; if ((m & alpha) == alpha && iswalpha_l(ch, __l)) break; if ((m & digit) == digit && iswdigit_l(ch, __l)) break; if ((m & punct) == punct && iswpunct_l(ch, __l)) break; if ((m & xdigit) == xdigit && iswxdigit_l(ch, __l)) break; if ((m & blank) == blank && iswblank_l(ch, __l)) break; #endif } return low; } const wchar_t* ctype_byname<wchar_t>::do_scan_not(mask m, const char_type* low, const char_type* high) const { for (; low != high; ++low) { #ifdef _LIBCPP_WCTYPE_IS_MASK if (!iswctype_l(*low, m, __l)) break; #else wint_t ch = static_cast<wint_t>(*low); if ((m & space) == space && iswspace_l(ch, __l)) continue; if ((m & print) == print && iswprint_l(ch, __l)) continue; if ((m & cntrl) == cntrl && iswcntrl_l(ch, __l)) continue; if ((m & upper) == upper && iswupper_l(ch, __l)) continue; if ((m & lower) == lower && iswlower_l(ch, __l)) continue; if ((m & alpha) == alpha && iswalpha_l(ch, __l)) continue; if ((m & digit) == digit && iswdigit_l(ch, __l)) continue; if ((m & punct) == punct && iswpunct_l(ch, __l)) continue; if ((m & xdigit) == xdigit && iswxdigit_l(ch, __l)) continue; if ((m & blank) == blank && iswblank_l(ch, __l)) continue; break; #endif } return low; } wchar_t ctype_byname<wchar_t>::do_toupper(char_type c) const { return towupper_l(c, __l); } const wchar_t* ctype_byname<wchar_t>::do_toupper(char_type* low, const char_type* high) const { for (; low != high; ++low) *low = towupper_l(*low, __l); return low; } wchar_t ctype_byname<wchar_t>::do_tolower(char_type c) const { return towlower_l(c, __l); } const wchar_t* ctype_byname<wchar_t>::do_tolower(char_type* low, const char_type* high) const { for (; low != high; ++low) *low = towlower_l(*low, __l); return low; } wchar_t ctype_byname<wchar_t>::do_widen(char c) const { return __libcpp_btowc_l(c, __l); } const char* ctype_byname<wchar_t>::do_widen(const char* low, const char* high, char_type* dest) const { for (; low != high; ++low, ++dest) *dest = __libcpp_btowc_l(*low, __l); return low; } char ctype_byname<wchar_t>::do_narrow(char_type c, char dfault) const { int r = __libcpp_wctob_l(c, __l); return r != static_cast<int>(WEOF) ? static_cast<char>(r) : dfault; } const wchar_t* ctype_byname<wchar_t>::do_narrow(const char_type* low, const char_type* high, char dfault, char* dest) const { for (; low != high; ++low, ++dest) { int r = __libcpp_wctob_l(*low, __l); *dest = r != static_cast<int>(WEOF) ? static_cast<char>(r) : dfault; } return low; } // template <> class codecvt<char, char, mbstate_t> locale::id codecvt<char, char, mbstate_t>::id; codecvt<char, char, mbstate_t>::~codecvt() { } codecvt<char, char, mbstate_t>::result codecvt<char, char, mbstate_t>::do_out(state_type&, const intern_type* frm, const intern_type*, const intern_type*& frm_nxt, extern_type* to, extern_type*, extern_type*& to_nxt) const { frm_nxt = frm; to_nxt = to; return noconv; } codecvt<char, char, mbstate_t>::result codecvt<char, char, mbstate_t>::do_in(state_type&, const extern_type* frm, const extern_type*, const extern_type*& frm_nxt, intern_type* to, intern_type*, intern_type*& to_nxt) const { frm_nxt = frm; to_nxt = to; return noconv; } codecvt<char, char, mbstate_t>::result codecvt<char, char, mbstate_t>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int codecvt<char, char, mbstate_t>::do_encoding() const _NOEXCEPT { return 1; } bool codecvt<char, char, mbstate_t>::do_always_noconv() const _NOEXCEPT { return true; } int codecvt<char, char, mbstate_t>::do_length(state_type&, const extern_type* frm, const extern_type* end, size_t mx) const { return static_cast<int>(min<size_t>(mx, static_cast<size_t>(end-frm))); } int codecvt<char, char, mbstate_t>::do_max_length() const _NOEXCEPT { return 1; } // template <> class codecvt<wchar_t, char, mbstate_t> locale::id codecvt<wchar_t, char, mbstate_t>::id; codecvt<wchar_t, char, mbstate_t>::codecvt(size_t refs) : locale::facet(refs), __l(_LIBCPP_GET_C_LOCALE) { } codecvt<wchar_t, char, mbstate_t>::codecvt(const char* nm, size_t refs) : locale::facet(refs), __l(newlocale(LC_ALL_MASK, nm, 0)) { if (__l == 0) __throw_runtime_error("codecvt_byname<wchar_t, char, mbstate_t>::codecvt_byname" " failed to construct for " + string(nm)); } codecvt<wchar_t, char, mbstate_t>::~codecvt() { if (__l != _LIBCPP_GET_C_LOCALE) freelocale(__l); } codecvt<wchar_t, char, mbstate_t>::result codecvt<wchar_t, char, mbstate_t>::do_out(state_type& st, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { // look for first internal null in frm const intern_type* fend = frm; for (; fend != frm_end; ++fend) if (*fend == 0) break; // loop over all null-terminated sequences in frm to_nxt = to; for (frm_nxt = frm; frm != frm_end && to != to_end; frm = frm_nxt, to = to_nxt) { // save state in case it is needed to recover to_nxt on error mbstate_t save_state = st; size_t n = __libcpp_wcsnrtombs_l(to, &frm_nxt, static_cast<size_t>(fend-frm), static_cast<size_t>(to_end-to), &st, __l); if (n == size_t(-1)) { // need to recover to_nxt for (to_nxt = to; frm != frm_nxt; ++frm) { n = __libcpp_wcrtomb_l(to_nxt, *frm, &save_state, __l); if (n == size_t(-1)) break; to_nxt += n; } frm_nxt = frm; return error; } if (n == 0) return partial; to_nxt += n; if (to_nxt == to_end) break; if (fend != frm_end) // set up next null terminated sequence { // Try to write the terminating null extern_type tmp[MB_LEN_MAX]; n = __libcpp_wcrtomb_l(tmp, intern_type(), &st, __l); if (n == size_t(-1)) // on error return error; if (n > static_cast<size_t>(to_end-to_nxt)) // is there room? return partial; for (extern_type* p = tmp; n; --n) // write it *to_nxt++ = *p++; ++frm_nxt; // look for next null in frm for (fend = frm_nxt; fend != frm_end; ++fend) if (*fend == 0) break; } } return frm_nxt == frm_end ? ok : partial; } codecvt<wchar_t, char, mbstate_t>::result codecvt<wchar_t, char, mbstate_t>::do_in(state_type& st, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { // look for first internal null in frm const extern_type* fend = frm; for (; fend != frm_end; ++fend) if (*fend == 0) break; // loop over all null-terminated sequences in frm to_nxt = to; for (frm_nxt = frm; frm != frm_end && to != to_end; frm = frm_nxt, to = to_nxt) { // save state in case it is needed to recover to_nxt on error mbstate_t save_state = st; size_t n = __libcpp_mbsnrtowcs_l(to, &frm_nxt, static_cast<size_t>(fend-frm), static_cast<size_t>(to_end-to), &st, __l); if (n == size_t(-1)) { // need to recover to_nxt for (to_nxt = to; frm != frm_nxt; ++to_nxt) { n = __libcpp_mbrtowc_l(to_nxt, frm, static_cast<size_t>(fend-frm), &save_state, __l); switch (n) { case 0: ++frm; break; case size_t(-1): frm_nxt = frm; return error; case size_t(-2): frm_nxt = frm; return partial; default: frm += n; break; } } frm_nxt = frm; return frm_nxt == frm_end ? ok : partial; } if (n == size_t(-1)) return error; to_nxt += n; if (to_nxt == to_end) break; if (fend != frm_end) // set up next null terminated sequence { // Try to write the terminating null n = __libcpp_mbrtowc_l(to_nxt, frm_nxt, 1, &st, __l); if (n != 0) // on error return error; ++to_nxt; ++frm_nxt; // look for next null in frm for (fend = frm_nxt; fend != frm_end; ++fend) if (*fend == 0) break; } } return frm_nxt == frm_end ? ok : partial; } codecvt<wchar_t, char, mbstate_t>::result codecvt<wchar_t, char, mbstate_t>::do_unshift(state_type& st, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { to_nxt = to; extern_type tmp[MB_LEN_MAX]; size_t n = __libcpp_wcrtomb_l(tmp, intern_type(), &st, __l); if (n == size_t(-1) || n == 0) // on error return error; --n; if (n > static_cast<size_t>(to_end-to_nxt)) // is there room? return partial; for (extern_type* p = tmp; n; --n) // write it *to_nxt++ = *p++; return ok; } int codecvt<wchar_t, char, mbstate_t>::do_encoding() const _NOEXCEPT { if (__libcpp_mbtowc_l(nullptr, nullptr, MB_LEN_MAX, __l) != 0) return -1; // stateless encoding if (__l == 0 || __libcpp_mb_cur_max_l(__l) == 1) // there are no known constant length encodings return 1; // which take more than 1 char to form a wchar_t return 0; } bool codecvt<wchar_t, char, mbstate_t>::do_always_noconv() const _NOEXCEPT { return false; } int codecvt<wchar_t, char, mbstate_t>::do_length(state_type& st, const extern_type* frm, const extern_type* frm_end, size_t mx) const { int nbytes = 0; for (size_t nwchar_t = 0; nwchar_t < mx && frm != frm_end; ++nwchar_t) { size_t n = __libcpp_mbrlen_l(frm, static_cast<size_t>(frm_end-frm), &st, __l); switch (n) { case 0: ++nbytes; ++frm; break; case size_t(-1): case size_t(-2): return nbytes; default: nbytes += n; frm += n; break; } } return nbytes; } int codecvt<wchar_t, char, mbstate_t>::do_max_length() const _NOEXCEPT { return __l == 0 ? 1 : static_cast<int>(__libcpp_mb_cur_max_l(__l)); } // Valid UTF ranges // UTF-32 UTF-16 UTF-8 # of code points // first second first second third fourth // 000000 - 00007F 0000 - 007F 00 - 7F 127 // 000080 - 0007FF 0080 - 07FF C2 - DF, 80 - BF 1920 // 000800 - 000FFF 0800 - 0FFF E0 - E0, A0 - BF, 80 - BF 2048 // 001000 - 00CFFF 1000 - CFFF E1 - EC, 80 - BF, 80 - BF 49152 // 00D000 - 00D7FF D000 - D7FF ED - ED, 80 - 9F, 80 - BF 2048 // 00D800 - 00DFFF invalid // 00E000 - 00FFFF E000 - FFFF EE - EF, 80 - BF, 80 - BF 8192 // 010000 - 03FFFF D800 - D8BF, DC00 - DFFF F0 - F0, 90 - BF, 80 - BF, 80 - BF 196608 // 040000 - 0FFFFF D8C0 - DBBF, DC00 - DFFF F1 - F3, 80 - BF, 80 - BF, 80 - BF 786432 // 100000 - 10FFFF DBC0 - DBFF, DC00 - DFFF F4 - F4, 80 - 8F, 80 - BF, 80 - BF 65536 static codecvt_base::result utf16_to_utf8(const uint16_t* frm, const uint16_t* frm_end, const uint16_t*& frm_nxt, uint8_t* to, uint8_t* to_end, uint8_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & generate_header) { if (to_end-to_nxt < 3) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xEF); *to_nxt++ = static_cast<uint8_t>(0xBB); *to_nxt++ = static_cast<uint8_t>(0xBF); } for (; frm_nxt < frm_end; ++frm_nxt) { uint16_t wc1 = *frm_nxt; if (wc1 > Maxcode) return codecvt_base::error; if (wc1 < 0x0080) { if (to_end-to_nxt < 1) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(wc1); } else if (wc1 < 0x0800) { if (to_end-to_nxt < 2) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xC0 | (wc1 >> 6)); *to_nxt++ = static_cast<uint8_t>(0x80 | (wc1 & 0x03F)); } else if (wc1 < 0xD800) { if (to_end-to_nxt < 3) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xE0 | (wc1 >> 12)); *to_nxt++ = static_cast<uint8_t>(0x80 | ((wc1 & 0x0FC0) >> 6)); *to_nxt++ = static_cast<uint8_t>(0x80 | (wc1 & 0x003F)); } else if (wc1 < 0xDC00) { if (frm_end-frm_nxt < 2) return codecvt_base::partial; uint16_t wc2 = frm_nxt[1]; if ((wc2 & 0xFC00) != 0xDC00) return codecvt_base::error; if (to_end-to_nxt < 4) return codecvt_base::partial; if (((((wc1 & 0x03C0UL) >> 6) + 1) << 16) + ((wc1 & 0x003FUL) << 10) + (wc2 & 0x03FF) > Maxcode) return codecvt_base::error; ++frm_nxt; uint8_t z = ((wc1 & 0x03C0) >> 6) + 1; *to_nxt++ = static_cast<uint8_t>(0xF0 | (z >> 2)); *to_nxt++ = static_cast<uint8_t>(0x80 | ((z & 0x03) << 4) | ((wc1 & 0x003C) >> 2)); *to_nxt++ = static_cast<uint8_t>(0x80 | ((wc1 & 0x0003) << 4) | ((wc2 & 0x03C0) >> 6)); *to_nxt++ = static_cast<uint8_t>(0x80 | (wc2 & 0x003F)); } else if (wc1 < 0xE000) { return codecvt_base::error; } else { if (to_end-to_nxt < 3) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xE0 | (wc1 >> 12)); *to_nxt++ = static_cast<uint8_t>(0x80 | ((wc1 & 0x0FC0) >> 6)); *to_nxt++ = static_cast<uint8_t>(0x80 | (wc1 & 0x003F)); } } return codecvt_base::ok; } static codecvt_base::result utf16_to_utf8(const uint32_t* frm, const uint32_t* frm_end, const uint32_t*& frm_nxt, uint8_t* to, uint8_t* to_end, uint8_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & generate_header) { if (to_end-to_nxt < 3) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xEF); *to_nxt++ = static_cast<uint8_t>(0xBB); *to_nxt++ = static_cast<uint8_t>(0xBF); } for (; frm_nxt < frm_end; ++frm_nxt) { uint16_t wc1 = static_cast<uint16_t>(*frm_nxt); if (wc1 > Maxcode) return codecvt_base::error; if (wc1 < 0x0080) { if (to_end-to_nxt < 1) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(wc1); } else if (wc1 < 0x0800) { if (to_end-to_nxt < 2) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xC0 | (wc1 >> 6)); *to_nxt++ = static_cast<uint8_t>(0x80 | (wc1 & 0x03F)); } else if (wc1 < 0xD800) { if (to_end-to_nxt < 3) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xE0 | (wc1 >> 12)); *to_nxt++ = static_cast<uint8_t>(0x80 | ((wc1 & 0x0FC0) >> 6)); *to_nxt++ = static_cast<uint8_t>(0x80 | (wc1 & 0x003F)); } else if (wc1 < 0xDC00) { if (frm_end-frm_nxt < 2) return codecvt_base::partial; uint16_t wc2 = static_cast<uint16_t>(frm_nxt[1]); if ((wc2 & 0xFC00) != 0xDC00) return codecvt_base::error; if (to_end-to_nxt < 4) return codecvt_base::partial; if (((((wc1 & 0x03C0UL) >> 6) + 1) << 16) + ((wc1 & 0x003FUL) << 10) + (wc2 & 0x03FF) > Maxcode) return codecvt_base::error; ++frm_nxt; uint8_t z = ((wc1 & 0x03C0) >> 6) + 1; *to_nxt++ = static_cast<uint8_t>(0xF0 | (z >> 2)); *to_nxt++ = static_cast<uint8_t>(0x80 | ((z & 0x03) << 4) | ((wc1 & 0x003C) >> 2)); *to_nxt++ = static_cast<uint8_t>(0x80 | ((wc1 & 0x0003) << 4) | ((wc2 & 0x03C0) >> 6)); *to_nxt++ = static_cast<uint8_t>(0x80 | (wc2 & 0x003F)); } else if (wc1 < 0xE000) { return codecvt_base::error; } else { if (to_end-to_nxt < 3) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xE0 | (wc1 >> 12)); *to_nxt++ = static_cast<uint8_t>(0x80 | ((wc1 & 0x0FC0) >> 6)); *to_nxt++ = static_cast<uint8_t>(0x80 | (wc1 & 0x003F)); } } return codecvt_base::ok; } static codecvt_base::result utf8_to_utf16(const uint8_t* frm, const uint8_t* frm_end, const uint8_t*& frm_nxt, uint16_t* to, uint16_t* to_end, uint16_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & consume_header) { if (frm_end-frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF) frm_nxt += 3; } for (; frm_nxt < frm_end && to_nxt < to_end; ++to_nxt) { uint8_t c1 = *frm_nxt; if (c1 > Maxcode) return codecvt_base::error; if (c1 < 0x80) { *to_nxt = static_cast<uint16_t>(c1); ++frm_nxt; } else if (c1 < 0xC2) { return codecvt_base::error; } else if (c1 < 0xE0) { if (frm_end-frm_nxt < 2) return codecvt_base::partial; uint8_t c2 = frm_nxt[1]; if ((c2 & 0xC0) != 0x80) return codecvt_base::error; uint16_t t = static_cast<uint16_t>(((c1 & 0x1F) << 6) | (c2 & 0x3F)); if (t > Maxcode) return codecvt_base::error; *to_nxt = t; frm_nxt += 2; } else if (c1 < 0xF0) { if (frm_end-frm_nxt < 3) return codecvt_base::partial; uint8_t c2 = frm_nxt[1]; uint8_t c3 = frm_nxt[2]; switch (c1) { case 0xE0: if ((c2 & 0xE0) != 0xA0) return codecvt_base::error; break; case 0xED: if ((c2 & 0xE0) != 0x80) return codecvt_base::error; break; default: if ((c2 & 0xC0) != 0x80) return codecvt_base::error; break; } if ((c3 & 0xC0) != 0x80) return codecvt_base::error; uint16_t t = static_cast<uint16_t>(((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F)); if (t > Maxcode) return codecvt_base::error; *to_nxt = t; frm_nxt += 3; } else if (c1 < 0xF5) { if (frm_end-frm_nxt < 4) return codecvt_base::partial; uint8_t c2 = frm_nxt[1]; uint8_t c3 = frm_nxt[2]; uint8_t c4 = frm_nxt[3]; switch (c1) { case 0xF0: if (!(0x90 <= c2 && c2 <= 0xBF)) return codecvt_base::error; break; case 0xF4: if ((c2 & 0xF0) != 0x80) return codecvt_base::error; break; default: if ((c2 & 0xC0) != 0x80) return codecvt_base::error; break; } if ((c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80) return codecvt_base::error; if (to_end-to_nxt < 2) return codecvt_base::partial; if ((((c1 & 7UL) << 18) + ((c2 & 0x3FUL) << 12) + ((c3 & 0x3FUL) << 6) + (c4 & 0x3F)) > Maxcode) return codecvt_base::error; *to_nxt = static_cast<uint16_t>( 0xD800 | (((((c1 & 0x07) << 2) | ((c2 & 0x30) >> 4)) - 1) << 6) | ((c2 & 0x0F) << 2) | ((c3 & 0x30) >> 4)); *++to_nxt = static_cast<uint16_t>( 0xDC00 | ((c3 & 0x0F) << 6) | (c4 & 0x3F)); frm_nxt += 4; } else { return codecvt_base::error; } } return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok; } static codecvt_base::result utf8_to_utf16(const uint8_t* frm, const uint8_t* frm_end, const uint8_t*& frm_nxt, uint32_t* to, uint32_t* to_end, uint32_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & consume_header) { if (frm_end-frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF) frm_nxt += 3; } for (; frm_nxt < frm_end && to_nxt < to_end; ++to_nxt) { uint8_t c1 = *frm_nxt; if (c1 > Maxcode) return codecvt_base::error; if (c1 < 0x80) { *to_nxt = static_cast<uint32_t>(c1); ++frm_nxt; } else if (c1 < 0xC2) { return codecvt_base::error; } else if (c1 < 0xE0) { if (frm_end-frm_nxt < 2) return codecvt_base::partial; uint8_t c2 = frm_nxt[1]; if ((c2 & 0xC0) != 0x80) return codecvt_base::error; uint16_t t = static_cast<uint16_t>(((c1 & 0x1F) << 6) | (c2 & 0x3F)); if (t > Maxcode) return codecvt_base::error; *to_nxt = static_cast<uint32_t>(t); frm_nxt += 2; } else if (c1 < 0xF0) { if (frm_end-frm_nxt < 3) return codecvt_base::partial; uint8_t c2 = frm_nxt[1]; uint8_t c3 = frm_nxt[2]; switch (c1) { case 0xE0: if ((c2 & 0xE0) != 0xA0) return codecvt_base::error; break; case 0xED: if ((c2 & 0xE0) != 0x80) return codecvt_base::error; break; default: if ((c2 & 0xC0) != 0x80) return codecvt_base::error; break; } if ((c3 & 0xC0) != 0x80) return codecvt_base::error; uint16_t t = static_cast<uint16_t>(((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F)); if (t > Maxcode) return codecvt_base::error; *to_nxt = static_cast<uint32_t>(t); frm_nxt += 3; } else if (c1 < 0xF5) { if (frm_end-frm_nxt < 4) return codecvt_base::partial; uint8_t c2 = frm_nxt[1]; uint8_t c3 = frm_nxt[2]; uint8_t c4 = frm_nxt[3]; switch (c1) { case 0xF0: if (!(0x90 <= c2 && c2 <= 0xBF)) return codecvt_base::error; break; case 0xF4: if ((c2 & 0xF0) != 0x80) return codecvt_base::error; break; default: if ((c2 & 0xC0) != 0x80) return codecvt_base::error; break; } if ((c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80) return codecvt_base::error; if (to_end-to_nxt < 2) return codecvt_base::partial; if ((((c1 & 7UL) << 18) + ((c2 & 0x3FUL) << 12) + ((c3 & 0x3FUL) << 6) + (c4 & 0x3F)) > Maxcode) return codecvt_base::error; *to_nxt = static_cast<uint32_t>( 0xD800 | (((((c1 & 0x07) << 2) | ((c2 & 0x30) >> 4)) - 1) << 6) | ((c2 & 0x0F) << 2) | ((c3 & 0x30) >> 4)); *++to_nxt = static_cast<uint32_t>( 0xDC00 | ((c3 & 0x0F) << 6) | (c4 & 0x3F)); frm_nxt += 4; } else { return codecvt_base::error; } } return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok; } static int utf8_to_utf16_length(const uint8_t* frm, const uint8_t* frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { const uint8_t* frm_nxt = frm; if (mode & consume_header) { if (frm_end-frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF) frm_nxt += 3; } for (size_t nchar16_t = 0; frm_nxt < frm_end && nchar16_t < mx; ++nchar16_t) { uint8_t c1 = *frm_nxt; if (c1 > Maxcode) break; if (c1 < 0x80) { ++frm_nxt; } else if (c1 < 0xC2) { break; } else if (c1 < 0xE0) { if ((frm_end-frm_nxt < 2) || (frm_nxt[1] & 0xC0) != 0x80) break; uint16_t t = static_cast<uint16_t>(((c1 & 0x1F) << 6) | (frm_nxt[1] & 0x3F)); if (t > Maxcode) break; frm_nxt += 2; } else if (c1 < 0xF0) { if (frm_end-frm_nxt < 3) break; uint8_t c2 = frm_nxt[1]; uint8_t c3 = frm_nxt[2]; switch (c1) { case 0xE0: if ((c2 & 0xE0) != 0xA0) return static_cast<int>(frm_nxt - frm); break; case 0xED: if ((c2 & 0xE0) != 0x80) return static_cast<int>(frm_nxt - frm); break; default: if ((c2 & 0xC0) != 0x80) return static_cast<int>(frm_nxt - frm); break; } if ((c3 & 0xC0) != 0x80) break; if ((((c1 & 0x0Fu) << 12) | ((c2 & 0x3Fu) << 6) | (c3 & 0x3Fu)) > Maxcode) break; frm_nxt += 3; } else if (c1 < 0xF5) { if (frm_end-frm_nxt < 4 || mx-nchar16_t < 2) break; uint8_t c2 = frm_nxt[1]; uint8_t c3 = frm_nxt[2]; uint8_t c4 = frm_nxt[3]; switch (c1) { case 0xF0: if (!(0x90 <= c2 && c2 <= 0xBF)) return static_cast<int>(frm_nxt - frm); break; case 0xF4: if ((c2 & 0xF0) != 0x80) return static_cast<int>(frm_nxt - frm); break; default: if ((c2 & 0xC0) != 0x80) return static_cast<int>(frm_nxt - frm); break; } if ((c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80) break; if ((((c1 & 7UL) << 18) + ((c2 & 0x3FUL) << 12) + ((c3 & 0x3FUL) << 6) + (c4 & 0x3F)) > Maxcode) break; ++nchar16_t; frm_nxt += 4; } else { break; } } return static_cast<int>(frm_nxt - frm); } static codecvt_base::result ucs4_to_utf8(const uint32_t* frm, const uint32_t* frm_end, const uint32_t*& frm_nxt, uint8_t* to, uint8_t* to_end, uint8_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & generate_header) { if (to_end-to_nxt < 3) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xEF); *to_nxt++ = static_cast<uint8_t>(0xBB); *to_nxt++ = static_cast<uint8_t>(0xBF); } for (; frm_nxt < frm_end; ++frm_nxt) { uint32_t wc = *frm_nxt; if ((wc & 0xFFFFF800) == 0x00D800 || wc > Maxcode) return codecvt_base::error; if (wc < 0x000080) { if (to_end-to_nxt < 1) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(wc); } else if (wc < 0x000800) { if (to_end-to_nxt < 2) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xC0 | (wc >> 6)); *to_nxt++ = static_cast<uint8_t>(0x80 | (wc & 0x03F)); } else if (wc < 0x010000) { if (to_end-to_nxt < 3) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xE0 | (wc >> 12)); *to_nxt++ = static_cast<uint8_t>(0x80 | ((wc & 0x0FC0) >> 6)); *to_nxt++ = static_cast<uint8_t>(0x80 | (wc & 0x003F)); } else // if (wc < 0x110000) { if (to_end-to_nxt < 4) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xF0 | (wc >> 18)); *to_nxt++ = static_cast<uint8_t>(0x80 | ((wc & 0x03F000) >> 12)); *to_nxt++ = static_cast<uint8_t>(0x80 | ((wc & 0x000FC0) >> 6)); *to_nxt++ = static_cast<uint8_t>(0x80 | (wc & 0x00003F)); } } return codecvt_base::ok; } static codecvt_base::result utf8_to_ucs4(const uint8_t* frm, const uint8_t* frm_end, const uint8_t*& frm_nxt, uint32_t* to, uint32_t* to_end, uint32_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & consume_header) { if (frm_end-frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF) frm_nxt += 3; } for (; frm_nxt < frm_end && to_nxt < to_end; ++to_nxt) { uint8_t c1 = static_cast<uint8_t>(*frm_nxt); if (c1 < 0x80) { if (c1 > Maxcode) return codecvt_base::error; *to_nxt = static_cast<uint32_t>(c1); ++frm_nxt; } else if (c1 < 0xC2) { return codecvt_base::error; } else if (c1 < 0xE0) { if (frm_end-frm_nxt < 2) return codecvt_base::partial; uint8_t c2 = frm_nxt[1]; if ((c2 & 0xC0) != 0x80) return codecvt_base::error; uint32_t t = static_cast<uint32_t>(((c1 & 0x1F) << 6) | (c2 & 0x3F)); if (t > Maxcode) return codecvt_base::error; *to_nxt = t; frm_nxt += 2; } else if (c1 < 0xF0) { if (frm_end-frm_nxt < 3) return codecvt_base::partial; uint8_t c2 = frm_nxt[1]; uint8_t c3 = frm_nxt[2]; switch (c1) { case 0xE0: if ((c2 & 0xE0) != 0xA0) return codecvt_base::error; break; case 0xED: if ((c2 & 0xE0) != 0x80) return codecvt_base::error; break; default: if ((c2 & 0xC0) != 0x80) return codecvt_base::error; break; } if ((c3 & 0xC0) != 0x80) return codecvt_base::error; uint32_t t = static_cast<uint32_t>(((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F)); if (t > Maxcode) return codecvt_base::error; *to_nxt = t; frm_nxt += 3; } else if (c1 < 0xF5) { if (frm_end-frm_nxt < 4) return codecvt_base::partial; uint8_t c2 = frm_nxt[1]; uint8_t c3 = frm_nxt[2]; uint8_t c4 = frm_nxt[3]; switch (c1) { case 0xF0: if (!(0x90 <= c2 && c2 <= 0xBF)) return codecvt_base::error; break; case 0xF4: if ((c2 & 0xF0) != 0x80) return codecvt_base::error; break; default: if ((c2 & 0xC0) != 0x80) return codecvt_base::error; break; } if ((c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80) return codecvt_base::error; uint32_t t = static_cast<uint32_t>(((c1 & 0x07) << 18) | ((c2 & 0x3F) << 12) | ((c3 & 0x3F) << 6) | (c4 & 0x3F)); if (t > Maxcode) return codecvt_base::error; *to_nxt = t; frm_nxt += 4; } else { return codecvt_base::error; } } return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok; } static int utf8_to_ucs4_length(const uint8_t* frm, const uint8_t* frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { const uint8_t* frm_nxt = frm; if (mode & consume_header) { if (frm_end-frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF) frm_nxt += 3; } for (size_t nchar32_t = 0; frm_nxt < frm_end && nchar32_t < mx; ++nchar32_t) { uint8_t c1 = static_cast<uint8_t>(*frm_nxt); if (c1 < 0x80) { if (c1 > Maxcode) break; ++frm_nxt; } else if (c1 < 0xC2) { break; } else if (c1 < 0xE0) { if ((frm_end-frm_nxt < 2) || ((frm_nxt[1] & 0xC0) != 0x80)) break; if ((((c1 & 0x1Fu) << 6) | (frm_nxt[1] & 0x3Fu)) > Maxcode) break; frm_nxt += 2; } else if (c1 < 0xF0) { if (frm_end-frm_nxt < 3) break; uint8_t c2 = frm_nxt[1]; uint8_t c3 = frm_nxt[2]; switch (c1) { case 0xE0: if ((c2 & 0xE0) != 0xA0) return static_cast<int>(frm_nxt - frm); break; case 0xED: if ((c2 & 0xE0) != 0x80) return static_cast<int>(frm_nxt - frm); break; default: if ((c2 & 0xC0) != 0x80) return static_cast<int>(frm_nxt - frm); break; } if ((c3 & 0xC0) != 0x80) break; if ((((c1 & 0x0Fu) << 12) | ((c2 & 0x3Fu) << 6) | (c3 & 0x3Fu)) > Maxcode) break; frm_nxt += 3; } else if (c1 < 0xF5) { if (frm_end-frm_nxt < 4) break; uint8_t c2 = frm_nxt[1]; uint8_t c3 = frm_nxt[2]; uint8_t c4 = frm_nxt[3]; switch (c1) { case 0xF0: if (!(0x90 <= c2 && c2 <= 0xBF)) return static_cast<int>(frm_nxt - frm); break; case 0xF4: if ((c2 & 0xF0) != 0x80) return static_cast<int>(frm_nxt - frm); break; default: if ((c2 & 0xC0) != 0x80) return static_cast<int>(frm_nxt - frm); break; } if ((c3 & 0xC0) != 0x80 || (c4 & 0xC0) != 0x80) break; if ((((c1 & 0x07u) << 18) | ((c2 & 0x3Fu) << 12) | ((c3 & 0x3Fu) << 6) | (c4 & 0x3Fu)) > Maxcode) break; frm_nxt += 4; } else { break; } } return static_cast<int>(frm_nxt - frm); } static codecvt_base::result ucs2_to_utf8(const uint16_t* frm, const uint16_t* frm_end, const uint16_t*& frm_nxt, uint8_t* to, uint8_t* to_end, uint8_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & generate_header) { if (to_end-to_nxt < 3) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xEF); *to_nxt++ = static_cast<uint8_t>(0xBB); *to_nxt++ = static_cast<uint8_t>(0xBF); } for (; frm_nxt < frm_end; ++frm_nxt) { uint16_t wc = *frm_nxt; if ((wc & 0xF800) == 0xD800 || wc > Maxcode) return codecvt_base::error; if (wc < 0x0080) { if (to_end-to_nxt < 1) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(wc); } else if (wc < 0x0800) { if (to_end-to_nxt < 2) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xC0 | (wc >> 6)); *to_nxt++ = static_cast<uint8_t>(0x80 | (wc & 0x03F)); } else // if (wc <= 0xFFFF) { if (to_end-to_nxt < 3) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xE0 | (wc >> 12)); *to_nxt++ = static_cast<uint8_t>(0x80 | ((wc & 0x0FC0) >> 6)); *to_nxt++ = static_cast<uint8_t>(0x80 | (wc & 0x003F)); } } return codecvt_base::ok; } static codecvt_base::result utf8_to_ucs2(const uint8_t* frm, const uint8_t* frm_end, const uint8_t*& frm_nxt, uint16_t* to, uint16_t* to_end, uint16_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & consume_header) { if (frm_end-frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF) frm_nxt += 3; } for (; frm_nxt < frm_end && to_nxt < to_end; ++to_nxt) { uint8_t c1 = static_cast<uint8_t>(*frm_nxt); if (c1 < 0x80) { if (c1 > Maxcode) return codecvt_base::error; *to_nxt = static_cast<uint16_t>(c1); ++frm_nxt; } else if (c1 < 0xC2) { return codecvt_base::error; } else if (c1 < 0xE0) { if (frm_end-frm_nxt < 2) return codecvt_base::partial; uint8_t c2 = frm_nxt[1]; if ((c2 & 0xC0) != 0x80) return codecvt_base::error; uint16_t t = static_cast<uint16_t>(((c1 & 0x1F) << 6) | (c2 & 0x3F)); if (t > Maxcode) return codecvt_base::error; *to_nxt = t; frm_nxt += 2; } else if (c1 < 0xF0) { if (frm_end-frm_nxt < 3) return codecvt_base::partial; uint8_t c2 = frm_nxt[1]; uint8_t c3 = frm_nxt[2]; switch (c1) { case 0xE0: if ((c2 & 0xE0) != 0xA0) return codecvt_base::error; break; case 0xED: if ((c2 & 0xE0) != 0x80) return codecvt_base::error; break; default: if ((c2 & 0xC0) != 0x80) return codecvt_base::error; break; } if ((c3 & 0xC0) != 0x80) return codecvt_base::error; uint16_t t = static_cast<uint16_t>(((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F)); if (t > Maxcode) return codecvt_base::error; *to_nxt = t; frm_nxt += 3; } else { return codecvt_base::error; } } return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok; } static int utf8_to_ucs2_length(const uint8_t* frm, const uint8_t* frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { const uint8_t* frm_nxt = frm; if (mode & consume_header) { if (frm_end-frm_nxt >= 3 && frm_nxt[0] == 0xEF && frm_nxt[1] == 0xBB && frm_nxt[2] == 0xBF) frm_nxt += 3; } for (size_t nchar32_t = 0; frm_nxt < frm_end && nchar32_t < mx; ++nchar32_t) { uint8_t c1 = static_cast<uint8_t>(*frm_nxt); if (c1 < 0x80) { if (c1 > Maxcode) break; ++frm_nxt; } else if (c1 < 0xC2) { break; } else if (c1 < 0xE0) { if ((frm_end-frm_nxt < 2) || ((frm_nxt[1] & 0xC0) != 0x80)) break; if ((((c1 & 0x1Fu) << 6) | (frm_nxt[1] & 0x3Fu)) > Maxcode) break; frm_nxt += 2; } else if (c1 < 0xF0) { if (frm_end-frm_nxt < 3) break; uint8_t c2 = frm_nxt[1]; uint8_t c3 = frm_nxt[2]; switch (c1) { case 0xE0: if ((c2 & 0xE0) != 0xA0) return static_cast<int>(frm_nxt - frm); break; case 0xED: if ((c2 & 0xE0) != 0x80) return static_cast<int>(frm_nxt - frm); break; default: if ((c2 & 0xC0) != 0x80) return static_cast<int>(frm_nxt - frm); break; } if ((c3 & 0xC0) != 0x80) break; if ((((c1 & 0x0Fu) << 12) | ((c2 & 0x3Fu) << 6) | (c3 & 0x3Fu)) > Maxcode) break; frm_nxt += 3; } else { break; } } return static_cast<int>(frm_nxt - frm); } static codecvt_base::result ucs4_to_utf16be(const uint32_t* frm, const uint32_t* frm_end, const uint32_t*& frm_nxt, uint8_t* to, uint8_t* to_end, uint8_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & generate_header) { if (to_end-to_nxt < 2) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xFE); *to_nxt++ = static_cast<uint8_t>(0xFF); } for (; frm_nxt < frm_end; ++frm_nxt) { uint32_t wc = *frm_nxt; if ((wc & 0xFFFFF800) == 0x00D800 || wc > Maxcode) return codecvt_base::error; if (wc < 0x010000) { if (to_end-to_nxt < 2) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(wc >> 8); *to_nxt++ = static_cast<uint8_t>(wc); } else { if (to_end-to_nxt < 4) return codecvt_base::partial; uint16_t t = static_cast<uint16_t>( 0xD800 | ((((wc & 0x1F0000) >> 16) - 1) << 6) | ((wc & 0x00FC00) >> 10)); *to_nxt++ = static_cast<uint8_t>(t >> 8); *to_nxt++ = static_cast<uint8_t>(t); t = static_cast<uint16_t>(0xDC00 | (wc & 0x03FF)); *to_nxt++ = static_cast<uint8_t>(t >> 8); *to_nxt++ = static_cast<uint8_t>(t); } } return codecvt_base::ok; } static codecvt_base::result utf16be_to_ucs4(const uint8_t* frm, const uint8_t* frm_end, const uint8_t*& frm_nxt, uint32_t* to, uint32_t* to_end, uint32_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & consume_header) { if (frm_end-frm_nxt >= 2 && frm_nxt[0] == 0xFE && frm_nxt[1] == 0xFF) frm_nxt += 2; } for (; frm_nxt < frm_end - 1 && to_nxt < to_end; ++to_nxt) { uint16_t c1 = static_cast<uint16_t>(frm_nxt[0] << 8 | frm_nxt[1]); if ((c1 & 0xFC00) == 0xDC00) return codecvt_base::error; if ((c1 & 0xFC00) != 0xD800) { if (c1 > Maxcode) return codecvt_base::error; *to_nxt = static_cast<uint32_t>(c1); frm_nxt += 2; } else { if (frm_end-frm_nxt < 4) return codecvt_base::partial; uint16_t c2 = static_cast<uint16_t>(frm_nxt[2] << 8 | frm_nxt[3]); if ((c2 & 0xFC00) != 0xDC00) return codecvt_base::error; uint32_t t = static_cast<uint32_t>( ((((c1 & 0x03C0) >> 6) + 1) << 16) | ((c1 & 0x003F) << 10) | (c2 & 0x03FF)); if (t > Maxcode) return codecvt_base::error; *to_nxt = t; frm_nxt += 4; } } return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok; } static int utf16be_to_ucs4_length(const uint8_t* frm, const uint8_t* frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { const uint8_t* frm_nxt = frm; if (mode & consume_header) { if (frm_end-frm_nxt >= 2 && frm_nxt[0] == 0xFE && frm_nxt[1] == 0xFF) frm_nxt += 2; } for (size_t nchar32_t = 0; frm_nxt < frm_end - 1 && nchar32_t < mx; ++nchar32_t) { uint16_t c1 = static_cast<uint16_t>(frm_nxt[0] << 8 | frm_nxt[1]); if ((c1 & 0xFC00) == 0xDC00) break; if ((c1 & 0xFC00) != 0xD800) { if (c1 > Maxcode) break; frm_nxt += 2; } else { if (frm_end-frm_nxt < 4) break; uint16_t c2 = static_cast<uint16_t>(frm_nxt[2] << 8 | frm_nxt[3]); if ((c2 & 0xFC00) != 0xDC00) break; uint32_t t = static_cast<uint32_t>( ((((c1 & 0x03C0) >> 6) + 1) << 16) | ((c1 & 0x003F) << 10) | (c2 & 0x03FF)); if (t > Maxcode) break; frm_nxt += 4; } } return static_cast<int>(frm_nxt - frm); } static codecvt_base::result ucs4_to_utf16le(const uint32_t* frm, const uint32_t* frm_end, const uint32_t*& frm_nxt, uint8_t* to, uint8_t* to_end, uint8_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & generate_header) { if (to_end - to_nxt < 2) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xFF); *to_nxt++ = static_cast<uint8_t>(0xFE); } for (; frm_nxt < frm_end; ++frm_nxt) { uint32_t wc = *frm_nxt; if ((wc & 0xFFFFF800) == 0x00D800 || wc > Maxcode) return codecvt_base::error; if (wc < 0x010000) { if (to_end-to_nxt < 2) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(wc); *to_nxt++ = static_cast<uint8_t>(wc >> 8); } else { if (to_end-to_nxt < 4) return codecvt_base::partial; uint16_t t = static_cast<uint16_t>( 0xD800 | ((((wc & 0x1F0000) >> 16) - 1) << 6) | ((wc & 0x00FC00) >> 10)); *to_nxt++ = static_cast<uint8_t>(t); *to_nxt++ = static_cast<uint8_t>(t >> 8); t = static_cast<uint16_t>(0xDC00 | (wc & 0x03FF)); *to_nxt++ = static_cast<uint8_t>(t); *to_nxt++ = static_cast<uint8_t>(t >> 8); } } return codecvt_base::ok; } static codecvt_base::result utf16le_to_ucs4(const uint8_t* frm, const uint8_t* frm_end, const uint8_t*& frm_nxt, uint32_t* to, uint32_t* to_end, uint32_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & consume_header) { if (frm_end-frm_nxt >= 2 && frm_nxt[0] == 0xFF && frm_nxt[1] == 0xFE) frm_nxt += 2; } for (; frm_nxt < frm_end - 1 && to_nxt < to_end; ++to_nxt) { uint16_t c1 = static_cast<uint16_t>(frm_nxt[1] << 8 | frm_nxt[0]); if ((c1 & 0xFC00) == 0xDC00) return codecvt_base::error; if ((c1 & 0xFC00) != 0xD800) { if (c1 > Maxcode) return codecvt_base::error; *to_nxt = static_cast<uint32_t>(c1); frm_nxt += 2; } else { if (frm_end-frm_nxt < 4) return codecvt_base::partial; uint16_t c2 = static_cast<uint16_t>(frm_nxt[3] << 8 | frm_nxt[2]); if ((c2 & 0xFC00) != 0xDC00) return codecvt_base::error; uint32_t t = static_cast<uint32_t>( ((((c1 & 0x03C0) >> 6) + 1) << 16) | ((c1 & 0x003F) << 10) | (c2 & 0x03FF)); if (t > Maxcode) return codecvt_base::error; *to_nxt = t; frm_nxt += 4; } } return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok; } static int utf16le_to_ucs4_length(const uint8_t* frm, const uint8_t* frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { const uint8_t* frm_nxt = frm; if (mode & consume_header) { if (frm_end-frm_nxt >= 2 && frm_nxt[0] == 0xFF && frm_nxt[1] == 0xFE) frm_nxt += 2; } for (size_t nchar32_t = 0; frm_nxt < frm_end - 1 && nchar32_t < mx; ++nchar32_t) { uint16_t c1 = static_cast<uint16_t>(frm_nxt[1] << 8 | frm_nxt[0]); if ((c1 & 0xFC00) == 0xDC00) break; if ((c1 & 0xFC00) != 0xD800) { if (c1 > Maxcode) break; frm_nxt += 2; } else { if (frm_end-frm_nxt < 4) break; uint16_t c2 = static_cast<uint16_t>(frm_nxt[3] << 8 | frm_nxt[2]); if ((c2 & 0xFC00) != 0xDC00) break; uint32_t t = static_cast<uint32_t>( ((((c1 & 0x03C0) >> 6) + 1) << 16) | ((c1 & 0x003F) << 10) | (c2 & 0x03FF)); if (t > Maxcode) break; frm_nxt += 4; } } return static_cast<int>(frm_nxt - frm); } static codecvt_base::result ucs2_to_utf16be(const uint16_t* frm, const uint16_t* frm_end, const uint16_t*& frm_nxt, uint8_t* to, uint8_t* to_end, uint8_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & generate_header) { if (to_end-to_nxt < 2) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xFE); *to_nxt++ = static_cast<uint8_t>(0xFF); } for (; frm_nxt < frm_end; ++frm_nxt) { uint16_t wc = *frm_nxt; if ((wc & 0xF800) == 0xD800 || wc > Maxcode) return codecvt_base::error; if (to_end-to_nxt < 2) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(wc >> 8); *to_nxt++ = static_cast<uint8_t>(wc); } return codecvt_base::ok; } static codecvt_base::result utf16be_to_ucs2(const uint8_t* frm, const uint8_t* frm_end, const uint8_t*& frm_nxt, uint16_t* to, uint16_t* to_end, uint16_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & consume_header) { if (frm_end-frm_nxt >= 2 && frm_nxt[0] == 0xFE && frm_nxt[1] == 0xFF) frm_nxt += 2; } for (; frm_nxt < frm_end - 1 && to_nxt < to_end; ++to_nxt) { uint16_t c1 = static_cast<uint16_t>(frm_nxt[0] << 8 | frm_nxt[1]); if ((c1 & 0xF800) == 0xD800 || c1 > Maxcode) return codecvt_base::error; *to_nxt = c1; frm_nxt += 2; } return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok; } static int utf16be_to_ucs2_length(const uint8_t* frm, const uint8_t* frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { const uint8_t* frm_nxt = frm; if (mode & consume_header) { if (frm_end-frm_nxt >= 2 && frm_nxt[0] == 0xFE && frm_nxt[1] == 0xFF) frm_nxt += 2; } for (size_t nchar16_t = 0; frm_nxt < frm_end - 1 && nchar16_t < mx; ++nchar16_t) { uint16_t c1 = static_cast<uint16_t>(frm_nxt[0] << 8 | frm_nxt[1]); if ((c1 & 0xF800) == 0xD800 || c1 > Maxcode) break; frm_nxt += 2; } return static_cast<int>(frm_nxt - frm); } static codecvt_base::result ucs2_to_utf16le(const uint16_t* frm, const uint16_t* frm_end, const uint16_t*& frm_nxt, uint8_t* to, uint8_t* to_end, uint8_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & generate_header) { if (to_end-to_nxt < 2) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(0xFF); *to_nxt++ = static_cast<uint8_t>(0xFE); } for (; frm_nxt < frm_end; ++frm_nxt) { uint16_t wc = *frm_nxt; if ((wc & 0xF800) == 0xD800 || wc > Maxcode) return codecvt_base::error; if (to_end-to_nxt < 2) return codecvt_base::partial; *to_nxt++ = static_cast<uint8_t>(wc); *to_nxt++ = static_cast<uint8_t>(wc >> 8); } return codecvt_base::ok; } static codecvt_base::result utf16le_to_ucs2(const uint8_t* frm, const uint8_t* frm_end, const uint8_t*& frm_nxt, uint16_t* to, uint16_t* to_end, uint16_t*& to_nxt, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { frm_nxt = frm; to_nxt = to; if (mode & consume_header) { if (frm_end-frm_nxt >= 2 && frm_nxt[0] == 0xFF && frm_nxt[1] == 0xFE) frm_nxt += 2; } for (; frm_nxt < frm_end - 1 && to_nxt < to_end; ++to_nxt) { uint16_t c1 = static_cast<uint16_t>(frm_nxt[1] << 8 | frm_nxt[0]); if ((c1 & 0xF800) == 0xD800 || c1 > Maxcode) return codecvt_base::error; *to_nxt = c1; frm_nxt += 2; } return frm_nxt < frm_end ? codecvt_base::partial : codecvt_base::ok; } static int utf16le_to_ucs2_length(const uint8_t* frm, const uint8_t* frm_end, size_t mx, unsigned long Maxcode = 0x10FFFF, codecvt_mode mode = codecvt_mode(0)) { const uint8_t* frm_nxt = frm; frm_nxt = frm; if (mode & consume_header) { if (frm_end-frm_nxt >= 2 && frm_nxt[0] == 0xFF && frm_nxt[1] == 0xFE) frm_nxt += 2; } for (size_t nchar16_t = 0; frm_nxt < frm_end - 1 && nchar16_t < mx; ++nchar16_t) { uint16_t c1 = static_cast<uint16_t>(frm_nxt[1] << 8 | frm_nxt[0]); if ((c1 & 0xF800) == 0xD800 || c1 > Maxcode) break; frm_nxt += 2; } return static_cast<int>(frm_nxt - frm); } // template <> class codecvt<char16_t, char, mbstate_t> locale::id codecvt<char16_t, char, mbstate_t>::id; codecvt<char16_t, char, mbstate_t>::~codecvt() { } codecvt<char16_t, char, mbstate_t>::result codecvt<char16_t, char, mbstate_t>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { const uint16_t* _frm = reinterpret_cast<const uint16_t*>(frm); const uint16_t* _frm_end = reinterpret_cast<const uint16_t*>(frm_end); const uint16_t* _frm_nxt = _frm; uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; result r = utf16_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } codecvt<char16_t, char, mbstate_t>::result codecvt<char16_t, char, mbstate_t>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; uint16_t* _to = reinterpret_cast<uint16_t*>(to); uint16_t* _to_end = reinterpret_cast<uint16_t*>(to_end); uint16_t* _to_nxt = _to; result r = utf8_to_utf16(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } codecvt<char16_t, char, mbstate_t>::result codecvt<char16_t, char, mbstate_t>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int codecvt<char16_t, char, mbstate_t>::do_encoding() const _NOEXCEPT { return 0; } bool codecvt<char16_t, char, mbstate_t>::do_always_noconv() const _NOEXCEPT { return false; } int codecvt<char16_t, char, mbstate_t>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf8_to_utf16_length(_frm, _frm_end, mx); } int codecvt<char16_t, char, mbstate_t>::do_max_length() const _NOEXCEPT { return 4; } // template <> class codecvt<char32_t, char, mbstate_t> locale::id codecvt<char32_t, char, mbstate_t>::id; codecvt<char32_t, char, mbstate_t>::~codecvt() { } codecvt<char32_t, char, mbstate_t>::result codecvt<char32_t, char, mbstate_t>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { const uint32_t* _frm = reinterpret_cast<const uint32_t*>(frm); const uint32_t* _frm_end = reinterpret_cast<const uint32_t*>(frm_end); const uint32_t* _frm_nxt = _frm; uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; result r = ucs4_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } codecvt<char32_t, char, mbstate_t>::result codecvt<char32_t, char, mbstate_t>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; uint32_t* _to = reinterpret_cast<uint32_t*>(to); uint32_t* _to_end = reinterpret_cast<uint32_t*>(to_end); uint32_t* _to_nxt = _to; result r = utf8_to_ucs4(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } codecvt<char32_t, char, mbstate_t>::result codecvt<char32_t, char, mbstate_t>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int codecvt<char32_t, char, mbstate_t>::do_encoding() const _NOEXCEPT { return 0; } bool codecvt<char32_t, char, mbstate_t>::do_always_noconv() const _NOEXCEPT { return false; } int codecvt<char32_t, char, mbstate_t>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf8_to_ucs4_length(_frm, _frm_end, mx); } int codecvt<char32_t, char, mbstate_t>::do_max_length() const _NOEXCEPT { return 4; } // __codecvt_utf8<wchar_t> __codecvt_utf8<wchar_t>::result __codecvt_utf8<wchar_t>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { #if defined(_LIBCPP_SHORT_WCHAR) const uint16_t* _frm = reinterpret_cast<const uint16_t*>(frm); const uint16_t* _frm_end = reinterpret_cast<const uint16_t*>(frm_end); const uint16_t* _frm_nxt = _frm; #else const uint32_t* _frm = reinterpret_cast<const uint32_t*>(frm); const uint32_t* _frm_end = reinterpret_cast<const uint32_t*>(frm_end); const uint32_t* _frm_nxt = _frm; #endif uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; #if defined(_LIBCPP_SHORT_WCHAR) result r = ucs2_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); #else result r = ucs4_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); #endif frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf8<wchar_t>::result __codecvt_utf8<wchar_t>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; #if defined(_LIBCPP_SHORT_WCHAR) uint16_t* _to = reinterpret_cast<uint16_t*>(to); uint16_t* _to_end = reinterpret_cast<uint16_t*>(to_end); uint16_t* _to_nxt = _to; result r = utf8_to_ucs2(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); #else uint32_t* _to = reinterpret_cast<uint32_t*>(to); uint32_t* _to_end = reinterpret_cast<uint32_t*>(to_end); uint32_t* _to_nxt = _to; result r = utf8_to_ucs4(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); #endif frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf8<wchar_t>::result __codecvt_utf8<wchar_t>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int __codecvt_utf8<wchar_t>::do_encoding() const _NOEXCEPT { return 0; } bool __codecvt_utf8<wchar_t>::do_always_noconv() const _NOEXCEPT { return false; } int __codecvt_utf8<wchar_t>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf8_to_ucs4_length(_frm, _frm_end, mx, _Maxcode_, _Mode_); } int __codecvt_utf8<wchar_t>::do_max_length() const _NOEXCEPT { if (_Mode_ & consume_header) return 7; return 4; } // __codecvt_utf8<char16_t> __codecvt_utf8<char16_t>::result __codecvt_utf8<char16_t>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { const uint16_t* _frm = reinterpret_cast<const uint16_t*>(frm); const uint16_t* _frm_end = reinterpret_cast<const uint16_t*>(frm_end); const uint16_t* _frm_nxt = _frm; uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; result r = ucs2_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf8<char16_t>::result __codecvt_utf8<char16_t>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; uint16_t* _to = reinterpret_cast<uint16_t*>(to); uint16_t* _to_end = reinterpret_cast<uint16_t*>(to_end); uint16_t* _to_nxt = _to; result r = utf8_to_ucs2(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf8<char16_t>::result __codecvt_utf8<char16_t>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int __codecvt_utf8<char16_t>::do_encoding() const _NOEXCEPT { return 0; } bool __codecvt_utf8<char16_t>::do_always_noconv() const _NOEXCEPT { return false; } int __codecvt_utf8<char16_t>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf8_to_ucs2_length(_frm, _frm_end, mx, _Maxcode_, _Mode_); } int __codecvt_utf8<char16_t>::do_max_length() const _NOEXCEPT { if (_Mode_ & consume_header) return 6; return 3; } // __codecvt_utf8<char32_t> __codecvt_utf8<char32_t>::result __codecvt_utf8<char32_t>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { const uint32_t* _frm = reinterpret_cast<const uint32_t*>(frm); const uint32_t* _frm_end = reinterpret_cast<const uint32_t*>(frm_end); const uint32_t* _frm_nxt = _frm; uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; result r = ucs4_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf8<char32_t>::result __codecvt_utf8<char32_t>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; uint32_t* _to = reinterpret_cast<uint32_t*>(to); uint32_t* _to_end = reinterpret_cast<uint32_t*>(to_end); uint32_t* _to_nxt = _to; result r = utf8_to_ucs4(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf8<char32_t>::result __codecvt_utf8<char32_t>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int __codecvt_utf8<char32_t>::do_encoding() const _NOEXCEPT { return 0; } bool __codecvt_utf8<char32_t>::do_always_noconv() const _NOEXCEPT { return false; } int __codecvt_utf8<char32_t>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf8_to_ucs4_length(_frm, _frm_end, mx, _Maxcode_, _Mode_); } int __codecvt_utf8<char32_t>::do_max_length() const _NOEXCEPT { if (_Mode_ & consume_header) return 7; return 4; } // __codecvt_utf16<wchar_t, false> __codecvt_utf16<wchar_t, false>::result __codecvt_utf16<wchar_t, false>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { const uint32_t* _frm = reinterpret_cast<const uint32_t*>(frm); const uint32_t* _frm_end = reinterpret_cast<const uint32_t*>(frm_end); const uint32_t* _frm_nxt = _frm; uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; result r = ucs4_to_utf16be(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf16<wchar_t, false>::result __codecvt_utf16<wchar_t, false>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; uint32_t* _to = reinterpret_cast<uint32_t*>(to); uint32_t* _to_end = reinterpret_cast<uint32_t*>(to_end); uint32_t* _to_nxt = _to; result r = utf16be_to_ucs4(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf16<wchar_t, false>::result __codecvt_utf16<wchar_t, false>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int __codecvt_utf16<wchar_t, false>::do_encoding() const _NOEXCEPT { return 0; } bool __codecvt_utf16<wchar_t, false>::do_always_noconv() const _NOEXCEPT { return false; } int __codecvt_utf16<wchar_t, false>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf16be_to_ucs4_length(_frm, _frm_end, mx, _Maxcode_, _Mode_); } int __codecvt_utf16<wchar_t, false>::do_max_length() const _NOEXCEPT { if (_Mode_ & consume_header) return 6; return 4; } // __codecvt_utf16<wchar_t, true> __codecvt_utf16<wchar_t, true>::result __codecvt_utf16<wchar_t, true>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { const uint32_t* _frm = reinterpret_cast<const uint32_t*>(frm); const uint32_t* _frm_end = reinterpret_cast<const uint32_t*>(frm_end); const uint32_t* _frm_nxt = _frm; uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; result r = ucs4_to_utf16le(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf16<wchar_t, true>::result __codecvt_utf16<wchar_t, true>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; uint32_t* _to = reinterpret_cast<uint32_t*>(to); uint32_t* _to_end = reinterpret_cast<uint32_t*>(to_end); uint32_t* _to_nxt = _to; result r = utf16le_to_ucs4(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf16<wchar_t, true>::result __codecvt_utf16<wchar_t, true>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int __codecvt_utf16<wchar_t, true>::do_encoding() const _NOEXCEPT { return 0; } bool __codecvt_utf16<wchar_t, true>::do_always_noconv() const _NOEXCEPT { return false; } int __codecvt_utf16<wchar_t, true>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf16le_to_ucs4_length(_frm, _frm_end, mx, _Maxcode_, _Mode_); } int __codecvt_utf16<wchar_t, true>::do_max_length() const _NOEXCEPT { if (_Mode_ & consume_header) return 6; return 4; } // __codecvt_utf16<char16_t, false> __codecvt_utf16<char16_t, false>::result __codecvt_utf16<char16_t, false>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { const uint16_t* _frm = reinterpret_cast<const uint16_t*>(frm); const uint16_t* _frm_end = reinterpret_cast<const uint16_t*>(frm_end); const uint16_t* _frm_nxt = _frm; uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; result r = ucs2_to_utf16be(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf16<char16_t, false>::result __codecvt_utf16<char16_t, false>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; uint16_t* _to = reinterpret_cast<uint16_t*>(to); uint16_t* _to_end = reinterpret_cast<uint16_t*>(to_end); uint16_t* _to_nxt = _to; result r = utf16be_to_ucs2(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf16<char16_t, false>::result __codecvt_utf16<char16_t, false>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int __codecvt_utf16<char16_t, false>::do_encoding() const _NOEXCEPT { return 0; } bool __codecvt_utf16<char16_t, false>::do_always_noconv() const _NOEXCEPT { return false; } int __codecvt_utf16<char16_t, false>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf16be_to_ucs2_length(_frm, _frm_end, mx, _Maxcode_, _Mode_); } int __codecvt_utf16<char16_t, false>::do_max_length() const _NOEXCEPT { if (_Mode_ & consume_header) return 4; return 2; } // __codecvt_utf16<char16_t, true> __codecvt_utf16<char16_t, true>::result __codecvt_utf16<char16_t, true>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { const uint16_t* _frm = reinterpret_cast<const uint16_t*>(frm); const uint16_t* _frm_end = reinterpret_cast<const uint16_t*>(frm_end); const uint16_t* _frm_nxt = _frm; uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; result r = ucs2_to_utf16le(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf16<char16_t, true>::result __codecvt_utf16<char16_t, true>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; uint16_t* _to = reinterpret_cast<uint16_t*>(to); uint16_t* _to_end = reinterpret_cast<uint16_t*>(to_end); uint16_t* _to_nxt = _to; result r = utf16le_to_ucs2(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf16<char16_t, true>::result __codecvt_utf16<char16_t, true>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int __codecvt_utf16<char16_t, true>::do_encoding() const _NOEXCEPT { return 0; } bool __codecvt_utf16<char16_t, true>::do_always_noconv() const _NOEXCEPT { return false; } int __codecvt_utf16<char16_t, true>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf16le_to_ucs2_length(_frm, _frm_end, mx, _Maxcode_, _Mode_); } int __codecvt_utf16<char16_t, true>::do_max_length() const _NOEXCEPT { if (_Mode_ & consume_header) return 4; return 2; } // __codecvt_utf16<char32_t, false> __codecvt_utf16<char32_t, false>::result __codecvt_utf16<char32_t, false>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { const uint32_t* _frm = reinterpret_cast<const uint32_t*>(frm); const uint32_t* _frm_end = reinterpret_cast<const uint32_t*>(frm_end); const uint32_t* _frm_nxt = _frm; uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; result r = ucs4_to_utf16be(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf16<char32_t, false>::result __codecvt_utf16<char32_t, false>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; uint32_t* _to = reinterpret_cast<uint32_t*>(to); uint32_t* _to_end = reinterpret_cast<uint32_t*>(to_end); uint32_t* _to_nxt = _to; result r = utf16be_to_ucs4(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf16<char32_t, false>::result __codecvt_utf16<char32_t, false>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int __codecvt_utf16<char32_t, false>::do_encoding() const _NOEXCEPT { return 0; } bool __codecvt_utf16<char32_t, false>::do_always_noconv() const _NOEXCEPT { return false; } int __codecvt_utf16<char32_t, false>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf16be_to_ucs4_length(_frm, _frm_end, mx, _Maxcode_, _Mode_); } int __codecvt_utf16<char32_t, false>::do_max_length() const _NOEXCEPT { if (_Mode_ & consume_header) return 6; return 4; } // __codecvt_utf16<char32_t, true> __codecvt_utf16<char32_t, true>::result __codecvt_utf16<char32_t, true>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { const uint32_t* _frm = reinterpret_cast<const uint32_t*>(frm); const uint32_t* _frm_end = reinterpret_cast<const uint32_t*>(frm_end); const uint32_t* _frm_nxt = _frm; uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; result r = ucs4_to_utf16le(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf16<char32_t, true>::result __codecvt_utf16<char32_t, true>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; uint32_t* _to = reinterpret_cast<uint32_t*>(to); uint32_t* _to_end = reinterpret_cast<uint32_t*>(to_end); uint32_t* _to_nxt = _to; result r = utf16le_to_ucs4(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf16<char32_t, true>::result __codecvt_utf16<char32_t, true>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int __codecvt_utf16<char32_t, true>::do_encoding() const _NOEXCEPT { return 0; } bool __codecvt_utf16<char32_t, true>::do_always_noconv() const _NOEXCEPT { return false; } int __codecvt_utf16<char32_t, true>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf16le_to_ucs4_length(_frm, _frm_end, mx, _Maxcode_, _Mode_); } int __codecvt_utf16<char32_t, true>::do_max_length() const _NOEXCEPT { if (_Mode_ & consume_header) return 6; return 4; } // __codecvt_utf8_utf16<wchar_t> __codecvt_utf8_utf16<wchar_t>::result __codecvt_utf8_utf16<wchar_t>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { const uint32_t* _frm = reinterpret_cast<const uint32_t*>(frm); const uint32_t* _frm_end = reinterpret_cast<const uint32_t*>(frm_end); const uint32_t* _frm_nxt = _frm; uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; result r = utf16_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf8_utf16<wchar_t>::result __codecvt_utf8_utf16<wchar_t>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; uint32_t* _to = reinterpret_cast<uint32_t*>(to); uint32_t* _to_end = reinterpret_cast<uint32_t*>(to_end); uint32_t* _to_nxt = _to; result r = utf8_to_utf16(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf8_utf16<wchar_t>::result __codecvt_utf8_utf16<wchar_t>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int __codecvt_utf8_utf16<wchar_t>::do_encoding() const _NOEXCEPT { return 0; } bool __codecvt_utf8_utf16<wchar_t>::do_always_noconv() const _NOEXCEPT { return false; } int __codecvt_utf8_utf16<wchar_t>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf8_to_utf16_length(_frm, _frm_end, mx, _Maxcode_, _Mode_); } int __codecvt_utf8_utf16<wchar_t>::do_max_length() const _NOEXCEPT { if (_Mode_ & consume_header) return 7; return 4; } // __codecvt_utf8_utf16<char16_t> __codecvt_utf8_utf16<char16_t>::result __codecvt_utf8_utf16<char16_t>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { const uint16_t* _frm = reinterpret_cast<const uint16_t*>(frm); const uint16_t* _frm_end = reinterpret_cast<const uint16_t*>(frm_end); const uint16_t* _frm_nxt = _frm; uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; result r = utf16_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf8_utf16<char16_t>::result __codecvt_utf8_utf16<char16_t>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; uint16_t* _to = reinterpret_cast<uint16_t*>(to); uint16_t* _to_end = reinterpret_cast<uint16_t*>(to_end); uint16_t* _to_nxt = _to; result r = utf8_to_utf16(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf8_utf16<char16_t>::result __codecvt_utf8_utf16<char16_t>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int __codecvt_utf8_utf16<char16_t>::do_encoding() const _NOEXCEPT { return 0; } bool __codecvt_utf8_utf16<char16_t>::do_always_noconv() const _NOEXCEPT { return false; } int __codecvt_utf8_utf16<char16_t>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf8_to_utf16_length(_frm, _frm_end, mx, _Maxcode_, _Mode_); } int __codecvt_utf8_utf16<char16_t>::do_max_length() const _NOEXCEPT { if (_Mode_ & consume_header) return 7; return 4; } // __codecvt_utf8_utf16<char32_t> __codecvt_utf8_utf16<char32_t>::result __codecvt_utf8_utf16<char32_t>::do_out(state_type&, const intern_type* frm, const intern_type* frm_end, const intern_type*& frm_nxt, extern_type* to, extern_type* to_end, extern_type*& to_nxt) const { const uint32_t* _frm = reinterpret_cast<const uint32_t*>(frm); const uint32_t* _frm_end = reinterpret_cast<const uint32_t*>(frm_end); const uint32_t* _frm_nxt = _frm; uint8_t* _to = reinterpret_cast<uint8_t*>(to); uint8_t* _to_end = reinterpret_cast<uint8_t*>(to_end); uint8_t* _to_nxt = _to; result r = utf16_to_utf8(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf8_utf16<char32_t>::result __codecvt_utf8_utf16<char32_t>::do_in(state_type&, const extern_type* frm, const extern_type* frm_end, const extern_type*& frm_nxt, intern_type* to, intern_type* to_end, intern_type*& to_nxt) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); const uint8_t* _frm_nxt = _frm; uint32_t* _to = reinterpret_cast<uint32_t*>(to); uint32_t* _to_end = reinterpret_cast<uint32_t*>(to_end); uint32_t* _to_nxt = _to; result r = utf8_to_utf16(_frm, _frm_end, _frm_nxt, _to, _to_end, _to_nxt, _Maxcode_, _Mode_); frm_nxt = frm + (_frm_nxt - _frm); to_nxt = to + (_to_nxt - _to); return r; } __codecvt_utf8_utf16<char32_t>::result __codecvt_utf8_utf16<char32_t>::do_unshift(state_type&, extern_type* to, extern_type*, extern_type*& to_nxt) const { to_nxt = to; return noconv; } int __codecvt_utf8_utf16<char32_t>::do_encoding() const _NOEXCEPT { return 0; } bool __codecvt_utf8_utf16<char32_t>::do_always_noconv() const _NOEXCEPT { return false; } int __codecvt_utf8_utf16<char32_t>::do_length(state_type&, const extern_type* frm, const extern_type* frm_end, size_t mx) const { const uint8_t* _frm = reinterpret_cast<const uint8_t*>(frm); const uint8_t* _frm_end = reinterpret_cast<const uint8_t*>(frm_end); return utf8_to_utf16_length(_frm, _frm_end, mx, _Maxcode_, _Mode_); } int __codecvt_utf8_utf16<char32_t>::do_max_length() const _NOEXCEPT { if (_Mode_ & consume_header) return 7; return 4; } // __narrow_to_utf8<16> __narrow_to_utf8<16>::~__narrow_to_utf8() { } // __narrow_to_utf8<32> __narrow_to_utf8<32>::~__narrow_to_utf8() { } // __widen_from_utf8<16> __widen_from_utf8<16>::~__widen_from_utf8() { } // __widen_from_utf8<32> __widen_from_utf8<32>::~__widen_from_utf8() { } static bool checked_string_to_wchar_convert(wchar_t& dest, const char* ptr, __locale_struct* loc) { if (*ptr == '\0') return false; mbstate_t mb = {}; wchar_t out; size_t ret = __libcpp_mbrtowc_l(&out, ptr, strlen(ptr), &mb, loc); if (ret == static_cast<size_t>(-1) || ret == static_cast<size_t>(-2)) { return false; } dest = out; return true; } static bool checked_string_to_char_convert(char& dest, const char* ptr, __locale_struct* __loc) { if (*ptr == '\0') return false; if (!ptr[1]) { dest = *ptr; return true; } // First convert the MBS into a wide char then attempt to narrow it using // wctob_l. wchar_t wout; if (!checked_string_to_wchar_convert(wout, ptr, __loc)) return false; int res; if ((res = __libcpp_wctob_l(wout, __loc)) != char_traits<char>::eof()) { dest = res; return true; } // FIXME: Work around specific multibyte sequences that we can reasonable // translate into a different single byte. switch (wout) { case L'\u00A0': // non-breaking space dest = ' '; return true; default: return false; } _LIBCPP_UNREACHABLE(); } // numpunct<char> && numpunct<wchar_t> locale::id numpunct< char >::id; locale::id numpunct<wchar_t>::id; numpunct<char>::numpunct(size_t refs) : locale::facet(refs), __decimal_point_('.'), __thousands_sep_(',') { } numpunct<wchar_t>::numpunct(size_t refs) : locale::facet(refs), __decimal_point_(L'.'), __thousands_sep_(L',') { } numpunct<char>::~numpunct() { } numpunct<wchar_t>::~numpunct() { } char numpunct< char >::do_decimal_point() const {return __decimal_point_;} wchar_t numpunct<wchar_t>::do_decimal_point() const {return __decimal_point_;} char numpunct< char >::do_thousands_sep() const {return __thousands_sep_;} wchar_t numpunct<wchar_t>::do_thousands_sep() const {return __thousands_sep_;} string numpunct< char >::do_grouping() const {return __grouping_;} string numpunct<wchar_t>::do_grouping() const {return __grouping_;} string numpunct< char >::do_truename() const {return "true";} wstring numpunct<wchar_t>::do_truename() const {return L"true";} string numpunct< char >::do_falsename() const {return "false";} wstring numpunct<wchar_t>::do_falsename() const {return L"false";} // numpunct_byname<char> numpunct_byname<char>::numpunct_byname(const char* nm, size_t refs) : numpunct<char>(refs) { __init(nm); } numpunct_byname<char>::numpunct_byname(const string& nm, size_t refs) : numpunct<char>(refs) { __init(nm.c_str()); } numpunct_byname<char>::~numpunct_byname() { } void numpunct_byname<char>::__init(const char* nm) { if (strcmp(nm, "C") != 0) { __locale_unique_ptr loc(newlocale(LC_ALL_MASK, nm, 0), freelocale); if (loc == nullptr) __throw_runtime_error("numpunct_byname<char>::numpunct_byname" " failed to construct for " + string(nm)); lconv* lc = __libcpp_localeconv_l(loc.get()); checked_string_to_char_convert(__decimal_point_, lc->decimal_point, loc.get()); checked_string_to_char_convert(__thousands_sep_, lc->thousands_sep, loc.get()); __grouping_ = lc->grouping; // localization for truename and falsename is not available } } // numpunct_byname<wchar_t> numpunct_byname<wchar_t>::numpunct_byname(const char* nm, size_t refs) : numpunct<wchar_t>(refs) { __init(nm); } numpunct_byname<wchar_t>::numpunct_byname(const string& nm, size_t refs) : numpunct<wchar_t>(refs) { __init(nm.c_str()); } numpunct_byname<wchar_t>::~numpunct_byname() { } void numpunct_byname<wchar_t>::__init(const char* nm) { if (strcmp(nm, "C") != 0) { __locale_unique_ptr loc(newlocale(LC_ALL_MASK, nm, 0), freelocale); if (loc == nullptr) __throw_runtime_error("numpunct_byname<wchar_t>::numpunct_byname" " failed to construct for " + string(nm)); lconv* lc = __libcpp_localeconv_l(loc.get()); checked_string_to_wchar_convert(__decimal_point_, lc->decimal_point, loc.get()); checked_string_to_wchar_convert(__thousands_sep_, lc->thousands_sep, loc.get()); __grouping_ = lc->grouping; // localization for truename and falsename is not available } } // num_get helpers int __num_get_base::__get_base(ios_base& iob) { ios_base::fmtflags __basefield = iob.flags() & ios_base::basefield; if (__basefield == ios_base::oct) return 8; else if (__basefield == ios_base::hex) return 16; else if (__basefield == 0) return 0; return 10; } const char __num_get_base::__src[33] = "0123456789abcdefABCDEFxX+-pPiInN"; void __check_grouping(const string& __grouping, unsigned* __g, unsigned* __g_end, ios_base::iostate& __err) { if (__grouping.size() != 0) { reverse(__g, __g_end); const char* __ig = __grouping.data(); const char* __eg = __ig + __grouping.size(); for (unsigned* __r = __g; __r < __g_end-1; ++__r) { if (0 < *__ig && *__ig < numeric_limits<char>::max()) { if (static_cast<unsigned>(*__ig) != *__r) { __err = ios_base::failbit; return; } } if (__eg - __ig > 1) ++__ig; } if (0 < *__ig && *__ig < numeric_limits<char>::max()) { if (static_cast<unsigned>(*__ig) < __g_end[-1] || __g_end[-1] == 0) __err = ios_base::failbit; } } } void __num_put_base::__format_int(char* __fmtp, const char* __len, bool __signd, ios_base::fmtflags __flags) { if (__flags & ios_base::showpos) *__fmtp++ = '+'; if (__flags & ios_base::showbase) *__fmtp++ = '#'; while(*__len) *__fmtp++ = *__len++; if ((__flags & ios_base::basefield) == ios_base::oct) *__fmtp = 'o'; else if ((__flags & ios_base::basefield) == ios_base::hex) { if (__flags & ios_base::uppercase) *__fmtp = 'X'; else *__fmtp = 'x'; } else if (__signd) *__fmtp = 'd'; else *__fmtp = 'u'; } bool __num_put_base::__format_float(char* __fmtp, const char* __len, ios_base::fmtflags __flags) { bool specify_precision = true; if (__flags & ios_base::showpos) *__fmtp++ = '+'; if (__flags & ios_base::showpoint) *__fmtp++ = '#'; ios_base::fmtflags floatfield = __flags & ios_base::floatfield; bool uppercase = (__flags & ios_base::uppercase) != 0; if (floatfield == (ios_base::fixed | ios_base::scientific)) specify_precision = false; else { *__fmtp++ = '.'; *__fmtp++ = '*'; } while(*__len) *__fmtp++ = *__len++; if (floatfield == ios_base::fixed) { if (uppercase) *__fmtp = 'F'; else *__fmtp = 'f'; } else if (floatfield == ios_base::scientific) { if (uppercase) *__fmtp = 'E'; else *__fmtp = 'e'; } else if (floatfield == (ios_base::fixed | ios_base::scientific)) { if (uppercase) *__fmtp = 'A'; else *__fmtp = 'a'; } else { if (uppercase) *__fmtp = 'G'; else *__fmtp = 'g'; } return specify_precision; } char* __num_put_base::__identify_padding(char* __nb, char* __ne, const ios_base& __iob) { switch (__iob.flags() & ios_base::adjustfield) { case ios_base::internal: if (__nb[0] == '-' || __nb[0] == '+') return __nb+1; if (__ne - __nb >= 2 && __nb[0] == '0' && (__nb[1] == 'x' || __nb[1] == 'X')) return __nb+2; break; case ios_base::left: return __ne; case ios_base::right: default: break; } return __nb; } // time_get static string* init_weeks() { static string weeks[14]; weeks[0] = "Sunday"; weeks[1] = "Monday"; weeks[2] = "Tuesday"; weeks[3] = "Wednesday"; weeks[4] = "Thursday"; weeks[5] = "Friday"; weeks[6] = "Saturday"; weeks[7] = "Sun"; weeks[8] = "Mon"; weeks[9] = "Tue"; weeks[10] = "Wed"; weeks[11] = "Thu"; weeks[12] = "Fri"; weeks[13] = "Sat"; return weeks; } static wstring* init_wweeks() { static wstring weeks[14]; weeks[0] = L"Sunday"; weeks[1] = L"Monday"; weeks[2] = L"Tuesday"; weeks[3] = L"Wednesday"; weeks[4] = L"Thursday"; weeks[5] = L"Friday"; weeks[6] = L"Saturday"; weeks[7] = L"Sun"; weeks[8] = L"Mon"; weeks[9] = L"Tue"; weeks[10] = L"Wed"; weeks[11] = L"Thu"; weeks[12] = L"Fri"; weeks[13] = L"Sat"; return weeks; } template <> const string* __time_get_c_storage<char>::__weeks() const { static const string* weeks = init_weeks(); return weeks; } template <> const wstring* __time_get_c_storage<wchar_t>::__weeks() const { static const wstring* weeks = init_wweeks(); return weeks; } static string* init_months() { static string months[24]; months[0] = "January"; months[1] = "February"; months[2] = "March"; months[3] = "April"; months[4] = "May"; months[5] = "June"; months[6] = "July"; months[7] = "August"; months[8] = "September"; months[9] = "October"; months[10] = "November"; months[11] = "December"; months[12] = "Jan"; months[13] = "Feb"; months[14] = "Mar"; months[15] = "Apr"; months[16] = "May"; months[17] = "Jun"; months[18] = "Jul"; months[19] = "Aug"; months[20] = "Sep"; months[21] = "Oct"; months[22] = "Nov"; months[23] = "Dec"; return months; } static wstring* init_wmonths() { static wstring months[24]; months[0] = L"January"; months[1] = L"February"; months[2] = L"March"; months[3] = L"April"; months[4] = L"May"; months[5] = L"June"; months[6] = L"July"; months[7] = L"August"; months[8] = L"September"; months[9] = L"October"; months[10] = L"November"; months[11] = L"December"; months[12] = L"Jan"; months[13] = L"Feb"; months[14] = L"Mar"; months[15] = L"Apr"; months[16] = L"May"; months[17] = L"Jun"; months[18] = L"Jul"; months[19] = L"Aug"; months[20] = L"Sep"; months[21] = L"Oct"; months[22] = L"Nov"; months[23] = L"Dec"; return months; } template <> const string* __time_get_c_storage<char>::__months() const { static const string* months = init_months(); return months; } template <> const wstring* __time_get_c_storage<wchar_t>::__months() const { static const wstring* months = init_wmonths(); return months; } static string* init_am_pm() { static string am_pm[24]; am_pm[0] = "AM"; am_pm[1] = "PM"; return am_pm; } static wstring* init_wam_pm() { static wstring am_pm[24]; am_pm[0] = L"AM"; am_pm[1] = L"PM"; return am_pm; } template <> const string* __time_get_c_storage<char>::__am_pm() const { static const string* am_pm = init_am_pm(); return am_pm; } template <> const wstring* __time_get_c_storage<wchar_t>::__am_pm() const { static const wstring* am_pm = init_wam_pm(); return am_pm; } template <> const string& __time_get_c_storage<char>::__x() const { static string s("%m/%d/%y"); return s; } template <> const wstring& __time_get_c_storage<wchar_t>::__x() const { static wstring s(L"%m/%d/%y"); return s; } template <> const string& __time_get_c_storage<char>::__X() const { static string s("%H:%M:%S"); return s; } template <> const wstring& __time_get_c_storage<wchar_t>::__X() const { static wstring s(L"%H:%M:%S"); return s; } template <> const string& __time_get_c_storage<char>::__c() const { static string s("%a %b %d %H:%M:%S %Y"); return s; } template <> const wstring& __time_get_c_storage<wchar_t>::__c() const { static wstring s(L"%a %b %d %H:%M:%S %Y"); return s; } template <> const string& __time_get_c_storage<char>::__r() const { static string s("%I:%M:%S %p"); return s; } template <> const wstring& __time_get_c_storage<wchar_t>::__r() const { static wstring s(L"%I:%M:%S %p"); return s; } // time_get_byname __time_get::__time_get(const char* nm) : __loc_(newlocale(LC_ALL_MASK, nm, 0)) { if (__loc_ == 0) __throw_runtime_error("time_get_byname" " failed to construct for " + string(nm)); } __time_get::__time_get(const string& nm) : __loc_(newlocale(LC_ALL_MASK, nm.c_str(), 0)) { if (__loc_ == 0) __throw_runtime_error("time_get_byname" " failed to construct for " + nm); } __time_get::~__time_get() { freelocale(__loc_); } #if defined(__clang__) #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #if defined(__GNUG__) #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #endif template <> string __time_get_storage<char>::__analyze(char fmt, const ctype<char>& ct) { tm t = {0}; t.tm_sec = 59; t.tm_min = 55; t.tm_hour = 23; t.tm_mday = 31; t.tm_mon = 11; t.tm_year = 161; t.tm_wday = 6; t.tm_yday = 364; t.tm_isdst = -1; char buf[100]; char f[3] = {0}; f[0] = '%'; f[1] = fmt; size_t n = strftime_l(buf, countof(buf), f, &t, __loc_); char* bb = buf; char* be = buf + n; string result; while (bb != be) { if (ct.is(ctype_base::space, *bb)) { result.push_back(' '); for (++bb; bb != be && ct.is(ctype_base::space, *bb); ++bb) ; continue; } char* w = bb; ios_base::iostate err = ios_base::goodbit; ptrdiff_t i = __scan_keyword(w, be, this->__weeks_, this->__weeks_+14, ct, err, false) - this->__weeks_; if (i < 14) { result.push_back('%'); if (i < 7) result.push_back('A'); else result.push_back('a'); bb = w; continue; } w = bb; i = __scan_keyword(w, be, this->__months_, this->__months_+24, ct, err, false) - this->__months_; if (i < 24) { result.push_back('%'); if (i < 12) result.push_back('B'); else result.push_back('b'); if (fmt == 'x' && ct.is(ctype_base::digit, this->__months_[i][0])) result.back() = 'm'; bb = w; continue; } if (this->__am_pm_[0].size() + this->__am_pm_[1].size() > 0) { w = bb; i = __scan_keyword(w, be, this->__am_pm_, this->__am_pm_+2, ct, err, false) - this->__am_pm_; if (i < 2) { result.push_back('%'); result.push_back('p'); bb = w; continue; } } w = bb; if (ct.is(ctype_base::digit, *bb)) { switch(__get_up_to_n_digits(bb, be, err, ct, 4)) { case 6: result.push_back('%'); result.push_back('w'); break; case 7: result.push_back('%'); result.push_back('u'); break; case 11: result.push_back('%'); result.push_back('I'); break; case 12: result.push_back('%'); result.push_back('m'); break; case 23: result.push_back('%'); result.push_back('H'); break; case 31: result.push_back('%'); result.push_back('d'); break; case 55: result.push_back('%'); result.push_back('M'); break; case 59: result.push_back('%'); result.push_back('S'); break; case 61: result.push_back('%'); result.push_back('y'); break; case 364: result.push_back('%'); result.push_back('j'); break; case 2061: result.push_back('%'); result.push_back('Y'); break; default: for (; w != bb; ++w) result.push_back(*w); break; } continue; } if (*bb == '%') { result.push_back('%'); result.push_back('%'); ++bb; continue; } result.push_back(*bb); ++bb; } return result; } #if defined(__clang__) #pragma clang diagnostic ignored "-Wmissing-braces" #endif template <> wstring __time_get_storage<wchar_t>::__analyze(char fmt, const ctype<wchar_t>& ct) { tm t = {0}; t.tm_sec = 59; t.tm_min = 55; t.tm_hour = 23; t.tm_mday = 31; t.tm_mon = 11; t.tm_year = 161; t.tm_wday = 6; t.tm_yday = 364; t.tm_isdst = -1; char buf[100]; char f[3] = {0}; f[0] = '%'; f[1] = fmt; strftime_l(buf, countof(buf), f, &t, __loc_); wchar_t wbuf[100]; wchar_t* wbb = wbuf; mbstate_t mb = {0}; const char* bb = buf; size_t j = __libcpp_mbsrtowcs_l( wbb, &bb, countof(wbuf), &mb, __loc_); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); wchar_t* wbe = wbb + j; wstring result; while (wbb != wbe) { if (ct.is(ctype_base::space, *wbb)) { result.push_back(L' '); for (++wbb; wbb != wbe && ct.is(ctype_base::space, *wbb); ++wbb) ; continue; } wchar_t* w = wbb; ios_base::iostate err = ios_base::goodbit; ptrdiff_t i = __scan_keyword(w, wbe, this->__weeks_, this->__weeks_+14, ct, err, false) - this->__weeks_; if (i < 14) { result.push_back(L'%'); if (i < 7) result.push_back(L'A'); else result.push_back(L'a'); wbb = w; continue; } w = wbb; i = __scan_keyword(w, wbe, this->__months_, this->__months_+24, ct, err, false) - this->__months_; if (i < 24) { result.push_back(L'%'); if (i < 12) result.push_back(L'B'); else result.push_back(L'b'); if (fmt == 'x' && ct.is(ctype_base::digit, this->__months_[i][0])) result.back() = L'm'; wbb = w; continue; } if (this->__am_pm_[0].size() + this->__am_pm_[1].size() > 0) { w = wbb; i = __scan_keyword(w, wbe, this->__am_pm_, this->__am_pm_+2, ct, err, false) - this->__am_pm_; if (i < 2) { result.push_back(L'%'); result.push_back(L'p'); wbb = w; continue; } } w = wbb; if (ct.is(ctype_base::digit, *wbb)) { switch(__get_up_to_n_digits(wbb, wbe, err, ct, 4)) { case 6: result.push_back(L'%'); result.push_back(L'w'); break; case 7: result.push_back(L'%'); result.push_back(L'u'); break; case 11: result.push_back(L'%'); result.push_back(L'I'); break; case 12: result.push_back(L'%'); result.push_back(L'm'); break; case 23: result.push_back(L'%'); result.push_back(L'H'); break; case 31: result.push_back(L'%'); result.push_back(L'd'); break; case 55: result.push_back(L'%'); result.push_back(L'M'); break; case 59: result.push_back(L'%'); result.push_back(L'S'); break; case 61: result.push_back(L'%'); result.push_back(L'y'); break; case 364: result.push_back(L'%'); result.push_back(L'j'); break; case 2061: result.push_back(L'%'); result.push_back(L'Y'); break; default: for (; w != wbb; ++w) result.push_back(*w); break; } continue; } if (ct.narrow(*wbb, 0) == '%') { result.push_back(L'%'); result.push_back(L'%'); ++wbb; continue; } result.push_back(*wbb); ++wbb; } return result; } template <> void __time_get_storage<char>::init(const ctype<char>& ct) { tm t = {0}; char buf[100]; // __weeks_ for (int i = 0; i < 7; ++i) { t.tm_wday = i; strftime_l(buf, countof(buf), "%A", &t, __loc_); __weeks_[i] = buf; strftime_l(buf, countof(buf), "%a", &t, __loc_); __weeks_[i+7] = buf; } // __months_ for (int i = 0; i < 12; ++i) { t.tm_mon = i; strftime_l(buf, countof(buf), "%B", &t, __loc_); __months_[i] = buf; strftime_l(buf, countof(buf), "%b", &t, __loc_); __months_[i+12] = buf; } // __am_pm_ t.tm_hour = 1; strftime_l(buf, countof(buf), "%p", &t, __loc_); __am_pm_[0] = buf; t.tm_hour = 13; strftime_l(buf, countof(buf), "%p", &t, __loc_); __am_pm_[1] = buf; __c_ = __analyze('c', ct); __r_ = __analyze('r', ct); __x_ = __analyze('x', ct); __X_ = __analyze('X', ct); } template <> void __time_get_storage<wchar_t>::init(const ctype<wchar_t>& ct) { tm t = {0}; char buf[100]; wchar_t wbuf[100]; wchar_t* wbe; mbstate_t mb = {0}; // __weeks_ for (int i = 0; i < 7; ++i) { t.tm_wday = i; strftime_l(buf, countof(buf), "%A", &t, __loc_); mb = mbstate_t(); const char* bb = buf; size_t j = __libcpp_mbsrtowcs_l(wbuf, &bb, countof(wbuf), &mb, __loc_); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); wbe = wbuf + j; __weeks_[i].assign(wbuf, wbe); strftime_l(buf, countof(buf), "%a", &t, __loc_); mb = mbstate_t(); bb = buf; j = __libcpp_mbsrtowcs_l(wbuf, &bb, countof(wbuf), &mb, __loc_); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); wbe = wbuf + j; __weeks_[i+7].assign(wbuf, wbe); } // __months_ for (int i = 0; i < 12; ++i) { t.tm_mon = i; strftime_l(buf, countof(buf), "%B", &t, __loc_); mb = mbstate_t(); const char* bb = buf; size_t j = __libcpp_mbsrtowcs_l(wbuf, &bb, countof(wbuf), &mb, __loc_); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); wbe = wbuf + j; __months_[i].assign(wbuf, wbe); strftime_l(buf, countof(buf), "%b", &t, __loc_); mb = mbstate_t(); bb = buf; j = __libcpp_mbsrtowcs_l(wbuf, &bb, countof(wbuf), &mb, __loc_); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); wbe = wbuf + j; __months_[i+12].assign(wbuf, wbe); } // __am_pm_ t.tm_hour = 1; strftime_l(buf, countof(buf), "%p", &t, __loc_); mb = mbstate_t(); const char* bb = buf; size_t j = __libcpp_mbsrtowcs_l(wbuf, &bb, countof(wbuf), &mb, __loc_); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); wbe = wbuf + j; __am_pm_[0].assign(wbuf, wbe); t.tm_hour = 13; strftime_l(buf, countof(buf), "%p", &t, __loc_); mb = mbstate_t(); bb = buf; j = __libcpp_mbsrtowcs_l(wbuf, &bb, countof(wbuf), &mb, __loc_); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); wbe = wbuf + j; __am_pm_[1].assign(wbuf, wbe); __c_ = __analyze('c', ct); __r_ = __analyze('r', ct); __x_ = __analyze('x', ct); __X_ = __analyze('X', ct); } template <class CharT> struct _LIBCPP_HIDDEN __time_get_temp : public ctype_byname<CharT> { explicit __time_get_temp(const char* nm) : ctype_byname<CharT>(nm, 1) {} explicit __time_get_temp(const string& nm) : ctype_byname<CharT>(nm, 1) {} }; template <> __time_get_storage<char>::__time_get_storage(const char* __nm) : __time_get(__nm) { const __time_get_temp<char> ct(__nm); init(ct); } template <> __time_get_storage<char>::__time_get_storage(const string& __nm) : __time_get(__nm) { const __time_get_temp<char> ct(__nm); init(ct); } template <> __time_get_storage<wchar_t>::__time_get_storage(const char* __nm) : __time_get(__nm) { const __time_get_temp<wchar_t> ct(__nm); init(ct); } template <> __time_get_storage<wchar_t>::__time_get_storage(const string& __nm) : __time_get(__nm) { const __time_get_temp<wchar_t> ct(__nm); init(ct); } template <> time_base::dateorder __time_get_storage<char>::__do_date_order() const { unsigned i; for (i = 0; i < __x_.size(); ++i) if (__x_[i] == '%') break; ++i; switch (__x_[i]) { case 'y': case 'Y': for (++i; i < __x_.size(); ++i) if (__x_[i] == '%') break; if (i == __x_.size()) break; ++i; switch (__x_[i]) { case 'm': for (++i; i < __x_.size(); ++i) if (__x_[i] == '%') break; if (i == __x_.size()) break; ++i; if (__x_[i] == 'd') return time_base::ymd; break; case 'd': for (++i; i < __x_.size(); ++i) if (__x_[i] == '%') break; if (i == __x_.size()) break; ++i; if (__x_[i] == 'm') return time_base::ydm; break; } break; case 'm': for (++i; i < __x_.size(); ++i) if (__x_[i] == '%') break; if (i == __x_.size()) break; ++i; if (__x_[i] == 'd') { for (++i; i < __x_.size(); ++i) if (__x_[i] == '%') break; if (i == __x_.size()) break; ++i; if (__x_[i] == 'y' || __x_[i] == 'Y') return time_base::mdy; break; } break; case 'd': for (++i; i < __x_.size(); ++i) if (__x_[i] == '%') break; if (i == __x_.size()) break; ++i; if (__x_[i] == 'm') { for (++i; i < __x_.size(); ++i) if (__x_[i] == '%') break; if (i == __x_.size()) break; ++i; if (__x_[i] == 'y' || __x_[i] == 'Y') return time_base::dmy; break; } break; } return time_base::no_order; } template <> time_base::dateorder __time_get_storage<wchar_t>::__do_date_order() const { unsigned i; for (i = 0; i < __x_.size(); ++i) if (__x_[i] == L'%') break; ++i; switch (__x_[i]) { case L'y': case L'Y': for (++i; i < __x_.size(); ++i) if (__x_[i] == L'%') break; if (i == __x_.size()) break; ++i; switch (__x_[i]) { case L'm': for (++i; i < __x_.size(); ++i) if (__x_[i] == L'%') break; if (i == __x_.size()) break; ++i; if (__x_[i] == L'd') return time_base::ymd; break; case L'd': for (++i; i < __x_.size(); ++i) if (__x_[i] == L'%') break; if (i == __x_.size()) break; ++i; if (__x_[i] == L'm') return time_base::ydm; break; } break; case L'm': for (++i; i < __x_.size(); ++i) if (__x_[i] == L'%') break; if (i == __x_.size()) break; ++i; if (__x_[i] == L'd') { for (++i; i < __x_.size(); ++i) if (__x_[i] == L'%') break; if (i == __x_.size()) break; ++i; if (__x_[i] == L'y' || __x_[i] == L'Y') return time_base::mdy; break; } break; case L'd': for (++i; i < __x_.size(); ++i) if (__x_[i] == L'%') break; if (i == __x_.size()) break; ++i; if (__x_[i] == L'm') { for (++i; i < __x_.size(); ++i) if (__x_[i] == L'%') break; if (i == __x_.size()) break; ++i; if (__x_[i] == L'y' || __x_[i] == L'Y') return time_base::dmy; break; } break; } return time_base::no_order; } // time_put __time_put::__time_put(const char* nm) : __loc_(newlocale(LC_ALL_MASK, nm, 0)) { if (__loc_ == 0) __throw_runtime_error("time_put_byname" " failed to construct for " + string(nm)); } __time_put::__time_put(const string& nm) : __loc_(newlocale(LC_ALL_MASK, nm.c_str(), 0)) { if (__loc_ == 0) __throw_runtime_error("time_put_byname" " failed to construct for " + nm); } __time_put::~__time_put() { if (__loc_ != _LIBCPP_GET_C_LOCALE) freelocale(__loc_); } void __time_put::__do_put(char* __nb, char*& __ne, const tm* __tm, char __fmt, char __mod) const { char fmt[] = {'%', __fmt, __mod, 0}; if (__mod != 0) swap(fmt[1], fmt[2]); size_t n = strftime_l(__nb, countof(__nb, __ne), fmt, __tm, __loc_); __ne = __nb + n; } void __time_put::__do_put(wchar_t* __wb, wchar_t*& __we, const tm* __tm, char __fmt, char __mod) const { char __nar[100]; char* __ne = __nar + 100; __do_put(__nar, __ne, __tm, __fmt, __mod); mbstate_t mb = {0}; const char* __nb = __nar; size_t j = __libcpp_mbsrtowcs_l(__wb, &__nb, countof(__wb, __we), &mb, __loc_); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); __we = __wb + j; } // moneypunct_byname template <class charT> static void __init_pat(money_base::pattern& pat, basic_string<charT>& __curr_symbol_, bool intl, char cs_precedes, char sep_by_space, char sign_posn, charT space_char) { const char sign = static_cast<char>(money_base::sign); const char space = static_cast<char>(money_base::space); const char none = static_cast<char>(money_base::none); const char symbol = static_cast<char>(money_base::symbol); const char value = static_cast<char>(money_base::value); const bool symbol_contains_sep = intl && __curr_symbol_.size() == 4; // Comments on case branches reflect 'C11 7.11.2.1 The localeconv // function'. "Space between sign and symbol or value" means that // if the sign is adjacent to the symbol, there's a space between // them, and otherwise there's a space between the sign and value. // // C11's localeconv specifies that the fourth character of an // international curr_symbol is used to separate the sign and // value when sep_by_space says to do so. C++ can't represent // that, so we just use a space. When sep_by_space says to // separate the symbol and value-or-sign with a space, we rearrange the // curr_symbol to put its spacing character on the correct side of // the symbol. // // We also need to avoid adding an extra space between the sign // and value when the currency symbol is suppressed (by not // setting showbase). We match glibc's strfmon by interpreting // sep_by_space==1 as "omit the space when the currency symbol is // absent". // // Users who want to get this right should use ICU instead. switch (cs_precedes) { case 0: // value before curr_symbol if (symbol_contains_sep) { // Move the separator to before the symbol, to place it // between the value and symbol. rotate(__curr_symbol_.begin(), __curr_symbol_.begin() + 3, __curr_symbol_.end()); } switch (sign_posn) { case 0: // Parentheses surround the quantity and currency symbol. pat.field[0] = sign; pat.field[1] = value; pat.field[2] = none; // Any space appears in the symbol. pat.field[3] = symbol; switch (sep_by_space) { case 0: // No space separates the currency symbol and value. // This case may have changed between C99 and C11; // assume the currency symbol matches the intention. case 2: // Space between sign and currency or value. // The "sign" is two parentheses, so no space here either. return; case 1: // Space between currency-and-sign or currency and value. if (!symbol_contains_sep) { // We insert the space into the symbol instead of // setting pat.field[2]=space so that when // showbase is not set, the space goes away too. __curr_symbol_.insert(0, 1, space_char); } return; default: break; } break; case 1: // The sign string precedes the quantity and currency symbol. pat.field[0] = sign; pat.field[3] = symbol; switch (sep_by_space) { case 0: // No space separates the currency symbol and value. pat.field[1] = value; pat.field[2] = none; return; case 1: // Space between currency-and-sign or currency and value. pat.field[1] = value; pat.field[2] = none; if (!symbol_contains_sep) { // We insert the space into the symbol instead of // setting pat.field[2]=space so that when // showbase is not set, the space goes away too. __curr_symbol_.insert(0, 1, space_char); } return; case 2: // Space between sign and currency or value. pat.field[1] = space; pat.field[2] = value; if (symbol_contains_sep) { // Remove the separator from the symbol, since it // has already appeared after the sign. __curr_symbol_.erase(__curr_symbol_.begin()); } return; default: break; } break; case 2: // The sign string succeeds the quantity and currency symbol. pat.field[0] = value; pat.field[3] = sign; switch (sep_by_space) { case 0: // No space separates the currency symbol and value. pat.field[1] = none; pat.field[2] = symbol; return; case 1: // Space between currency-and-sign or currency and value. if (!symbol_contains_sep) { // We insert the space into the symbol instead of // setting pat.field[1]=space so that when // showbase is not set, the space goes away too. __curr_symbol_.insert(0, 1, space_char); } pat.field[1] = none; pat.field[2] = symbol; return; case 2: // Space between sign and currency or value. pat.field[1] = symbol; pat.field[2] = space; if (symbol_contains_sep) { // Remove the separator from the symbol, since it // should not be removed if showbase is absent. __curr_symbol_.erase(__curr_symbol_.begin()); } return; default: break; } break; case 3: // The sign string immediately precedes the currency symbol. pat.field[0] = value; pat.field[3] = symbol; switch (sep_by_space) { case 0: // No space separates the currency symbol and value. pat.field[1] = none; pat.field[2] = sign; return; case 1: // Space between currency-and-sign or currency and value. pat.field[1] = space; pat.field[2] = sign; if (symbol_contains_sep) { // Remove the separator from the symbol, since it // has already appeared before the sign. __curr_symbol_.erase(__curr_symbol_.begin()); } return; case 2: // Space between sign and currency or value. pat.field[1] = sign; pat.field[2] = none; if (!symbol_contains_sep) { // We insert the space into the symbol instead of // setting pat.field[2]=space so that when // showbase is not set, the space goes away too. __curr_symbol_.insert(0, 1, space_char); } return; default: break; } break; case 4: // The sign string immediately succeeds the currency symbol. pat.field[0] = value; pat.field[3] = sign; switch (sep_by_space) { case 0: // No space separates the currency symbol and value. pat.field[1] = none; pat.field[2] = symbol; return; case 1: // Space between currency-and-sign or currency and value. pat.field[1] = none; pat.field[2] = symbol; if (!symbol_contains_sep) { // We insert the space into the symbol instead of // setting pat.field[1]=space so that when // showbase is not set, the space goes away too. __curr_symbol_.insert(0, 1, space_char); } return; case 2: // Space between sign and currency or value. pat.field[1] = symbol; pat.field[2] = space; if (symbol_contains_sep) { // Remove the separator from the symbol, since it // should not disappear when showbase is absent. __curr_symbol_.erase(__curr_symbol_.begin()); } return; default: break; } break; default: break; } break; case 1: // curr_symbol before value switch (sign_posn) { case 0: // Parentheses surround the quantity and currency symbol. pat.field[0] = sign; pat.field[1] = symbol; pat.field[2] = none; // Any space appears in the symbol. pat.field[3] = value; switch (sep_by_space) { case 0: // No space separates the currency symbol and value. // This case may have changed between C99 and C11; // assume the currency symbol matches the intention. case 2: // Space between sign and currency or value. // The "sign" is two parentheses, so no space here either. return; case 1: // Space between currency-and-sign or currency and value. if (!symbol_contains_sep) { // We insert the space into the symbol instead of // setting pat.field[2]=space so that when // showbase is not set, the space goes away too. __curr_symbol_.insert(0, 1, space_char); } return; default: break; } break; case 1: // The sign string precedes the quantity and currency symbol. pat.field[0] = sign; pat.field[3] = value; switch (sep_by_space) { case 0: // No space separates the currency symbol and value. pat.field[1] = symbol; pat.field[2] = none; return; case 1: // Space between currency-and-sign or currency and value. pat.field[1] = symbol; pat.field[2] = none; if (!symbol_contains_sep) { // We insert the space into the symbol instead of // setting pat.field[2]=space so that when // showbase is not set, the space goes away too. __curr_symbol_.push_back(space_char); } return; case 2: // Space between sign and currency or value. pat.field[1] = space; pat.field[2] = symbol; if (symbol_contains_sep) { // Remove the separator from the symbol, since it // has already appeared after the sign. __curr_symbol_.pop_back(); } return; default: break; } break; case 2: // The sign string succeeds the quantity and currency symbol. pat.field[0] = symbol; pat.field[3] = sign; switch (sep_by_space) { case 0: // No space separates the currency symbol and value. pat.field[1] = none; pat.field[2] = value; return; case 1: // Space between currency-and-sign or currency and value. pat.field[1] = none; pat.field[2] = value; if (!symbol_contains_sep) { // We insert the space into the symbol instead of // setting pat.field[1]=space so that when // showbase is not set, the space goes away too. __curr_symbol_.push_back(space_char); } return; case 2: // Space between sign and currency or value. pat.field[1] = value; pat.field[2] = space; if (symbol_contains_sep) { // Remove the separator from the symbol, since it // will appear before the sign. __curr_symbol_.pop_back(); } return; default: break; } break; case 3: // The sign string immediately precedes the currency symbol. pat.field[0] = sign; pat.field[3] = value; switch (sep_by_space) { case 0: // No space separates the currency symbol and value. pat.field[1] = symbol; pat.field[2] = none; return; case 1: // Space between currency-and-sign or currency and value. pat.field[1] = symbol; pat.field[2] = none; if (!symbol_contains_sep) { // We insert the space into the symbol instead of // setting pat.field[2]=space so that when // showbase is not set, the space goes away too. __curr_symbol_.push_back(space_char); } return; case 2: // Space between sign and currency or value. pat.field[1] = space; pat.field[2] = symbol; if (symbol_contains_sep) { // Remove the separator from the symbol, since it // has already appeared after the sign. __curr_symbol_.pop_back(); } return; default: break; } break; case 4: // The sign string immediately succeeds the currency symbol. pat.field[0] = symbol; pat.field[3] = value; switch (sep_by_space) { case 0: // No space separates the currency symbol and value. pat.field[1] = sign; pat.field[2] = none; return; case 1: // Space between currency-and-sign or currency and value. pat.field[1] = sign; pat.field[2] = space; if (symbol_contains_sep) { // Remove the separator from the symbol, since it // should not disappear when showbase is absent. __curr_symbol_.pop_back(); } return; case 2: // Space between sign and currency or value. pat.field[1] = none; pat.field[2] = sign; if (!symbol_contains_sep) { // We insert the space into the symbol instead of // setting pat.field[1]=space so that when // showbase is not set, the space goes away too. __curr_symbol_.push_back(space_char); } return; default: break; } break; default: break; } break; default: break; } pat.field[0] = symbol; pat.field[1] = sign; pat.field[2] = none; pat.field[3] = value; } template<> void moneypunct_byname<char, false>::init(const char* nm) { typedef moneypunct<char, false> base; __locale_unique_ptr loc(newlocale(LC_ALL_MASK, nm, 0), freelocale); if (loc == nullptr) __throw_runtime_error("moneypunct_byname" " failed to construct for " + string(nm)); lconv* lc = __libcpp_localeconv_l(loc.get()); if (!checked_string_to_char_convert(__decimal_point_, lc->mon_decimal_point, loc.get())) __decimal_point_ = base::do_decimal_point(); if (!checked_string_to_char_convert(__thousands_sep_, lc->mon_thousands_sep, loc.get())) __thousands_sep_ = base::do_thousands_sep(); __grouping_ = lc->mon_grouping; __curr_symbol_ = lc->currency_symbol; if (lc->frac_digits != CHAR_MAX) __frac_digits_ = lc->frac_digits; else __frac_digits_ = base::do_frac_digits(); if (lc->p_sign_posn == 0) __positive_sign_ = "()"; else __positive_sign_ = lc->positive_sign; if (lc->n_sign_posn == 0) __negative_sign_ = "()"; else __negative_sign_ = lc->negative_sign; // Assume the positive and negative formats will want spaces in // the same places in curr_symbol since there's no way to // represent anything else. string_type __dummy_curr_symbol = __curr_symbol_; __init_pat(__pos_format_, __dummy_curr_symbol, false, lc->p_cs_precedes, lc->p_sep_by_space, lc->p_sign_posn, ' '); __init_pat(__neg_format_, __curr_symbol_, false, lc->n_cs_precedes, lc->n_sep_by_space, lc->n_sign_posn, ' '); } template<> void moneypunct_byname<char, true>::init(const char* nm) { typedef moneypunct<char, true> base; __locale_unique_ptr loc(newlocale(LC_ALL_MASK, nm, 0), freelocale); if (loc == nullptr) __throw_runtime_error("moneypunct_byname" " failed to construct for " + string(nm)); lconv* lc = __libcpp_localeconv_l(loc.get()); if (!checked_string_to_char_convert(__decimal_point_, lc->mon_decimal_point, loc.get())) __decimal_point_ = base::do_decimal_point(); if (!checked_string_to_char_convert(__thousands_sep_, lc->mon_thousands_sep, loc.get())) __thousands_sep_ = base::do_thousands_sep(); __grouping_ = lc->mon_grouping; __curr_symbol_ = lc->int_curr_symbol; if (lc->int_frac_digits != CHAR_MAX) __frac_digits_ = lc->int_frac_digits; else __frac_digits_ = base::do_frac_digits(); #if defined(_LIBCPP_MSVCRT) || defined(__MINGW32__) if (lc->p_sign_posn == 0) #else // _LIBCPP_MSVCRT if (lc->int_p_sign_posn == 0) #endif // !_LIBCPP_MSVCRT __positive_sign_ = "()"; else __positive_sign_ = lc->positive_sign; #if defined(_LIBCPP_MSVCRT) || defined(__MINGW32__) if(lc->n_sign_posn == 0) #else // _LIBCPP_MSVCRT if (lc->int_n_sign_posn == 0) #endif // !_LIBCPP_MSVCRT __negative_sign_ = "()"; else __negative_sign_ = lc->negative_sign; // Assume the positive and negative formats will want spaces in // the same places in curr_symbol since there's no way to // represent anything else. string_type __dummy_curr_symbol = __curr_symbol_; #if defined(_LIBCPP_MSVCRT) || defined(__MINGW32__) __init_pat(__pos_format_, __dummy_curr_symbol, true, lc->p_cs_precedes, lc->p_sep_by_space, lc->p_sign_posn, ' '); __init_pat(__neg_format_, __curr_symbol_, true, lc->n_cs_precedes, lc->n_sep_by_space, lc->n_sign_posn, ' '); #else // _LIBCPP_MSVCRT __init_pat(__pos_format_, __dummy_curr_symbol, true, lc->int_p_cs_precedes, lc->int_p_sep_by_space, lc->int_p_sign_posn, ' '); __init_pat(__neg_format_, __curr_symbol_, true, lc->int_n_cs_precedes, lc->int_n_sep_by_space, lc->int_n_sign_posn, ' '); #endif // !_LIBCPP_MSVCRT } template<> void moneypunct_byname<wchar_t, false>::init(const char* nm) { typedef moneypunct<wchar_t, false> base; __locale_unique_ptr loc(newlocale(LC_ALL_MASK, nm, 0), freelocale); if (loc == nullptr) __throw_runtime_error("moneypunct_byname" " failed to construct for " + string(nm)); lconv* lc = __libcpp_localeconv_l(loc.get()); if (!checked_string_to_wchar_convert(__decimal_point_, lc->mon_decimal_point, loc.get())) __decimal_point_ = base::do_decimal_point(); if (!checked_string_to_wchar_convert(__thousands_sep_, lc->mon_thousands_sep, loc.get())) __thousands_sep_ = base::do_thousands_sep(); __grouping_ = lc->mon_grouping; wchar_t wbuf[100]; mbstate_t mb = {0}; const char* bb = lc->currency_symbol; size_t j = __libcpp_mbsrtowcs_l(wbuf, &bb, countof(wbuf), &mb, loc.get()); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); wchar_t* wbe = wbuf + j; __curr_symbol_.assign(wbuf, wbe); if (lc->frac_digits != CHAR_MAX) __frac_digits_ = lc->frac_digits; else __frac_digits_ = base::do_frac_digits(); if (lc->p_sign_posn == 0) __positive_sign_ = L"()"; else { mb = mbstate_t(); bb = lc->positive_sign; j = __libcpp_mbsrtowcs_l(wbuf, &bb, countof(wbuf), &mb, loc.get()); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); wbe = wbuf + j; __positive_sign_.assign(wbuf, wbe); } if (lc->n_sign_posn == 0) __negative_sign_ = L"()"; else { mb = mbstate_t(); bb = lc->negative_sign; j = __libcpp_mbsrtowcs_l(wbuf, &bb, countof(wbuf), &mb, loc.get()); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); wbe = wbuf + j; __negative_sign_.assign(wbuf, wbe); } // Assume the positive and negative formats will want spaces in // the same places in curr_symbol since there's no way to // represent anything else. string_type __dummy_curr_symbol = __curr_symbol_; __init_pat(__pos_format_, __dummy_curr_symbol, false, lc->p_cs_precedes, lc->p_sep_by_space, lc->p_sign_posn, L' '); __init_pat(__neg_format_, __curr_symbol_, false, lc->n_cs_precedes, lc->n_sep_by_space, lc->n_sign_posn, L' '); } template<> void moneypunct_byname<wchar_t, true>::init(const char* nm) { typedef moneypunct<wchar_t, true> base; __locale_unique_ptr loc(newlocale(LC_ALL_MASK, nm, 0), freelocale); if (loc == nullptr) __throw_runtime_error("moneypunct_byname" " failed to construct for " + string(nm)); lconv* lc = __libcpp_localeconv_l(loc.get()); if (!checked_string_to_wchar_convert(__decimal_point_, lc->mon_decimal_point, loc.get())) __decimal_point_ = base::do_decimal_point(); if (!checked_string_to_wchar_convert(__thousands_sep_, lc->mon_thousands_sep, loc.get())) __thousands_sep_ = base::do_thousands_sep(); __grouping_ = lc->mon_grouping; wchar_t wbuf[100]; mbstate_t mb = {0}; const char* bb = lc->int_curr_symbol; size_t j = __libcpp_mbsrtowcs_l(wbuf, &bb, countof(wbuf), &mb, loc.get()); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); wchar_t* wbe = wbuf + j; __curr_symbol_.assign(wbuf, wbe); if (lc->int_frac_digits != CHAR_MAX) __frac_digits_ = lc->int_frac_digits; else __frac_digits_ = base::do_frac_digits(); #if defined(_LIBCPP_MSVCRT) || defined(__MINGW32__) if (lc->p_sign_posn == 0) #else // _LIBCPP_MSVCRT if (lc->int_p_sign_posn == 0) #endif // !_LIBCPP_MSVCRT __positive_sign_ = L"()"; else { mb = mbstate_t(); bb = lc->positive_sign; j = __libcpp_mbsrtowcs_l(wbuf, &bb, countof(wbuf), &mb, loc.get()); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); wbe = wbuf + j; __positive_sign_.assign(wbuf, wbe); } #if defined(_LIBCPP_MSVCRT) || defined(__MINGW32__) if (lc->n_sign_posn == 0) #else // _LIBCPP_MSVCRT if (lc->int_n_sign_posn == 0) #endif // !_LIBCPP_MSVCRT __negative_sign_ = L"()"; else { mb = mbstate_t(); bb = lc->negative_sign; j = __libcpp_mbsrtowcs_l(wbuf, &bb, countof(wbuf), &mb, loc.get()); if (j == size_t(-1)) __throw_runtime_error("locale not supported"); wbe = wbuf + j; __negative_sign_.assign(wbuf, wbe); } // Assume the positive and negative formats will want spaces in // the same places in curr_symbol since there's no way to // represent anything else. string_type __dummy_curr_symbol = __curr_symbol_; #if defined(_LIBCPP_MSVCRT) || defined(__MINGW32__) __init_pat(__pos_format_, __dummy_curr_symbol, true, lc->p_cs_precedes, lc->p_sep_by_space, lc->p_sign_posn, L' '); __init_pat(__neg_format_, __curr_symbol_, true, lc->n_cs_precedes, lc->n_sep_by_space, lc->n_sign_posn, L' '); #else // _LIBCPP_MSVCRT __init_pat(__pos_format_, __dummy_curr_symbol, true, lc->int_p_cs_precedes, lc->int_p_sep_by_space, lc->int_p_sign_posn, L' '); __init_pat(__neg_format_, __curr_symbol_, true, lc->int_n_cs_precedes, lc->int_n_sep_by_space, lc->int_n_sign_posn, L' '); #endif // !_LIBCPP_MSVCRT } void __do_nothing(void*) {} void __throw_runtime_error(const char* msg) { #ifndef _LIBCPP_NO_EXCEPTIONS throw runtime_error(msg); #else (void)msg; _VSTD::abort(); #endif } template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS collate<char>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS collate<wchar_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS num_get<char>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS num_get<wchar_t>; template struct _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS __num_get<char>; template struct _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS __num_get<wchar_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS num_put<char>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS num_put<wchar_t>; template struct _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS __num_put<char>; template struct _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS __num_put<wchar_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS time_get<char>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS time_get<wchar_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS time_get_byname<char>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS time_get_byname<wchar_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS time_put<char>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS time_put<wchar_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS time_put_byname<char>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS time_put_byname<wchar_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS moneypunct<char, false>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS moneypunct<char, true>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS moneypunct<wchar_t, false>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS moneypunct<wchar_t, true>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS moneypunct_byname<char, false>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS moneypunct_byname<char, true>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS moneypunct_byname<wchar_t, false>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS moneypunct_byname<wchar_t, true>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS money_get<char>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS money_get<wchar_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS __money_get<char>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS __money_get<wchar_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS money_put<char>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS money_put<wchar_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS __money_put<char>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS __money_put<wchar_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS messages<char>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS messages<wchar_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS messages_byname<char>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS messages_byname<wchar_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS codecvt_byname<char, char, mbstate_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS codecvt_byname<wchar_t, char, mbstate_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS codecvt_byname<char16_t, char, mbstate_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS codecvt_byname<char32_t, char, mbstate_t>; template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS __vector_base_common<true>; _LIBCPP_END_NAMESPACE_STD
31.572729
117
0.563245
JacobW92
33948708b8beaa2576b8ca121ae42251a4a48c94
2,850
hpp
C++
C++ Development Root/SourceCode/Domain/Event/EventHandler.hpp
Dpham181/CPSC-462-GROUP-2
36f55ec4980e2e98d58f1f0a63ecc5070d7faa47
[ "MIT" ]
1
2021-05-19T06:35:15.000Z
2021-05-19T06:35:15.000Z
C++ Development Root/SourceCode/Domain/Event/EventHandler.hpp
Dpham181/CPSC-462-GROUP-2
36f55ec4980e2e98d58f1f0a63ecc5070d7faa47
[ "MIT" ]
null
null
null
C++ Development Root/SourceCode/Domain/Event/EventHandler.hpp
Dpham181/CPSC-462-GROUP-2
36f55ec4980e2e98d58f1f0a63ecc5070d7faa47
[ "MIT" ]
null
null
null
#pragma once #include <any> #include <string> #include <vector> #include <memory> // unique_ptr #include <stdexcept> // domain_error, runtime_error #include "TechnicalServices/Persistence/PersistenceHandler.hpp" namespace Domain::Event { using TechnicalServices::Persistence::Event; using TechnicalServices::Persistence::UserCredentials; using TechnicalServices::Persistence::UserEvents; // Event Package within the Domain Layer Abstract class class EventHandler { public: struct EventException : std::runtime_error { using runtime_error::runtime_error; }; struct NoSuchEvent : EventException { using EventException::EventException; }; struct NoSuchProperty : EventException { using EventException::EventException; }; // object return event with creator static std::unique_ptr<EventHandler> UseEventManagement(const UserCredentials& User); // Operations menu virtual std::vector<std::string> getCommandsEvent() = 0; // retrieves the list of actions (commands) virtual std::any executeCommandEvent(const std::string& command, const std::vector<std::string>& args) =0; // executes one of the actions retrieved // Operations of Event management virtual std::vector<UserCredentials> UsersDB(const std::vector<UserCredentials>& UsersDB) = 0; virtual std::vector<Event> EventsDB(const std::vector<Event>& EventsDB) = 0; virtual std::vector<UserEvents> UserEventsDB(const std::vector<UserEvents>& UserEvents) = 0; virtual void viewEvents( ) = 0; virtual void viewUserEvents( ) = 0; virtual std::vector<std::string> availableTimes(const std::string UserIDs) = 0; virtual std::vector<std::string> availableLocations(std::vector<std::string> OfficeValues, const std::string Time) = 0; virtual Event searchEventId(const int EventId) = 0; virtual std::vector<Event> addEvent(const Event& Event) = 0; virtual std::vector<Event> updateEvent(const Event& Event) = 0; virtual void sendNotifications(const std::string meetingName, const std::string userIDs, const std::string meetingTime, const std::string meetingLocation) = 0; virtual ~EventHandler() noexcept = 0; protected: // Copy assignment operators, protected to prevent mix derived-type assignments EventHandler& operator=(const EventHandler& rhs) = default; // copy assignment EventHandler& operator=(EventHandler&& rhs) = default; // move assignment }; // class EventHandler } // namespace Domain::Event
43.181818
194
0.644561
Dpham181
3395624ea5571f2449e5f684634b3f8dfe774cd7
639
hpp
C++
libs/gui/include/sge/gui/widget/reference_alignment_vector.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/gui/include/sge/gui/widget/reference_alignment_vector.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/gui/include/sge/gui/widget/reference_alignment_vector.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // 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 SGE_GUI_WIDGET_REFERENCE_ALIGNMENT_VECTOR_HPP_INCLUDED #define SGE_GUI_WIDGET_REFERENCE_ALIGNMENT_VECTOR_HPP_INCLUDED #include <sge/gui/widget/reference_alignment_pair.hpp> #include <fcppt/config/external_begin.hpp> #include <vector> #include <fcppt/config/external_end.hpp> namespace sge::gui::widget { using reference_alignment_vector = std::vector<sge::gui::widget::reference_alignment_pair>; } #endif
29.045455
91
0.779343
cpreh
33962aaba731a57008371bc7be5ad52d6fac5742
13,564
hpp
C++
include/eve/detail/overload.hpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
340
2020-09-16T21:12:48.000Z
2022-03-28T15:40:33.000Z
third-party/eve/detail/overload.hpp
aguinet/ecsimd
cba9e7fe76601b98cbaeea317b6c4e671272e70b
[ "Apache-2.0" ]
383
2020-09-17T06:56:35.000Z
2022-03-13T15:58:53.000Z
third-party/eve/detail/overload.hpp
aguinet/ecsimd
cba9e7fe76601b98cbaeea317b6c4e671272e70b
[ "Apache-2.0" ]
28
2021-02-27T23:11:23.000Z
2022-03-25T12:31:29.000Z
//================================================================================================== /* EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #pragma once #include <eve/arch/spec.hpp> #include <eve/detail/meta.hpp> #include <eve/detail/abi.hpp> #include <eve/detail/function/to_logical.hpp> #include <eve/concept/conditional.hpp> #include <eve/concept/value.hpp> #include <concepts> #include <type_traits> #include <utility> #include <ostream> #define EVE_REGISTER_CALLABLE(TAG) \ namespace tag { struct TAG {}; } \ /**/ #define EVE_DECLARE_CALLABLE(TAG,NAME) \ template<typename C> struct if_; \ \ namespace detail \ { \ template<typename... Args> \ concept supports_ ## TAG = requires(Args&&... args) \ { \ { TAG( delay_t{}, EVE_CURRENT_API{}, EVE_FWD(args)...) }; \ }; \ \ template<typename Dummy> \ struct callable_object<tag::TAG, Dummy> \ { \ using tag_type = tag::TAG; \ \ template<typename Arg, typename... Args> \ requires ( tag_dispatchable<tag_type,Arg,Args...> \ || supports_ ## TAG<Arg,Args...> \ ) \ static EVE_FORCEINLINE constexpr auto call(Arg&& d, Args &&... args) noexcept \ { \ if constexpr( decorator<std::decay_t<Arg>> ) \ { \ check ( delay_t{}, ::eve::detail::types<std::decay_t<Arg>,tag_type>{}, \ EVE_FWD(args)... \ ); \ } \ else \ { \ check ( delay_t{}, ::eve::detail::types<tag_type>{}, EVE_FWD(d), \ EVE_FWD(args)... \ ); \ } \ \ if constexpr( tag_dispatchable<tag_type,Arg,Args...> ) \ { \ return tagged_dispatch ( tag_type{} \ , EVE_FWD(d), EVE_FWD(args)... \ ); \ } \ else \ { \ return TAG( delay_t{}, EVE_CURRENT_API{} \ , EVE_FWD(d), EVE_FWD(args)... \ ); \ } \ } \ \ template<typename... Args> \ requires ( tag_dispatchable<tag_type,Args...> \ || supports_ ## TAG<Args...> \ ) \ EVE_FORCEINLINE constexpr auto operator()(Args &&... args) const noexcept \ { \ return call(args...); \ } \ \ template<value Condition> \ EVE_FORCEINLINE constexpr auto operator[](Condition const &c) const noexcept \ requires( eve::supports_conditional<tag_type>::value ) \ { \ return [cond = if_(to_logical(c))](auto const&... args) EVE_LAMBDA_FORCEINLINE \ { \ return callable_object::call(cond, args...); \ }; \ } \ \ template<conditional_expr Condition> \ EVE_FORCEINLINE constexpr auto operator[](Condition const &c) const noexcept \ requires( eve::supports_conditional<tag_type>::value ) \ { \ return [c](auto const&... args) EVE_LAMBDA_FORCEINLINE \ { \ return callable_object::call(c, args...); \ }; \ } \ }; \ } \ /**/ #define EVE_ALIAS_CALLABLE(TAG, NAME) \ inline detail::callable_object<tag::TAG> const NAME = {} \ /**/ #define EVE_CALLABLE_API(TAG, NAME) \ using callable_##TAG = detail::callable_object<tag::TAG>; \ inline std::ostream& operator<<(std::ostream& os, detail::callable_object<tag::TAG> const&) \ { \ return os << #NAME; \ } /**/ #if defined(EVE_DOXYGEN_INVOKED) #define EVE_IMPLEMENT_CALLABLE(TAG, NAME) inline constexpr callable_##TAG NAME = {}; #else #define EVE_IMPLEMENT_CALLABLE(TAG, NAME) \ EVE_DECLARE_CALLABLE(TAG,NAME) \ EVE_CALLABLE_API(TAG,NAME) \ EVE_ALIAS_CALLABLE(TAG, NAME) \ /**/ #endif #if defined(EVE_DOXYGEN_INVOKED) #define EVE_MAKE_CALLABLE(TAG, NAME) inline constexpr callable_##TAG NAME = {}; #else #define EVE_MAKE_CALLABLE(TAG, NAME) \ EVE_REGISTER_CALLABLE(TAG) \ EVE_IMPLEMENT_CALLABLE(TAG,NAME) \ /**/ #endif // Flag a function to support delayed calls on given architecture #define EVE_SUPPORTS(ARCH) delay_t const &, ARCH const & // Flag a function to support delayed calls on given architecture #define EVE_MATCH_CALL(...) delay_t const &, ::eve::detail::types<__VA_ARGS__> const & // Flag a function to support delayed calls on given architecture #define EVE_RETARGET(ARCH) delay_t{}, ARCH {} namespace eve { //================================================================================================ // decorator definition, detection, combination and application to callables //================================================================================================ struct decorator_ {}; template<typename ID> concept decorator = std::derived_from<ID,decorator_>; template<typename Decoration> struct decorated; template<typename Decoration, typename... Args> struct decorated<Decoration(Args...)> : decorator_ { using base_type = Decoration; template<decorator Decorator> constexpr EVE_FORCEINLINE auto operator()(Decorator d) const noexcept { return Decoration::combine(d); } template <typename Function> struct fwding_lamda { Function f; template <typename... X> constexpr EVE_FORCEINLINE auto operator()(X&&... x) { return f(decorated{}, EVE_FWD(x)...); } }; template<typename Function> constexpr EVE_FORCEINLINE auto operator()(Function f) const noexcept { if constexpr( requires{ Decoration{}(f); } ) return Decoration{}(f); else return fwding_lamda<Function>{f}; } }; namespace detail { //============================================================================================== // basic type to support delayed calls struct delay_t {}; //============================================================================================== // Extension point for centralizing asserts & static_asserts template<typename Tag, typename... Args> void check(delay_t const&, Tag const&, Args const&... ) {} //============================================================================================== // callable_object forward declaration template<typename Tag, typename Dummy = void> struct callable_object; //============================================================================================== // User-facing tag-dispatch helper template <typename Tag, typename... Args> concept tag_dispatchable = requires(Tag tag, Args&&... args) { { tagged_dispatch(tag, EVE_FWD(args)...) }; }; } //============================================================================================== // Traits for foo[cond](...) supports template<typename Tag> struct supports_conditional : std::true_type {}; //============================================================================================== // Traits for optimized conversion support template<typename F> struct supports_optimized_conversion : std::false_type {}; }
60.553571
101
0.280891
the-moisrex
339a7139f5e28084d940d3172b0307c81c312f39
2,322
cpp
C++
exercise3/specs.cpp
alex-maleno/Fuzzing-Module
15aa673a2499dba6bd70a4aa5f86cd091a574434
[ "BSL-1.0" ]
1
2022-03-29T20:38:40.000Z
2022-03-29T20:38:40.000Z
exercise3/specs.cpp
alex-maleno/Fuzzing-Module
15aa673a2499dba6bd70a4aa5f86cd091a574434
[ "BSL-1.0" ]
null
null
null
exercise3/specs.cpp
alex-maleno/Fuzzing-Module
15aa673a2499dba6bd70a4aa5f86cd091a574434
[ "BSL-1.0" ]
null
null
null
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> #include "specs.h" Specs::Specs(int a, int f, int s){ alt = a; fuel = f; speed = s; } Specs::Specs(){ alt = 0; fuel = 0; speed = 0; } void Specs::choose_color() { std::string color; std::cout << "enter desired aircraft color: "; std::cin >> color; if (isNumber(color)) abort(); } void Specs::min_alt() { // bool too_low = true; std::cout << "enter aircraft minimum altitude: "; std::cin >> alt; // do { // too_low = false; if(alt < 0) { std::cout << "too low. crashing!" << std::endl; abort(); } else if (alt > 500) { std::cout << "too high. lowering to 500"; alt = 500; // too_low = true; } // } while(too_low); } void Specs::min_airspeed() { bool out_of_bounds = true; std::cout << "enter aircraft minimum airspeed: "; std::cin >> speed; do { out_of_bounds = false; if(speed < 0) abort(); if(speed < 100) { std::cout << "too low. please re-enter: "; std::cin >> speed; out_of_bounds = true; } else if (speed > 200) { std::cout << "too high. please re-enter: "; std::cin >> speed; out_of_bounds = true; } } while(out_of_bounds); } void Specs::fuel_cap() { bool too_high = true; std::cout << "enter fuel capacity: "; std::cin >> fuel; do { too_high = false; if(fuel < 0) abort(); if (fuel > 100) { std::cout << "too high. please re-enter: "; std::cin >> fuel; too_high = true; } } while(too_high); } bool Specs::isNumber(std::string str) { for (int i = 0; i < str.length(); i++) { if (isdigit(str[i]) == 0) return false; } return true; } int Specs::get_alt() { return alt; } int Specs::get_speed() { return speed; } int Specs::get_fuel() { return fuel; } void Specs::set_alt(int a) { alt = a; } void Specs::set_speed(int s) { speed = s; } void Specs::set_fuel(int f) { fuel = f; }
20.017241
56
0.47373
alex-maleno
339aeaec50f7842ffd5a827eb4f6648f0d15ae78
43,465
cpp
C++
source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp
frank-lesser/lldb
f5a215e2b1350fd0fa25780bc585c78b60b365a2
[ "Apache-2.0" ]
null
null
null
source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp
frank-lesser/lldb
f5a215e2b1350fd0fa25780bc585c78b60b365a2
[ "Apache-2.0" ]
null
null
null
source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp
frank-lesser/lldb
f5a215e2b1350fd0fa25780bc585c78b60b365a2
[ "Apache-2.0" ]
null
null
null
//===-- DynamicLoaderDarwin.cpp -----------------------------*- C++ -*-===// // // 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 "DynamicLoaderDarwin.h" #include "lldb/Breakpoint/StoppointCallbackContext.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" #include "lldb/Expression/DiagnosticManager.h" #include "lldb/Host/FileSystem.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Symbol/Function.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/ABI.h" #include "lldb/Target/ObjCLanguageRuntime.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadPlanCallFunction.h" #include "lldb/Target/ThreadPlanRunToAddress.h" #include "lldb/Utility/DataBuffer.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/State.h" //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN #ifdef ENABLE_DEBUG_PRINTF #include <stdio.h> #define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define DEBUG_PRINTF(fmt, ...) #endif #ifndef __APPLE__ #include "Utility/UuidCompatibility.h" #else #include <uuid/uuid.h> #endif #include <memory> using namespace lldb; using namespace lldb_private; // Constructor DynamicLoaderDarwin::DynamicLoaderDarwin(Process *process) : DynamicLoader(process), m_dyld_module_wp(), m_libpthread_module_wp(), m_pthread_getspecific_addr(), m_tid_to_tls_map(), m_dyld_image_infos(), m_dyld_image_infos_stop_id(UINT32_MAX), m_dyld(), m_mutex() {} // Destructor DynamicLoaderDarwin::~DynamicLoaderDarwin() {} /// Called after attaching a process. /// /// Allow DynamicLoader plug-ins to execute some code after /// attaching to a process. void DynamicLoaderDarwin::DidAttach() { PrivateInitialize(m_process); DoInitialImageFetch(); SetNotificationBreakpoint(); } /// Called after attaching a process. /// /// Allow DynamicLoader plug-ins to execute some code after /// attaching to a process. void DynamicLoaderDarwin::DidLaunch() { PrivateInitialize(m_process); DoInitialImageFetch(); SetNotificationBreakpoint(); } // Clear out the state of this class. void DynamicLoaderDarwin::Clear(bool clear_process) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (clear_process) m_process = nullptr; m_dyld_image_infos.clear(); m_dyld_image_infos_stop_id = UINT32_MAX; m_dyld.Clear(false); } ModuleSP DynamicLoaderDarwin::FindTargetModuleForImageInfo( ImageInfo &image_info, bool can_create, bool *did_create_ptr) { if (did_create_ptr) *did_create_ptr = false; Target &target = m_process->GetTarget(); const ModuleList &target_images = target.GetImages(); ModuleSpec module_spec(image_info.file_spec); module_spec.GetUUID() = image_info.uuid; ModuleSP module_sp(target_images.FindFirstModule(module_spec)); if (module_sp && !module_spec.GetUUID().IsValid() && !module_sp->GetUUID().IsValid()) { // No UUID, we must rely upon the cached module modification time and the // modification time of the file on disk if (module_sp->GetModificationTime() != FileSystem::Instance().GetModificationTime(module_sp->GetFileSpec())) module_sp.reset(); } if (!module_sp) { if (can_create) { // We'll call Target::ModulesDidLoad after all the modules have been // added to the target, don't let it be called for every one. module_sp = target.GetOrCreateModule(module_spec, false /* notify */); if (!module_sp || module_sp->GetObjectFile() == nullptr) module_sp = m_process->ReadModuleFromMemory(image_info.file_spec, image_info.address); if (did_create_ptr) *did_create_ptr = (bool)module_sp; } } return module_sp; } void DynamicLoaderDarwin::UnloadImages( const std::vector<lldb::addr_t> &solib_addresses) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (m_process->GetStopID() == m_dyld_image_infos_stop_id) return; Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); Target &target = m_process->GetTarget(); if (log) log->Printf("Removing %" PRId64 " modules.", (uint64_t)solib_addresses.size()); ModuleList unloaded_module_list; for (addr_t solib_addr : solib_addresses) { Address header; if (header.SetLoadAddress(solib_addr, &target)) { if (header.GetOffset() == 0) { ModuleSP module_to_remove(header.GetModule()); if (module_to_remove.get()) { if (log) log->Printf("Removing module at address 0x%" PRIx64, solib_addr); // remove the sections from the Target UnloadSections(module_to_remove); // add this to the list of modules to remove unloaded_module_list.AppendIfNeeded(module_to_remove); // remove the entry from the m_dyld_image_infos ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end(); for (pos = m_dyld_image_infos.begin(); pos != end; pos++) { if (solib_addr == (*pos).address) { m_dyld_image_infos.erase(pos); break; } } } } } } if (unloaded_module_list.GetSize() > 0) { if (log) { log->PutCString("Unloaded:"); unloaded_module_list.LogUUIDAndPaths( log, "DynamicLoaderDarwin::UnloadModules"); } m_process->GetTarget().GetImages().Remove(unloaded_module_list); m_dyld_image_infos_stop_id = m_process->GetStopID(); } } void DynamicLoaderDarwin::UnloadAllImages() { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); ModuleList unloaded_modules_list; Target &target = m_process->GetTarget(); const ModuleList &target_modules = target.GetImages(); std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex()); size_t num_modules = target_modules.GetSize(); ModuleSP dyld_sp(GetDYLDModule()); for (size_t i = 0; i < num_modules; i++) { ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i); // Don't remove dyld - else we'll lose our breakpoint notifying us about // libraries being re-loaded... if (module_sp.get() != nullptr && module_sp.get() != dyld_sp.get()) { UnloadSections(module_sp); unloaded_modules_list.Append(module_sp); } } if (unloaded_modules_list.GetSize() != 0) { if (log) { log->PutCString("Unloaded:"); unloaded_modules_list.LogUUIDAndPaths( log, "DynamicLoaderDarwin::UnloadAllImages"); } target.GetImages().Remove(unloaded_modules_list); m_dyld_image_infos.clear(); m_dyld_image_infos_stop_id = m_process->GetStopID(); } } // Update the load addresses for all segments in MODULE using the updated INFO // that is passed in. bool DynamicLoaderDarwin::UpdateImageLoadAddress(Module *module, ImageInfo &info) { bool changed = false; if (module) { ObjectFile *image_object_file = module->GetObjectFile(); if (image_object_file) { SectionList *section_list = image_object_file->GetSectionList(); if (section_list) { std::vector<uint32_t> inaccessible_segment_indexes; // We now know the slide amount, so go through all sections and update // the load addresses with the correct values. const size_t num_segments = info.segments.size(); for (size_t i = 0; i < num_segments; ++i) { // Only load a segment if it has protections. Things like __PAGEZERO // don't have any protections, and they shouldn't be slid SectionSP section_sp( section_list->FindSectionByName(info.segments[i].name)); if (info.segments[i].maxprot == 0) { inaccessible_segment_indexes.push_back(i); } else { const addr_t new_section_load_addr = info.segments[i].vmaddr + info.slide; static ConstString g_section_name_LINKEDIT("__LINKEDIT"); if (section_sp) { // __LINKEDIT sections from files in the shared cache can overlap // so check to see what the segment name is and pass "false" so // we don't warn of overlapping "Section" objects, and "true" for // all other sections. const bool warn_multiple = section_sp->GetName() != g_section_name_LINKEDIT; changed = m_process->GetTarget().SetSectionLoadAddress( section_sp, new_section_load_addr, warn_multiple); } } } // If the loaded the file (it changed) and we have segments that are // not readable or writeable, add them to the invalid memory region // cache for the process. This will typically only be the __PAGEZERO // segment in the main executable. We might be able to apply this more // generally to more sections that have no protections in the future, // but for now we are going to just do __PAGEZERO. if (changed && !inaccessible_segment_indexes.empty()) { for (uint32_t i = 0; i < inaccessible_segment_indexes.size(); ++i) { const uint32_t seg_idx = inaccessible_segment_indexes[i]; SectionSP section_sp( section_list->FindSectionByName(info.segments[seg_idx].name)); if (section_sp) { static ConstString g_pagezero_section_name("__PAGEZERO"); if (g_pagezero_section_name == section_sp->GetName()) { // __PAGEZERO never slides... const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr; const lldb::addr_t vmsize = info.segments[seg_idx].vmsize; Process::LoadRange pagezero_range(vmaddr, vmsize); m_process->AddInvalidMemoryRegion(pagezero_range); } } } } } } } // We might have an in memory image that was loaded as soon as it was created if (info.load_stop_id == m_process->GetStopID()) changed = true; else if (changed) { // Update the stop ID when this library was updated info.load_stop_id = m_process->GetStopID(); } return changed; } // Unload the segments in MODULE using the INFO that is passed in. bool DynamicLoaderDarwin::UnloadModuleSections(Module *module, ImageInfo &info) { bool changed = false; if (module) { ObjectFile *image_object_file = module->GetObjectFile(); if (image_object_file) { SectionList *section_list = image_object_file->GetSectionList(); if (section_list) { const size_t num_segments = info.segments.size(); for (size_t i = 0; i < num_segments; ++i) { SectionSP section_sp( section_list->FindSectionByName(info.segments[i].name)); if (section_sp) { const addr_t old_section_load_addr = info.segments[i].vmaddr + info.slide; if (m_process->GetTarget().SetSectionUnloaded( section_sp, old_section_load_addr)) changed = true; } else { Host::SystemLog(Host::eSystemLogWarning, "warning: unable to find and unload segment named " "'%s' in '%s' in macosx dynamic loader plug-in.\n", info.segments[i].name.AsCString("<invalid>"), image_object_file->GetFileSpec().GetPath().c_str()); } } } } } return changed; } // Given a JSON dictionary (from debugserver, most likely) of binary images // loaded in the inferior process, add the images to the ImageInfo collection. bool DynamicLoaderDarwin::JSONImageInformationIntoImageInfo( StructuredData::ObjectSP image_details, ImageInfo::collection &image_infos) { StructuredData::ObjectSP images_sp = image_details->GetAsDictionary()->GetValueForKey("images"); if (images_sp.get() == nullptr) return false; image_infos.resize(images_sp->GetAsArray()->GetSize()); for (size_t i = 0; i < image_infos.size(); i++) { StructuredData::ObjectSP image_sp = images_sp->GetAsArray()->GetItemAtIndex(i); if (image_sp.get() == nullptr || image_sp->GetAsDictionary() == nullptr) return false; StructuredData::Dictionary *image = image_sp->GetAsDictionary(); // clang-format off if (!image->HasKey("load_address") || !image->HasKey("pathname") || !image->HasKey("mod_date") || !image->HasKey("mach_header") || image->GetValueForKey("mach_header")->GetAsDictionary() == nullptr || !image->HasKey("segments") || image->GetValueForKey("segments")->GetAsArray() == nullptr || !image->HasKey("uuid")) { return false; } // clang-format on image_infos[i].address = image->GetValueForKey("load_address")->GetAsInteger()->GetValue(); image_infos[i].mod_date = image->GetValueForKey("mod_date")->GetAsInteger()->GetValue(); image_infos[i].file_spec.SetFile( image->GetValueForKey("pathname")->GetAsString()->GetValue(), FileSpec::Style::native); StructuredData::Dictionary *mh = image->GetValueForKey("mach_header")->GetAsDictionary(); image_infos[i].header.magic = mh->GetValueForKey("magic")->GetAsInteger()->GetValue(); image_infos[i].header.cputype = mh->GetValueForKey("cputype")->GetAsInteger()->GetValue(); image_infos[i].header.cpusubtype = mh->GetValueForKey("cpusubtype")->GetAsInteger()->GetValue(); image_infos[i].header.filetype = mh->GetValueForKey("filetype")->GetAsInteger()->GetValue(); if (image->HasKey("min_version_os_name")) { std::string os_name = image->GetValueForKey("min_version_os_name") ->GetAsString() ->GetValue(); if (os_name == "macosx") image_infos[i].os_type = llvm::Triple::MacOSX; else if (os_name == "ios" || os_name == "iphoneos") image_infos[i].os_type = llvm::Triple::IOS; else if (os_name == "tvos") image_infos[i].os_type = llvm::Triple::TvOS; else if (os_name == "watchos") image_infos[i].os_type = llvm::Triple::WatchOS; // NEED_BRIDGEOS_TRIPLE else if (os_name == "bridgeos") // NEED_BRIDGEOS_TRIPLE image_infos[i].os_type = llvm::Triple::BridgeOS; } if (image->HasKey("min_version_os_sdk")) { image_infos[i].min_version_os_sdk = image->GetValueForKey("min_version_os_sdk") ->GetAsString() ->GetValue(); } // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't // currently send them in the reply. if (mh->HasKey("flags")) image_infos[i].header.flags = mh->GetValueForKey("flags")->GetAsInteger()->GetValue(); else image_infos[i].header.flags = 0; if (mh->HasKey("ncmds")) image_infos[i].header.ncmds = mh->GetValueForKey("ncmds")->GetAsInteger()->GetValue(); else image_infos[i].header.ncmds = 0; if (mh->HasKey("sizeofcmds")) image_infos[i].header.sizeofcmds = mh->GetValueForKey("sizeofcmds")->GetAsInteger()->GetValue(); else image_infos[i].header.sizeofcmds = 0; StructuredData::Array *segments = image->GetValueForKey("segments")->GetAsArray(); uint32_t segcount = segments->GetSize(); for (size_t j = 0; j < segcount; j++) { Segment segment; StructuredData::Dictionary *seg = segments->GetItemAtIndex(j)->GetAsDictionary(); segment.name = ConstString(seg->GetValueForKey("name")->GetAsString()->GetValue()); segment.vmaddr = seg->GetValueForKey("vmaddr")->GetAsInteger()->GetValue(); segment.vmsize = seg->GetValueForKey("vmsize")->GetAsInteger()->GetValue(); segment.fileoff = seg->GetValueForKey("fileoff")->GetAsInteger()->GetValue(); segment.filesize = seg->GetValueForKey("filesize")->GetAsInteger()->GetValue(); segment.maxprot = seg->GetValueForKey("maxprot")->GetAsInteger()->GetValue(); // Fields that aren't used by DynamicLoaderDarwin so debugserver doesn't // currently send them in the reply. if (seg->HasKey("initprot")) segment.initprot = seg->GetValueForKey("initprot")->GetAsInteger()->GetValue(); else segment.initprot = 0; if (seg->HasKey("flags")) segment.flags = seg->GetValueForKey("flags")->GetAsInteger()->GetValue(); else segment.flags = 0; if (seg->HasKey("nsects")) segment.nsects = seg->GetValueForKey("nsects")->GetAsInteger()->GetValue(); else segment.nsects = 0; image_infos[i].segments.push_back(segment); } image_infos[i].uuid.SetFromOptionalStringRef( image->GetValueForKey("uuid")->GetAsString()->GetValue()); // All sections listed in the dyld image info structure will all either be // fixed up already, or they will all be off by a single slide amount that // is determined by finding the first segment that is at file offset zero // which also has bytes (a file size that is greater than zero) in the // object file. // Determine the slide amount (if any) const size_t num_sections = image_infos[i].segments.size(); for (size_t k = 0; k < num_sections; ++k) { // Iterate through the object file sections to find the first section // that starts of file offset zero and that has bytes in the file... if ((image_infos[i].segments[k].fileoff == 0 && image_infos[i].segments[k].filesize > 0) || (image_infos[i].segments[k].name == "__TEXT")) { image_infos[i].slide = image_infos[i].address - image_infos[i].segments[k].vmaddr; // We have found the slide amount, so we can exit this for loop. break; } } } return true; } void DynamicLoaderDarwin::UpdateSpecialBinariesFromNewImageInfos( ImageInfo::collection &image_infos) { uint32_t exe_idx = UINT32_MAX; uint32_t dyld_idx = UINT32_MAX; Target &target = m_process->GetTarget(); Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); ConstString g_dyld_sim_filename("dyld_sim"); ArchSpec target_arch = target.GetArchitecture(); const size_t image_infos_size = image_infos.size(); for (size_t i = 0; i < image_infos_size; i++) { if (image_infos[i].header.filetype == llvm::MachO::MH_DYLINKER) { // In a "simulator" process (an x86 process that is // ios/tvos/watchos/bridgeos) we will have two dyld modules -- // a "dyld" that we want to keep track of, and a "dyld_sim" which // we don't need to keep track of here. If the target is an x86 // system and the OS of the dyld binary is ios/tvos/watchos/bridgeos, // then we are looking at dyld_sym. // debugserver has only recently (late 2016) started sending up the os // type for each binary it sees -- so if we don't have an os type, use a // filename check as our next best guess. if (image_infos[i].os_type == llvm::Triple::OSType::UnknownOS) { if (image_infos[i].file_spec.GetFilename() != g_dyld_sim_filename) { dyld_idx = i; } } else if (target_arch.GetTriple().getArch() == llvm::Triple::x86 || target_arch.GetTriple().getArch() == llvm::Triple::x86_64) { if (image_infos[i].os_type != llvm::Triple::OSType::IOS && image_infos[i].os_type != llvm::Triple::TvOS && image_infos[i].os_type != llvm::Triple::WatchOS) { // NEED_BRIDGEOS_TRIPLE image_infos[i].os_type != llvm::Triple::BridgeOS) { dyld_idx = i; } } else { // catch-all for any other environment -- trust that dyld is actually // dyld dyld_idx = i; } } else if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE) { exe_idx = i; } } if (exe_idx != UINT32_MAX) { const bool can_create = true; ModuleSP exe_module_sp(FindTargetModuleForImageInfo(image_infos[exe_idx], can_create, nullptr)); if (exe_module_sp) { if (log) log->Printf("Found executable module: %s", exe_module_sp->GetFileSpec().GetPath().c_str()); target.GetImages().AppendIfNeeded(exe_module_sp); UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]); if (exe_module_sp.get() != target.GetExecutableModulePointer()) { target.SetExecutableModule(exe_module_sp, eLoadDependentsNo); } } } if (dyld_idx != UINT32_MAX) { const bool can_create = true; ModuleSP dyld_sp = FindTargetModuleForImageInfo(image_infos[dyld_idx], can_create, nullptr); if (dyld_sp.get()) { if (log) log->Printf("Found dyld module: %s", dyld_sp->GetFileSpec().GetPath().c_str()); target.GetImages().AppendIfNeeded(dyld_sp); UpdateImageLoadAddress(dyld_sp.get(), image_infos[dyld_idx]); SetDYLDModule(dyld_sp); } } } void DynamicLoaderDarwin::UpdateDYLDImageInfoFromNewImageInfo( ImageInfo &image_info) { if (image_info.header.filetype == llvm::MachO::MH_DYLINKER) { const bool can_create = true; ModuleSP dyld_sp = FindTargetModuleForImageInfo(image_info, can_create, nullptr); if (dyld_sp.get()) { Target &target = m_process->GetTarget(); target.GetImages().AppendIfNeeded(dyld_sp); UpdateImageLoadAddress(dyld_sp.get(), image_info); SetDYLDModule(dyld_sp); } } } void DynamicLoaderDarwin::SetDYLDModule(lldb::ModuleSP &dyld_module_sp) { m_dyld_module_wp = dyld_module_sp; } ModuleSP DynamicLoaderDarwin::GetDYLDModule() { ModuleSP dyld_sp(m_dyld_module_wp.lock()); return dyld_sp; } bool DynamicLoaderDarwin::AddModulesUsingImageInfos( ImageInfo::collection &image_infos) { std::lock_guard<std::recursive_mutex> guard(m_mutex); // Now add these images to the main list. ModuleList loaded_module_list; Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); Target &target = m_process->GetTarget(); ModuleList &target_images = target.GetImages(); for (uint32_t idx = 0; idx < image_infos.size(); ++idx) { if (log) { log->Printf("Adding new image at address=0x%16.16" PRIx64 ".", image_infos[idx].address); image_infos[idx].PutToLog(log); } m_dyld_image_infos.push_back(image_infos[idx]); ModuleSP image_module_sp( FindTargetModuleForImageInfo(image_infos[idx], true, nullptr)); if (image_module_sp) { ObjectFile *objfile = image_module_sp->GetObjectFile(); if (objfile) { SectionList *sections = objfile->GetSectionList(); if (sections) { ConstString commpage_dbstr("__commpage"); Section *commpage_section = sections->FindSectionByName(commpage_dbstr).get(); if (commpage_section) { ModuleSpec module_spec(objfile->GetFileSpec(), image_infos[idx].GetArchitecture()); module_spec.GetObjectName() = commpage_dbstr; ModuleSP commpage_image_module_sp( target_images.FindFirstModule(module_spec)); if (!commpage_image_module_sp) { module_spec.SetObjectOffset(objfile->GetFileOffset() + commpage_section->GetFileOffset()); module_spec.SetObjectSize(objfile->GetByteSize()); commpage_image_module_sp = target.GetOrCreateModule(module_spec, true /* notify */); if (!commpage_image_module_sp || commpage_image_module_sp->GetObjectFile() == nullptr) { commpage_image_module_sp = m_process->ReadModuleFromMemory( image_infos[idx].file_spec, image_infos[idx].address); // Always load a memory image right away in the target in case // we end up trying to read the symbol table from memory... The // __LINKEDIT will need to be mapped so we can figure out where // the symbol table bits are... bool changed = false; UpdateImageLoadAddress(commpage_image_module_sp.get(), image_infos[idx]); target.GetImages().Append(commpage_image_module_sp); if (changed) { image_infos[idx].load_stop_id = m_process->GetStopID(); loaded_module_list.AppendIfNeeded(commpage_image_module_sp); } } } } } } // UpdateImageLoadAddress will return true if any segments change load // address. We need to check this so we don't mention that all loaded // shared libraries are newly loaded each time we hit out dyld breakpoint // since dyld will list all shared libraries each time. if (UpdateImageLoadAddress(image_module_sp.get(), image_infos[idx])) { target_images.AppendIfNeeded(image_module_sp); loaded_module_list.AppendIfNeeded(image_module_sp); } } } if (loaded_module_list.GetSize() > 0) { if (log) loaded_module_list.LogUUIDAndPaths(log, "DynamicLoaderDarwin::ModulesDidLoad"); m_process->GetTarget().ModulesDidLoad(loaded_module_list); } return true; } // On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch // functions written in hand-written assembly, and also have hand-written // unwind information in the eh_frame section. Normally we prefer analyzing // the assembly instructions of a currently executing frame to unwind from that // frame -- but on hand-written functions this profiling can fail. We should // use the eh_frame instructions for these functions all the time. // // As an aside, it would be better if the eh_frame entries had a flag (or were // extensible so they could have an Apple-specific flag) which indicates that // the instructions are asynchronous -- accurate at every instruction, instead // of our normal default assumption that they are not. bool DynamicLoaderDarwin::AlwaysRelyOnEHUnwindInfo(SymbolContext &sym_ctx) { ModuleSP module_sp; if (sym_ctx.symbol) { module_sp = sym_ctx.symbol->GetAddressRef().GetModule(); } if (module_sp.get() == nullptr && sym_ctx.function) { module_sp = sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule(); } if (module_sp.get() == nullptr) return false; ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime(); return objc_runtime != nullptr && objc_runtime->IsModuleObjCLibrary(module_sp); } // Dump a Segment to the file handle provided. void DynamicLoaderDarwin::Segment::PutToLog(Log *log, lldb::addr_t slide) const { if (log) { if (slide == 0) log->Printf("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")", name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize); else log->Printf("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") slide = 0x%" PRIx64, name.AsCString(""), vmaddr + slide, vmaddr + slide + vmsize, slide); } } const DynamicLoaderDarwin::Segment * DynamicLoaderDarwin::ImageInfo::FindSegment(ConstString name) const { const size_t num_segments = segments.size(); for (size_t i = 0; i < num_segments; ++i) { if (segments[i].name == name) return &segments[i]; } return nullptr; } // Dump an image info structure to the file handle provided. void DynamicLoaderDarwin::ImageInfo::PutToLog(Log *log) const { if (!log) return; if (address == LLDB_INVALID_ADDRESS) { LLDB_LOG(log, "modtime={0:x+8} uuid={1} path='{2}' (UNLOADED)", mod_date, uuid.GetAsString(), file_spec.GetPath()); } else { LLDB_LOG(log, "address={0:x+16} modtime={1:x+8} uuid={2} path='{3}'", address, mod_date, uuid.GetAsString(), file_spec.GetPath()); for (uint32_t i = 0; i < segments.size(); ++i) segments[i].PutToLog(log, slide); } } void DynamicLoaderDarwin::PrivateInitialize(Process *process) { DEBUG_PRINTF("DynamicLoaderDarwin::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState())); Clear(true); m_process = process; m_process->GetTarget().ClearAllLoadedSections(); } // Member function that gets called when the process state changes. void DynamicLoaderDarwin::PrivateProcessStateChanged(Process *process, StateType state) { DEBUG_PRINTF("DynamicLoaderDarwin::%s(%s)\n", __FUNCTION__, StateAsCString(state)); switch (state) { case eStateConnected: case eStateAttaching: case eStateLaunching: case eStateInvalid: case eStateUnloaded: case eStateExited: case eStateDetached: Clear(false); break; case eStateStopped: // Keep trying find dyld and set our notification breakpoint each time we // stop until we succeed if (!DidSetNotificationBreakpoint() && m_process->IsAlive()) { if (NeedToDoInitialImageFetch()) DoInitialImageFetch(); SetNotificationBreakpoint(); } break; case eStateRunning: case eStateStepping: case eStateCrashed: case eStateSuspended: break; } } ThreadPlanSP DynamicLoaderDarwin::GetStepThroughTrampolinePlan(Thread &thread, bool stop_others) { ThreadPlanSP thread_plan_sp; StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get(); const SymbolContext &current_context = current_frame->GetSymbolContext(eSymbolContextSymbol); Symbol *current_symbol = current_context.symbol; Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); TargetSP target_sp(thread.CalculateTarget()); if (current_symbol != nullptr) { std::vector<Address> addresses; if (current_symbol->IsTrampoline()) { ConstString trampoline_name = current_symbol->GetMangled().GetName( current_symbol->GetLanguage(), Mangled::ePreferMangled); if (trampoline_name) { const ModuleList &images = target_sp->GetImages(); SymbolContextList code_symbols; images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode, code_symbols); size_t num_code_symbols = code_symbols.GetSize(); if (num_code_symbols > 0) { for (uint32_t i = 0; i < num_code_symbols; i++) { SymbolContext context; AddressRange addr_range; if (code_symbols.GetContextAtIndex(i, context)) { context.GetAddressRange(eSymbolContextEverything, 0, false, addr_range); addresses.push_back(addr_range.GetBaseAddress()); if (log) { addr_t load_addr = addr_range.GetBaseAddress().GetLoadAddress(target_sp.get()); log->Printf("Found a trampoline target symbol at 0x%" PRIx64 ".", load_addr); } } } } SymbolContextList reexported_symbols; images.FindSymbolsWithNameAndType( trampoline_name, eSymbolTypeReExported, reexported_symbols); size_t num_reexported_symbols = reexported_symbols.GetSize(); if (num_reexported_symbols > 0) { for (uint32_t i = 0; i < num_reexported_symbols; i++) { SymbolContext context; if (reexported_symbols.GetContextAtIndex(i, context)) { if (context.symbol) { Symbol *actual_symbol = context.symbol->ResolveReExportedSymbol(*target_sp.get()); if (actual_symbol) { const Address actual_symbol_addr = actual_symbol->GetAddress(); if (actual_symbol_addr.IsValid()) { addresses.push_back(actual_symbol_addr); if (log) { lldb::addr_t load_addr = actual_symbol_addr.GetLoadAddress(target_sp.get()); log->Printf( "Found a re-exported symbol: %s at 0x%" PRIx64 ".", actual_symbol->GetName().GetCString(), load_addr); } } } } } } } SymbolContextList indirect_symbols; images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeResolver, indirect_symbols); size_t num_indirect_symbols = indirect_symbols.GetSize(); if (num_indirect_symbols > 0) { for (uint32_t i = 0; i < num_indirect_symbols; i++) { SymbolContext context; AddressRange addr_range; if (indirect_symbols.GetContextAtIndex(i, context)) { context.GetAddressRange(eSymbolContextEverything, 0, false, addr_range); addresses.push_back(addr_range.GetBaseAddress()); if (log) { addr_t load_addr = addr_range.GetBaseAddress().GetLoadAddress(target_sp.get()); log->Printf("Found an indirect target symbol at 0x%" PRIx64 ".", load_addr); } } } } } } else if (current_symbol->GetType() == eSymbolTypeReExported) { // I am not sure we could ever end up stopped AT a re-exported symbol. // But just in case: const Symbol *actual_symbol = current_symbol->ResolveReExportedSymbol(*(target_sp.get())); if (actual_symbol) { Address target_addr(actual_symbol->GetAddress()); if (target_addr.IsValid()) { if (log) log->Printf( "Found a re-exported symbol: %s pointing to: %s at 0x%" PRIx64 ".", current_symbol->GetName().GetCString(), actual_symbol->GetName().GetCString(), target_addr.GetLoadAddress(target_sp.get())); addresses.push_back(target_addr.GetLoadAddress(target_sp.get())); } } } if (addresses.size() > 0) { // First check whether any of the addresses point to Indirect symbols, // and if they do, resolve them: std::vector<lldb::addr_t> load_addrs; for (Address address : addresses) { Symbol *symbol = address.CalculateSymbolContextSymbol(); if (symbol && symbol->IsIndirect()) { Status error; Address symbol_address = symbol->GetAddress(); addr_t resolved_addr = thread.GetProcess()->ResolveIndirectFunction( &symbol_address, error); if (error.Success()) { load_addrs.push_back(resolved_addr); if (log) log->Printf("ResolveIndirectFunction found resolved target for " "%s at 0x%" PRIx64 ".", symbol->GetName().GetCString(), resolved_addr); } } else { load_addrs.push_back(address.GetLoadAddress(target_sp.get())); } } thread_plan_sp = std::make_shared<ThreadPlanRunToAddress>( thread, load_addrs, stop_others); } } else { if (log) log->Printf("Could not find symbol for step through."); } return thread_plan_sp; } size_t DynamicLoaderDarwin::FindEquivalentSymbols( lldb_private::Symbol *original_symbol, lldb_private::ModuleList &images, lldb_private::SymbolContextList &equivalent_symbols) { ConstString trampoline_name = original_symbol->GetMangled().GetName( original_symbol->GetLanguage(), Mangled::ePreferMangled); if (!trampoline_name) return 0; size_t initial_size = equivalent_symbols.GetSize(); static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Za-z0-9\\$]+)$"; std::string equivalent_regex_buf("^"); equivalent_regex_buf.append(trampoline_name.GetCString()); equivalent_regex_buf.append(resolver_name_regex); RegularExpression equivalent_name_regex(equivalent_regex_buf); const bool append = true; images.FindSymbolsMatchingRegExAndType(equivalent_name_regex, eSymbolTypeCode, equivalent_symbols, append); return equivalent_symbols.GetSize() - initial_size; } lldb::ModuleSP DynamicLoaderDarwin::GetPThreadLibraryModule() { ModuleSP module_sp = m_libpthread_module_wp.lock(); if (!module_sp) { SymbolContextList sc_list; ModuleSpec module_spec; module_spec.GetFileSpec().GetFilename().SetCString( "libsystem_pthread.dylib"); ModuleList module_list; if (m_process->GetTarget().GetImages().FindModules(module_spec, module_list)) { if (module_list.GetSize() == 1) { module_sp = module_list.GetModuleAtIndex(0); if (module_sp) m_libpthread_module_wp = module_sp; } } } return module_sp; } Address DynamicLoaderDarwin::GetPthreadSetSpecificAddress() { if (!m_pthread_getspecific_addr.IsValid()) { ModuleSP module_sp = GetPThreadLibraryModule(); if (module_sp) { lldb_private::SymbolContextList sc_list; module_sp->FindSymbolsWithNameAndType(ConstString("pthread_getspecific"), eSymbolTypeCode, sc_list); SymbolContext sc; if (sc_list.GetContextAtIndex(0, sc)) { if (sc.symbol) m_pthread_getspecific_addr = sc.symbol->GetAddress(); } } } return m_pthread_getspecific_addr; } lldb::addr_t DynamicLoaderDarwin::GetThreadLocalData(const lldb::ModuleSP module_sp, const lldb::ThreadSP thread_sp, lldb::addr_t tls_file_addr) { if (!thread_sp || !module_sp) return LLDB_INVALID_ADDRESS; std::lock_guard<std::recursive_mutex> guard(m_mutex); const uint32_t addr_size = m_process->GetAddressByteSize(); uint8_t buf[sizeof(lldb::addr_t) * 3]; lldb_private::Address tls_addr; if (module_sp->ResolveFileAddress(tls_file_addr, tls_addr)) { Status error; const size_t tsl_data_size = addr_size * 3; Target &target = m_process->GetTarget(); if (target.ReadMemory(tls_addr, false, buf, tsl_data_size, error) == tsl_data_size) { const ByteOrder byte_order = m_process->GetByteOrder(); DataExtractor data(buf, sizeof(buf), byte_order, addr_size); lldb::offset_t offset = addr_size; // Skip the first pointer const lldb::addr_t pthread_key = data.GetAddress(&offset); const lldb::addr_t tls_offset = data.GetAddress(&offset); if (pthread_key != 0) { // First check to see if we have already figured out the location of // TLS data for the pthread_key on a specific thread yet. If we have we // can re-use it since its location will not change unless the process // execs. const tid_t tid = thread_sp->GetID(); auto tid_pos = m_tid_to_tls_map.find(tid); if (tid_pos != m_tid_to_tls_map.end()) { auto tls_pos = tid_pos->second.find(pthread_key); if (tls_pos != tid_pos->second.end()) { return tls_pos->second + tls_offset; } } StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0); if (frame_sp) { ClangASTContext *clang_ast_context = target.GetScratchClangASTContext(); if (!clang_ast_context) return LLDB_INVALID_ADDRESS; CompilerType clang_void_ptr_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType(); Address pthread_getspecific_addr = GetPthreadSetSpecificAddress(); if (pthread_getspecific_addr.IsValid()) { EvaluateExpressionOptions options; lldb::ThreadPlanSP thread_plan_sp(new ThreadPlanCallFunction( *thread_sp, pthread_getspecific_addr, clang_void_ptr_type, llvm::ArrayRef<lldb::addr_t>(pthread_key), options)); DiagnosticManager execution_errors; ExecutionContext exe_ctx(thread_sp); lldb::ExpressionResults results = m_process->RunThreadPlan( exe_ctx, thread_plan_sp, options, execution_errors); if (results == lldb::eExpressionCompleted) { lldb::ValueObjectSP result_valobj_sp = thread_plan_sp->GetReturnValueObject(); if (result_valobj_sp) { const lldb::addr_t pthread_key_data = result_valobj_sp->GetValueAsUnsigned(0); if (pthread_key_data) { m_tid_to_tls_map[tid].insert( std::make_pair(pthread_key, pthread_key_data)); return pthread_key_data + tls_offset; } } } } } } } } return LLDB_INVALID_ADDRESS; } bool DynamicLoaderDarwin::UseDYLDSPI(Process *process) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); bool use_new_spi_interface = false; llvm::VersionTuple version = process->GetHostOSVersion(); if (!version.empty()) { const llvm::Triple::OSType os_type = process->GetTarget().GetArchitecture().GetTriple().getOS(); // macOS 10.12 and newer if (os_type == llvm::Triple::MacOSX && version >= llvm::VersionTuple(10, 12)) use_new_spi_interface = true; // iOS 10 and newer if (os_type == llvm::Triple::IOS && version >= llvm::VersionTuple(10)) use_new_spi_interface = true; // tvOS 10 and newer if (os_type == llvm::Triple::TvOS && version >= llvm::VersionTuple(10)) use_new_spi_interface = true; // watchOS 3 and newer if (os_type == llvm::Triple::WatchOS && version >= llvm::VersionTuple(3)) use_new_spi_interface = true; // NEED_BRIDGEOS_TRIPLE // Any BridgeOS // NEED_BRIDGEOS_TRIPLE if (os_type == llvm::Triple::BridgeOS) // NEED_BRIDGEOS_TRIPLE use_new_spi_interface = true; } if (log) { if (use_new_spi_interface) log->Printf( "DynamicLoaderDarwin::UseDYLDSPI: Use new DynamicLoader plugin"); else log->Printf( "DynamicLoaderDarwin::UseDYLDSPI: Use old DynamicLoader plugin"); } return use_new_spi_interface; }
38.842717
87
0.634787
frank-lesser
339bad356e8e18d513bd0f16595581fb5db67491
11,051
cpp
C++
ProjectEuler+/euler-0333.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
null
null
null
ProjectEuler+/euler-0333.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
null
null
null
ProjectEuler+/euler-0333.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
1
2021-05-28T11:14:34.000Z
2021-05-28T11:14:34.000Z
// //////////////////////////////////////////////////////// // # Title // Special partitions // // # URL // https://projecteuler.net/problem=333 // http://euler.stephan-brumme.com/333/ // // # Problem // All positive integers can be partitioned in such a way that each and every term of the partition can be expressed as `2^i * 3^j`, where `i,j >= 0`. // // Let's consider only those such partitions where none of the terms can divide any of the other terms. // For example, the partition of `17 = 2 + 6 + 9 = 2^1 * 3^0 + 2^1 * 3^1 + 2^0 * 3^2` would not be valid since 2 can divide 6. // Neither would the partition `17 = 16 + 1 = 2^4 * 3^0 + 2^0 * 3^0` since 1 can divide 16. // The only valid partition of `17` would be `8 + 9 = 2^3 * 3^0 + 2^0 * 3^2`. // // Many integers have more than one valid partition, the first being `11` having the following two partitions. // `11 = 2 + 9 = 2^1 * 3^0 + 2^0 * 3^2` // `11 = 8 + 3 = 2^3 * 3^0 + 2^0 * 3^1` // // Let's define `P(n)` as the number of valid partitions of `n`. For example, `P(11) = 2`. // // Let's consider only the prime integers `q` which would have a single valid partition such as `P(17)`. // // The sum of the primes `q < 100` such that `P(q)=1` equals 233. // // Find the sum of the primes `q < 1000000` such that `P(q)=1`. // // # Solved by // Stephan Brumme // September 2017 // // # Algorithm // My ''bruteForce()'' attempt can verify `P(q < 100) = 1`: it creates a set of all powers `2^i 3^j < 100` and then analyzes each subset. // Unfortuately there are 143 such powers for `q < 10^6` so that ''bruteForce()'' would have to check `2^143` subsets - that's impossible. // // So I "restarted" my thinking process: if I have a term `2^a 3^b` and then each other term `2^c 3^d` must be neither a multiple nor a divisor. // That means if `a > c` then `b < d` because otherwise `2^a 3^b` would be a multiple of `2^c 3^d`. // And if `a < c` then `b > d` because otherwise `2^a 3^b` would be a divisor of `2^c 3^d`. // // I am free to "sort" all elements of a partition and decided to apply the following rule: // the first element has the smallest `2^x` and the largest `3^y` of all terms of the partition. // That's exactly how the example is sorted (coincidence ?): // `17 = 2^3 * 3^0 + 2^0 * 3^2` // // The first step is iterate over each possible `2^a * 3^b` so I can identify all numbers that can be reached by partitions consisting of only one term. // Then I go through all numbers in ascending order: // only if there was a way to reach a number with (at least) one term then I could add one more term - that must obey the rule if `a < c` then `b > d` // // My actual implementation may look a bit confusing because I tried hard to trim memory consumption: // - a unique ID is assigned to each of 143 terms `2^a * 3^b < 10^6` (see container ''ids'') // - create 143 bit vectors ''reachable'' with `10^6` elements: an element is true if there is at least one partition and the "last" term carries that ID // - create 143 bit vectors ''multiple'' with `10^6` elements: an element is true if there is more than one partition and the "last" term carries that ID // // The bit vectors ''reachable'' and ''multiple'' are filled step-by-step as I iterate over all `10^6` numbers. // - ignore each ID of the current number ''i'' where ''reachable[id][i] == false'' // - else add one more term: iterate over each possible successor where `a < c` and `b > d` // - set ''reachable[i + newTerm]'' accordingly, update ''multiple[i + newTerm]'' as well // - if the current number ''i'' has at most one ''reachable[id][i]'' that is true (and even this must be ''multiple[id][i] == false'') then I found a unique partition // // # Note // My final program was heavily affected by the desire to keep memory consumption low (it still needs about 38 MByte). // The bit vectors ''reachable'' and ''multiple'' could be merged into a single vector of ''unsigned char'' that just counts all combinations. // But this would require at least one byte per ID and per number, thus 143 MByte. // // The whole concept of using IDs could be replaced by temporarily allowing terms `2^a * 3^b > 10^6` and filtering them in the last step. // However, this further increases memory consumption. // // # Alternative // It seems you could write a Dynamic Programming algorithm - I tried but failed. #include <iostream> #include <vector> #include <set> #include <algorithm> // ---------- standard prime sieve from my toolbox ---------- // odd prime numbers are marked as "true" in a bitvector std::vector<bool> sieve; // return true, if x is a prime number bool isPrime(unsigned int x) { // handle even numbers if ((x & 1) == 0) return x == 2; // lookup for odd numbers return sieve[x >> 1]; } // find all prime numbers from 2 to size void fillSieve(unsigned int size) { // store only odd numbers const unsigned int half = (size >> 1) + 1; // allocate memory sieve.resize(half, true); // 1 is not a prime number sieve[0] = false; // process all relevant prime factors for (unsigned int i = 1; 2 * i*i < half; i++) // do we have a prime factor ? if (sieve[i]) { // mark all its multiples as false unsigned int current = 3 * i + 1; while (current < half) { sieve[current] = false; current += 2 * i + 1; } } } // ---------- problem specific code ---------- // slow algorithm unsigned int bruteForce(unsigned int limit) { // create all terms 2^i * 3^j std::vector<unsigned int> terms; for (unsigned int two = 1; two <= limit; two *= 2) for (unsigned int three = 1; two * three <= limit; three *= 3) terms.push_back(two * three); // each term is a multiple of 1, so I can safely remove it terms.erase(terms.begin()); // in ascending order std::sort(terms.begin(), terms.end()); // mainly for debugging: keep track of all terms of all solutions typedef std::vector<unsigned int> Solution; std::vector<std::vector<Solution>> solutions(limit + 1); // analyze all subsets unsigned int maxMask = 1 << terms.size(); for (unsigned int mask = 1; mask < maxMask; mask++) { unsigned int sum = 0; Solution currentTerms; // collect all terms for (unsigned int pos = 0; pos < terms.size(); pos++) { unsigned int posMask = 1 << pos; if ((posMask & mask) == 0) continue; // yes, use that term sum += terms[pos]; currentTerms.push_back(terms[pos]); } // too large ? if (sum > limit) continue; // no term must a multiple of any other term bool isGood = true; for (unsigned int i = 0; i < currentTerms.size() && isGood; i++) for (unsigned int j = i + 1; j < currentTerms.size() && isGood; j++) isGood = (currentTerms[j] % currentTerms[i] > 0); // note: currentTerms was sorted ascendingly // all terms are coprime if (isGood) solutions[sum].push_back(currentTerms); } // add all primes with exactly one solution unsigned int result = 0; for (unsigned int i = 0; i <= limit; i++) if (solutions[i].size() == 1 && isPrime(i)) { // display terms auto current = solutions[i].front(); std::cout << i << "="; for (auto x : current) std::cout << x << " "; std::cout << std::endl; result += i; } return result; } // return 2^two * 3^three unsigned int power(unsigned int two, unsigned int three) { // fast exponentiation for 3^three unsigned int result = 1; unsigned int base = 3; while (three > 0) { if (three & 1) result *= base; base *= base; three >>= 1; } // multiplying by 2^two is a bitshift return result << two; } int main() { unsigned int limit = 1000000; std::cin >> limit; // solve small inputs //std::cout << bruteForce(limit) << std::endl; // count how many powers of 2 and 3 are below the limit unsigned int numPowerOfTwo = 0; unsigned int numPowerOfThree = 0; while (power(numPowerOfTwo, 0) <= limit) numPowerOfTwo++; while (power(0, numPowerOfThree) <= limit) numPowerOfThree++; // assign a unique ID to each 2^i * 3^j <= limit const unsigned char TooLarge = 0; unsigned char nextId = 1; unsigned char ids[30][20]; // more than big enough std::vector<std::pair<unsigned int, unsigned int>> reverseId(1); // 0 is dummy ID (TooLarge) for (unsigned int expTwo = 0; expTwo < numPowerOfTwo; expTwo++) for (unsigned int expThree = 0; expThree < numPowerOfThree; expThree++) { auto current = power(expTwo, expThree); if (current <= limit) { reverseId.push_back({ expTwo, expThree }); ids[expTwo][expThree] = nextId++; } else ids[expTwo][expThree] = TooLarge; } // => only 143 out of 260 pairs // allocate memory, will store the number of ways to reach a value std::vector<std::vector<bool>> reachable(nextId); for (auto& x : reachable) x.resize(limit + 1, 0); std::vector<std::vector<bool>> multiple (nextId); for (auto& x : multiple) x.resize(limit + 1, 0); // seed values for (unsigned int id = 1; id < reverseId.size(); id++) { auto current = reverseId[id]; auto value = power(current.first, current.second); reachable[id][value] = true; } // add all primes with unique partitions fillSieve(limit); unsigned int sum = 0; for (unsigned int i = 1; i <= limit; i++) { // is there at least one combination to reach that number ? bool possible = false; // is there at most one combination to reach that number ? bool unique = true; // => look for numbers that are possible and unique for (unsigned int id = 1; id < reverseId.size(); id++) { auto expTwo = reverseId[id].first; auto expThree = reverseId[id].second; // can I reach this number if one term has the current ID ? if (!reachable[id][i]) continue; // store new sum if (possible || multiple[id][i]) // multiple ways to reach current position ? unique = false; possible = true; // try to add every possible coprime number with 2^c * 3^d (where c > a and b < d) for (unsigned int nextExpTwo = expTwo + 1; nextExpTwo < numPowerOfTwo; nextExpTwo++) for (unsigned int nextExpThree = 0; nextExpThree < expThree; nextExpThree++) { auto nextId = ids[nextExpTwo][nextExpThree]; if (nextId == TooLarge) break; // add one term auto next = i + power(nextExpTwo, nextExpThree); if (next > limit) break; // if the next number was already reachable then there are now multiple ways if (reachable[nextId][next]) multiple [nextId][next] = true; else reachable[nextId][next] = true; } } // unique sum of a prime ? if (possible && unique && isPrime(i)) sum += i; } // display result std::cout << sum << std::endl; return 0; }
35.306709
167
0.620939
sarvekash
339e4e31a2dc79426fb5156af52da3466e2741cb
345
cc
C++
cpptest/infinite_loop.cc
wshonline/test
2eed4c08798f7a68b139295f080a8df31c55fac4
[ "MIT" ]
null
null
null
cpptest/infinite_loop.cc
wshonline/test
2eed4c08798f7a68b139295f080a8df31c55fac4
[ "MIT" ]
null
null
null
cpptest/infinite_loop.cc
wshonline/test
2eed4c08798f7a68b139295f080a8df31c55fac4
[ "MIT" ]
null
null
null
// 死循环 // 传入形参m,拷贝了新的m,而it指向的是原m的地址 #include <map> #include <iostream> void test(std::map<int, int> mp, std::map<int, int>::iterator it) { while (it != mp.end()) { std::cout << it->first << std::endl; it++; } } int main() { std::map<int, int> mp; mp[0] = 1; mp[1] = 2; auto it = mp.begin(); test(mp, it); return 0; }
15
67
0.542029
wshonline
339ec6b7d56cc01612d4cd42f7f159af579b1045
5,485
cpp
C++
src/services/hardwareFileSystem/cpu/instructionsets.cpp
patrick-lafferty/saturn
6dc36adb42ad9b647704dd19247423a522eeb551
[ "BSD-3-Clause" ]
26
2018-03-19T15:59:46.000Z
2021-08-06T16:13:16.000Z
src/services/hardwareFileSystem/cpu/instructionsets.cpp
patrick-lafferty/saturn
6dc36adb42ad9b647704dd19247423a522eeb551
[ "BSD-3-Clause" ]
34
2018-01-21T17:43:29.000Z
2020-06-27T02:00:53.000Z
src/services/hardwareFileSystem/cpu/instructionsets.cpp
patrick-lafferty/saturn
6dc36adb42ad9b647704dd19247423a522eeb551
[ "BSD-3-Clause" ]
3
2019-12-08T22:26:35.000Z
2021-06-25T17:05:57.000Z
/* Copyright (c) 2017, Patrick Lafferty All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "instructionsets.h" #include <string.h> #include <system_calls.h> #include <services/virtualFileSystem/virtualFileSystem.h> #include <algorithm> using namespace VirtualFileSystem; using namespace Vostok; namespace HardwareFileSystem { CPUInstructionSetsObject::CPUInstructionSetsObject() { features = 0; } void CPUInstructionSetsObject::readSelf(uint32_t requesterTaskId, uint32_t requestId) { ReadResult result; result.success = true; result.requestId = requestId; ArgBuffer args {result.buffer, sizeof(result.buffer)}; args.writeType(ArgTypes::Property); args.writeValueWithType("sse3", ArgTypes::Cstring); args.writeValueWithType("ssse3", ArgTypes::Cstring); args.writeValueWithType("sse4_1", ArgTypes::Cstring); args.writeValueWithType("sse4_2", ArgTypes::Cstring); args.writeValueWithType("avx", ArgTypes::Cstring); args.writeType(ArgTypes::EndArg); result.recipientId = requesterTaskId; send(IPC::RecipientType::TaskId, &result); } /* Vostok Object property support */ int CPUInstructionSetsObject::getProperty(std::string_view name) { if (name.compare("sse3") == 0) { return static_cast<int>(PropertyId::SSE3); } else if (name.compare("ssse3") == 0) { return static_cast<int>(PropertyId::SSSE3); } else if (name.compare("sse4_1") == 0) { return static_cast<int>(PropertyId::SSE4_1); } else if (name.compare("sse4_2") == 0) { return static_cast<int>(PropertyId::SSE4_2); } else if (name.compare("avx") == 0) { return static_cast<int>(PropertyId::AVX); } return -1; } void CPUInstructionSetsObject::readProperty(uint32_t requesterTaskId, uint32_t requestId, uint32_t propertyId) { ReadResult result; result.success = true; result.requestId = requestId; ArgBuffer args {result.buffer, sizeof(result.buffer)}; args.writeType(ArgTypes::Property); args.writeValueWithType((features & (1 << propertyId)) > 0, ArgTypes::Uint32); args.writeType(ArgTypes::EndArg); result.recipientId = requesterTaskId; send(IPC::RecipientType::TaskId, &result); } void CPUInstructionSetsObject::writeProperty(uint32_t requesterTaskId, uint32_t requestId, uint32_t propertyId, ArgBuffer& args) { auto type = args.readType(); if (type != ArgTypes::Property) { replyWriteSucceeded(requesterTaskId, requestId, false); return; } auto x = args.read<uint32_t>(ArgTypes::Uint32); if (!args.hasErrors()) { if (x > 0) { features |= (1 << propertyId); } replyWriteSucceeded(requesterTaskId, requestId, true); return; } replyWriteSucceeded(requesterTaskId, requestId, false); } /* CPU Features Object specific implementation */ const char* CPUInstructionSetsObject::getName() { return "instruction_sets"; } void detectInstructionSets(uint32_t ecx) { auto sse3 = (ecx & (1u << 0)); auto ssse3 = (ecx & (1u << 9)); auto sse4_1 = (ecx & (1u << 19)); auto sse4_2 = (ecx & (1u << 20)); auto avx = (ecx & (1u << 28)); writeTransaction("/system/hardware/cpu/features/instruction_sets/sse3", sse3, ArgTypes::Uint32); writeTransaction("/system/hardware/cpu/features/instruction_sets/ssse3", ssse3, ArgTypes::Uint32); writeTransaction("/system/hardware/cpu/features/instruction_sets/sse4_1", sse4_1, ArgTypes::Uint32); writeTransaction("/system/hardware/cpu/features/instruction_sets/sse4_2", sse4_2, ArgTypes::Uint32); writeTransaction("/system/hardware/cpu/features/instruction_sets/avx", avx, ArgTypes::Uint32); } }
38.626761
134
0.67876
patrick-lafferty
339f63d47e6838822c8608a743aa11920c5ba72b
117,798
cc
C++
src/MissionManager/MissionController.cc
pestophagous/qgroundcontrol
9e261b56598a6c3e5cb4b71fbbe02640453e6d5b
[ "Apache-2.0" ]
null
null
null
src/MissionManager/MissionController.cc
pestophagous/qgroundcontrol
9e261b56598a6c3e5cb4b71fbbe02640453e6d5b
[ "Apache-2.0" ]
null
null
null
src/MissionManager/MissionController.cc
pestophagous/qgroundcontrol
9e261b56598a6c3e5cb4b71fbbe02640453e6d5b
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** * * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "MissionCommandUIInfo.h" #include "MissionController.h" #include "MultiVehicleManager.h" #include "MissionManager.h" #include "FlightPathSegment.h" #include "FirmwarePlugin.h" #include "QGCApplication.h" #include "SimpleMissionItem.h" #include "SurveyComplexItem.h" #include "FixedWingLandingComplexItem.h" #include "VTOLLandingComplexItem.h" #include "StructureScanComplexItem.h" #include "CorridorScanComplexItem.h" #include "JsonHelper.h" #include "ParameterManager.h" #include "QGroundControlQmlGlobal.h" #include "SettingsManager.h" #include "AppSettings.h" #include "MissionSettingsItem.h" #include "QGCQGeoCoordinate.h" #include "PlanMasterController.h" #include "KMLPlanDomDocument.h" #include "QGCCorePlugin.h" #include "TakeoffMissionItem.h" #include "PlanViewSettings.h" #define UPDATE_TIMEOUT 5000 ///< How often we check for bounding box changes QGC_LOGGING_CATEGORY(MissionControllerLog, "MissionControllerLog") const char* MissionController::_settingsGroup = "MissionController"; const char* MissionController::_jsonFileTypeValue = "Mission"; const char* MissionController::_jsonItemsKey = "items"; const char* MissionController::_jsonPlannedHomePositionKey = "plannedHomePosition"; const char* MissionController::_jsonFirmwareTypeKey = "firmwareType"; const char* MissionController::_jsonVehicleTypeKey = "vehicleType"; const char* MissionController::_jsonCruiseSpeedKey = "cruiseSpeed"; const char* MissionController::_jsonHoverSpeedKey = "hoverSpeed"; const char* MissionController::_jsonParamsKey = "params"; const char* MissionController::_jsonGlobalPlanAltitudeModeKey = "globalPlanAltitudeMode"; // Deprecated V1 format keys const char* MissionController::_jsonComplexItemsKey = "complexItems"; const char* MissionController::_jsonMavAutopilotKey = "MAV_AUTOPILOT"; const int MissionController::_missionFileVersion = 2; MissionController::MissionController(PlanMasterController* masterController, QObject *parent) : PlanElementController (masterController, parent) , _controllerVehicle (masterController->controllerVehicle()) , _managerVehicle (masterController->managerVehicle()) , _missionManager (masterController->managerVehicle()->missionManager()) , _visualItems (new QmlObjectListModel(this)) , _planViewSettings (qgcApp()->toolbox()->settingsManager()->planViewSettings()) , _appSettings (qgcApp()->toolbox()->settingsManager()->appSettings()) { _resetMissionFlightStatus(); _updateTimer.setSingleShot(true); connect(&_updateTimer, &QTimer::timeout, this, &MissionController::_updateTimeout); connect(_planViewSettings->takeoffItemNotRequired(), &Fact::rawValueChanged, this, &MissionController::_takeoffItemNotRequiredChanged); connect(this, &MissionController::missionDistanceChanged, this, &MissionController::recalcTerrainProfile); // The follow is used to compress multiple recalc calls in a row to into a single call. connect(this, &MissionController::_recalcMissionFlightStatusSignal, this, &MissionController::_recalcMissionFlightStatus, Qt::QueuedConnection); connect(this, &MissionController::_recalcFlightPathSegmentsSignal, this, &MissionController::_recalcFlightPathSegments, Qt::QueuedConnection); qgcApp()->addCompressedSignal(QMetaMethod::fromSignal(&MissionController::_recalcMissionFlightStatusSignal)); qgcApp()->addCompressedSignal(QMetaMethod::fromSignal(&MissionController::_recalcFlightPathSegmentsSignal)); qgcApp()->addCompressedSignal(QMetaMethod::fromSignal(&MissionController::recalcTerrainProfile)); } MissionController::~MissionController() { } void MissionController::_resetMissionFlightStatus(void) { _missionFlightStatus.totalDistance = 0.0; _missionFlightStatus.maxTelemetryDistance = 0.0; _missionFlightStatus.totalTime = 0.0; _missionFlightStatus.hoverTime = 0.0; _missionFlightStatus.cruiseTime = 0.0; _missionFlightStatus.hoverDistance = 0.0; _missionFlightStatus.cruiseDistance = 0.0; _missionFlightStatus.cruiseSpeed = _controllerVehicle->defaultCruiseSpeed(); _missionFlightStatus.hoverSpeed = _controllerVehicle->defaultHoverSpeed(); _missionFlightStatus.vehicleSpeed = _controllerVehicle->multiRotor() || _managerVehicle->vtol() ? _missionFlightStatus.hoverSpeed : _missionFlightStatus.cruiseSpeed; _missionFlightStatus.vehicleYaw = qQNaN(); _missionFlightStatus.gimbalYaw = qQNaN(); _missionFlightStatus.gimbalPitch = qQNaN(); _missionFlightStatus.mAhBattery = 0; _missionFlightStatus.hoverAmps = 0; _missionFlightStatus.cruiseAmps = 0; _missionFlightStatus.ampMinutesAvailable = 0; _missionFlightStatus.hoverAmpsTotal = 0; _missionFlightStatus.cruiseAmpsTotal = 0; _missionFlightStatus.batteryChangePoint = -1; _missionFlightStatus.batteriesRequired = -1; _missionFlightStatus.vtolMode = _missionContainsVTOLTakeoff ? QGCMAVLink::VehicleClassMultiRotor : QGCMAVLink::VehicleClassFixedWing; _controllerVehicle->firmwarePlugin()->batteryConsumptionData(_controllerVehicle, _missionFlightStatus.mAhBattery, _missionFlightStatus.hoverAmps, _missionFlightStatus.cruiseAmps); if (_missionFlightStatus.mAhBattery != 0) { double batteryPercentRemainingAnnounce = qgcApp()->toolbox()->settingsManager()->appSettings()->batteryPercentRemainingAnnounce()->rawValue().toDouble(); _missionFlightStatus.ampMinutesAvailable = static_cast<double>(_missionFlightStatus.mAhBattery) / 1000.0 * 60.0 * ((100.0 - batteryPercentRemainingAnnounce) / 100.0); } emit missionDistanceChanged(_missionFlightStatus.totalDistance); emit missionTimeChanged(); emit missionHoverDistanceChanged(_missionFlightStatus.hoverDistance); emit missionCruiseDistanceChanged(_missionFlightStatus.cruiseDistance); emit missionHoverTimeChanged(); emit missionCruiseTimeChanged(); emit missionMaxTelemetryChanged(_missionFlightStatus.maxTelemetryDistance); emit batteryChangePointChanged(_missionFlightStatus.batteryChangePoint); emit batteriesRequiredChanged(_missionFlightStatus.batteriesRequired); } void MissionController::start(bool flyView) { qCDebug(MissionControllerLog) << "start flyView" << flyView; _managerVehicleChanged(_managerVehicle); connect(_masterController, &PlanMasterController::managerVehicleChanged, this, &MissionController::_managerVehicleChanged); PlanElementController::start(flyView); _init(); } void MissionController::_init(void) { // We start with an empty mission _addMissionSettings(_visualItems); _initAllVisualItems(); } // Called when new mission items have completed downloading from Vehicle void MissionController::_newMissionItemsAvailableFromVehicle(bool removeAllRequested) { qCDebug(MissionControllerLog) << "_newMissionItemsAvailableFromVehicle flyView:count" << _flyView << _missionManager->missionItems().count(); // Fly view always reloads on _loadComplete // Plan view only reloads if: // - Load was specifically requested // - There is no current Plan if (_flyView || removeAllRequested || _itemsRequested || isEmpty()) { // Fly Mode (accept if): // - Always accepts new items from the vehicle so Fly view is kept up to date // Edit Mode (accept if): // - Remove all was requested from Fly view (clear mission on flight end) // - A load from vehicle was manually requested // - The initial automatic load from a vehicle completed and the current editor is empty _deinitAllVisualItems(); _visualItems->deleteLater(); _visualItems = nullptr; _settingsItem = nullptr; _takeoffMissionItem = nullptr; _updateContainsItems(); // This will clear containsItems which will be set again below. This will re-pop Start Mission confirmation. QmlObjectListModel* newControllerMissionItems = new QmlObjectListModel(this); const QList<MissionItem*>& newMissionItems = _missionManager->missionItems(); qCDebug(MissionControllerLog) << "loading from vehicle: count"<< newMissionItems.count(); _missionItemCount = newMissionItems.count(); emit missionItemCountChanged(_missionItemCount); MissionSettingsItem* settingsItem = _addMissionSettings(newControllerMissionItems); int i=0; if (_controllerVehicle->firmwarePlugin()->sendHomePositionToVehicle() && newMissionItems.count() != 0) { // First item is fake home position MissionItem* fakeHomeItem = newMissionItems[0]; if (fakeHomeItem->coordinate().latitude() != 0 || fakeHomeItem->coordinate().longitude() != 0) { settingsItem->setInitialHomePosition(fakeHomeItem->coordinate()); } i = 1; } for (; i < newMissionItems.count(); i++) { const MissionItem* missionItem = newMissionItems[i]; SimpleMissionItem* simpleItem = new SimpleMissionItem(_masterController, _flyView, *missionItem, this); if (TakeoffMissionItem::isTakeoffCommand(static_cast<MAV_CMD>(simpleItem->command()))) { // This needs to be a TakeoffMissionItem _takeoffMissionItem = new TakeoffMissionItem(*missionItem, _masterController, _flyView, settingsItem, this); simpleItem->deleteLater(); simpleItem = _takeoffMissionItem; } newControllerMissionItems->append(simpleItem); } _visualItems = newControllerMissionItems; _settingsItem = settingsItem; MissionController::_scanForAdditionalSettings(_visualItems, _masterController); _initAllVisualItems(); _updateContainsItems(); emit newItemsFromVehicle(); } _itemsRequested = false; } void MissionController::loadFromVehicle(void) { if (_masterController->offline()) { qCWarning(MissionControllerLog) << "MissionControllerLog::loadFromVehicle called while offline"; } else if (syncInProgress()) { qCWarning(MissionControllerLog) << "MissionControllerLog::loadFromVehicle called while syncInProgress"; } else { _itemsRequested = true; _managerVehicle->missionManager()->loadFromVehicle(); } } void MissionController::sendToVehicle(void) { if (_masterController->offline()) { qCWarning(MissionControllerLog) << "MissionControllerLog::sendToVehicle called while offline"; } else if (syncInProgress()) { qCWarning(MissionControllerLog) << "MissionControllerLog::sendToVehicle called while syncInProgress"; } else { qCDebug(MissionControllerLog) << "MissionControllerLog::sendToVehicle"; if (_visualItems->count() == 1) { // This prevents us from sending a possibly bogus home position to the vehicle QmlObjectListModel emptyModel; sendItemsToVehicle(_managerVehicle, &emptyModel); } else { sendItemsToVehicle(_managerVehicle, _visualItems); } setDirty(false); } } /// Converts from visual items to MissionItems /// @param missionItemParent QObject parent for newly allocated MissionItems /// @return true: Mission end action was added to end of list bool MissionController::_convertToMissionItems(QmlObjectListModel* visualMissionItems, QList<MissionItem*>& rgMissionItems, QObject* missionItemParent) { if (visualMissionItems->count() == 0) { return false; } bool endActionSet = false; int lastSeqNum = 0; for (int i=0; i<visualMissionItems->count(); i++) { VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(visualMissionItems->get(i)); lastSeqNum = visualItem->lastSequenceNumber(); visualItem->appendMissionItems(rgMissionItems, missionItemParent); qCDebug(MissionControllerLog) << "_convertToMissionItems seqNum:lastSeqNum:command" << visualItem->sequenceNumber() << lastSeqNum << visualItem->commandName(); } // Mission settings has a special case for end mission action MissionSettingsItem* settingsItem = visualMissionItems->value<MissionSettingsItem*>(0); if (settingsItem) { endActionSet = settingsItem->addMissionEndAction(rgMissionItems, lastSeqNum + 1, missionItemParent); } return endActionSet; } void MissionController::addMissionToKML(KMLPlanDomDocument& planKML) { QObject* deleteParent = new QObject(); QList<MissionItem*> rgMissionItems; _convertToMissionItems(_visualItems, rgMissionItems, deleteParent); planKML.addMission(_controllerVehicle, _visualItems, rgMissionItems); deleteParent->deleteLater(); } void MissionController::sendItemsToVehicle(Vehicle* vehicle, QmlObjectListModel* visualMissionItems) { if (vehicle) { QList<MissionItem*> rgMissionItems; _convertToMissionItems(visualMissionItems, rgMissionItems, vehicle); // PlanManager takes control of MissionItems so no need to delete vehicle->missionManager()->writeMissionItems(rgMissionItems); } } int MissionController::_nextSequenceNumber(void) { if (_visualItems->count() == 0) { qWarning() << "Internal error: Empty visual item list"; return 0; } else { VisualMissionItem* lastItem = _visualItems->value<VisualMissionItem*>(_visualItems->count() - 1); return lastItem->lastSequenceNumber() + 1; } } VisualMissionItem* MissionController::_insertSimpleMissionItemWorker(QGeoCoordinate coordinate, MAV_CMD command, int visualItemIndex, bool makeCurrentItem) { int sequenceNumber = _nextSequenceNumber(); SimpleMissionItem * newItem = new SimpleMissionItem(_masterController, _flyView, false /* forLoad */, this); newItem->setSequenceNumber(sequenceNumber); newItem->setCoordinate(coordinate); newItem->setCommand(command); _initVisualItem(newItem); if (newItem->specifiesAltitude()) { if (!qgcApp()->toolbox()->missionCommandTree()->isLandCommand(command)) { double prevAltitude; int prevAltitudeMode; if (_findPreviousAltitude(visualItemIndex, &prevAltitude, &prevAltitudeMode)) { newItem->altitude()->setRawValue(prevAltitude); if (globalAltitudeMode() == QGroundControlQmlGlobal::AltitudeModeNone) { // We are in mixed altitude modes, so copy from previous. Otherwise alt mode will be set from global setting. newItem->setAltitudeMode(static_cast<QGroundControlQmlGlobal::AltitudeMode>(prevAltitudeMode)); } } } } if (visualItemIndex == -1) { _visualItems->append(newItem); } else { _visualItems->insert(visualItemIndex, newItem); } // We send the click coordinate through here to be able to set the planned home position from the user click location if needed _recalcAllWithCoordinate(coordinate); if (makeCurrentItem) { setCurrentPlanViewSeqNum(newItem->sequenceNumber(), true); } _firstItemAdded(); return newItem; } VisualMissionItem* MissionController::insertSimpleMissionItem(QGeoCoordinate coordinate, int visualItemIndex, bool makeCurrentItem) { return _insertSimpleMissionItemWorker(coordinate, MAV_CMD_NAV_WAYPOINT, visualItemIndex, makeCurrentItem); } VisualMissionItem* MissionController::insertTakeoffItem(QGeoCoordinate /*coordinate*/, int visualItemIndex, bool makeCurrentItem) { int sequenceNumber = _nextSequenceNumber(); _takeoffMissionItem = new TakeoffMissionItem(_controllerVehicle->vtol() ? MAV_CMD_NAV_VTOL_TAKEOFF : MAV_CMD_NAV_TAKEOFF, _masterController, _flyView, _settingsItem, this); _takeoffMissionItem->setSequenceNumber(sequenceNumber); _initVisualItem(_takeoffMissionItem); if (_takeoffMissionItem->specifiesAltitude()) { double prevAltitude; int prevAltitudeMode; if (_findPreviousAltitude(visualItemIndex, &prevAltitude, &prevAltitudeMode)) { _takeoffMissionItem->altitude()->setRawValue(prevAltitude); _takeoffMissionItem->setAltitudeMode(static_cast<QGroundControlQmlGlobal::AltitudeMode>(prevAltitudeMode)); } } if (visualItemIndex == -1) { _visualItems->append(_takeoffMissionItem); } else { _visualItems->insert(visualItemIndex, _takeoffMissionItem); } _recalcAll(); if (makeCurrentItem) { setCurrentPlanViewSeqNum(_takeoffMissionItem->sequenceNumber(), true); } _firstItemAdded(); return _takeoffMissionItem; } VisualMissionItem* MissionController::insertLandItem(QGeoCoordinate coordinate, int visualItemIndex, bool makeCurrentItem) { if (_controllerVehicle->fixedWing()) { FixedWingLandingComplexItem* fwLanding = qobject_cast<FixedWingLandingComplexItem*>(insertComplexMissionItem(FixedWingLandingComplexItem::name, coordinate, visualItemIndex, makeCurrentItem)); return fwLanding; } else if (_controllerVehicle->vtol()) { VTOLLandingComplexItem* vtolLanding = qobject_cast<VTOLLandingComplexItem*>(insertComplexMissionItem(VTOLLandingComplexItem::name, coordinate, visualItemIndex, makeCurrentItem)); return vtolLanding; } else { return _insertSimpleMissionItemWorker(coordinate, _controllerVehicle->vtol() ? MAV_CMD_NAV_VTOL_LAND : MAV_CMD_NAV_RETURN_TO_LAUNCH, visualItemIndex, makeCurrentItem); } } VisualMissionItem* MissionController::insertROIMissionItem(QGeoCoordinate coordinate, int visualItemIndex, bool makeCurrentItem) { SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(_insertSimpleMissionItemWorker(coordinate, MAV_CMD_DO_SET_ROI_LOCATION, visualItemIndex, makeCurrentItem)); if (!_controllerVehicle->firmwarePlugin()->supportedMissionCommands(QGCMAVLink::VehicleClassGeneric).contains(MAV_CMD_DO_SET_ROI_LOCATION)) { simpleItem->setCommand(MAV_CMD_DO_SET_ROI) ; simpleItem->missionItem().setParam1(MAV_ROI_LOCATION); } _recalcROISpecialVisuals(); return simpleItem; } VisualMissionItem* MissionController::insertCancelROIMissionItem(int visualItemIndex, bool makeCurrentItem) { SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(_insertSimpleMissionItemWorker(QGeoCoordinate(), MAV_CMD_DO_SET_ROI_NONE, visualItemIndex, makeCurrentItem)); if (!_controllerVehicle->firmwarePlugin()->supportedMissionCommands(QGCMAVLink::VehicleClassGeneric).contains(MAV_CMD_DO_SET_ROI_NONE)) { simpleItem->setCommand(MAV_CMD_DO_SET_ROI) ; simpleItem->missionItem().setParam1(MAV_ROI_NONE); } _recalcROISpecialVisuals(); return simpleItem; } VisualMissionItem* MissionController::insertComplexMissionItem(QString itemName, QGeoCoordinate mapCenterCoordinate, int visualItemIndex, bool makeCurrentItem) { ComplexMissionItem* newItem = nullptr; if (itemName == SurveyComplexItem::name) { newItem = new SurveyComplexItem(_masterController, _flyView, QString() /* kmlFile */, _visualItems /* parent */); newItem->setCoordinate(mapCenterCoordinate); } else if (itemName == FixedWingLandingComplexItem::name) { newItem = new FixedWingLandingComplexItem(_masterController, _flyView, _visualItems /* parent */); } else if (itemName == VTOLLandingComplexItem::name) { newItem = new VTOLLandingComplexItem(_masterController, _flyView, _visualItems /* parent */); } else if (itemName == StructureScanComplexItem::name) { newItem = new StructureScanComplexItem(_masterController, _flyView, QString() /* kmlFile */, _visualItems /* parent */); } else if (itemName == CorridorScanComplexItem::name) { newItem = new CorridorScanComplexItem(_masterController, _flyView, QString() /* kmlFile */, _visualItems /* parent */); } else { qWarning() << "Internal error: Unknown complex item:" << itemName; return nullptr; } _insertComplexMissionItemWorker(mapCenterCoordinate, newItem, visualItemIndex, makeCurrentItem); return newItem; } VisualMissionItem* MissionController::insertComplexMissionItemFromKMLOrSHP(QString itemName, QString file, int visualItemIndex, bool makeCurrentItem) { ComplexMissionItem* newItem = nullptr; if (itemName == SurveyComplexItem::name) { newItem = new SurveyComplexItem(_masterController, _flyView, file, _visualItems); } else if (itemName == StructureScanComplexItem::name) { newItem = new StructureScanComplexItem(_masterController, _flyView, file, _visualItems); } else if (itemName == CorridorScanComplexItem::name) { newItem = new CorridorScanComplexItem(_masterController, _flyView, file, _visualItems); } else { qWarning() << "Internal error: Unknown complex item:" << itemName; return nullptr; } _insertComplexMissionItemWorker(QGeoCoordinate(), newItem, visualItemIndex, makeCurrentItem); return newItem; } void MissionController::_insertComplexMissionItemWorker(const QGeoCoordinate& mapCenterCoordinate, ComplexMissionItem* complexItem, int visualItemIndex, bool makeCurrentItem) { int sequenceNumber = _nextSequenceNumber(); bool surveyStyleItem = qobject_cast<SurveyComplexItem*>(complexItem) || qobject_cast<CorridorScanComplexItem*>(complexItem) || qobject_cast<StructureScanComplexItem*>(complexItem); if (surveyStyleItem) { bool rollSupported = false; bool pitchSupported = false; bool yawSupported = false; // If the vehicle is known to have a gimbal then we automatically point the gimbal straight down if not already set MissionSettingsItem* settingsItem = _visualItems->value<MissionSettingsItem*>(0); CameraSection* cameraSection = settingsItem->cameraSection(); // Set camera to photo mode (leave alone if user already specified) if (cameraSection->cameraModeSupported() && !cameraSection->specifyCameraMode()) { cameraSection->setSpecifyCameraMode(true); cameraSection->cameraMode()->setRawValue(CAMERA_MODE_IMAGE_SURVEY); } // Point gimbal straight down if (_controllerVehicle->firmwarePlugin()->hasGimbal(_controllerVehicle, rollSupported, pitchSupported, yawSupported) && pitchSupported) { // If the user already specified a gimbal angle leave it alone if (!cameraSection->specifyGimbal()) { cameraSection->setSpecifyGimbal(true); cameraSection->gimbalPitch()->setRawValue(-90.0); } } } complexItem->setSequenceNumber(sequenceNumber); complexItem->setWizardMode(true); _initVisualItem(complexItem); if (visualItemIndex == -1) { _visualItems->append(complexItem); } else { _visualItems->insert(visualItemIndex, complexItem); } //-- Keep track of bounding box changes in complex items if(!complexItem->isSimpleItem()) { connect(complexItem, &ComplexMissionItem::boundingCubeChanged, this, &MissionController::_complexBoundingBoxChanged); } _recalcAllWithCoordinate(mapCenterCoordinate); if (makeCurrentItem) { setCurrentPlanViewSeqNum(complexItem->sequenceNumber(), true); } _firstItemAdded(); } void MissionController::removeVisualItem(int viIndex) { if (viIndex <= 0 || viIndex >= _visualItems->count()) { qWarning() << "MissionController::removeVisualItem called with bad index - count:index" << _visualItems->count() << viIndex; return; } bool removeSurveyStyle = _visualItems->value<SurveyComplexItem*>(viIndex) || _visualItems->value<CorridorScanComplexItem*>(viIndex); VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->removeAt(viIndex)); if (item == _takeoffMissionItem) { _takeoffMissionItem = nullptr; } _deinitVisualItem(item); item->deleteLater(); if (removeSurveyStyle) { // Determine if the mission still has another survey style item in it bool foundSurvey = false; for (int i=1; i<_visualItems->count(); i++) { if (_visualItems->value<SurveyComplexItem*>(i) || _visualItems->value<CorridorScanComplexItem*>(i)) { foundSurvey = true; break; } } // If there is no longer a survey item in the mission remove added commands if (!foundSurvey) { bool rollSupported = false; bool pitchSupported = false; bool yawSupported = false; CameraSection* cameraSection = _settingsItem->cameraSection(); if (_controllerVehicle->firmwarePlugin()->hasGimbal(_controllerVehicle, rollSupported, pitchSupported, yawSupported) && pitchSupported) { if (cameraSection->specifyGimbal() && cameraSection->gimbalPitch()->rawValue().toDouble() == -90.0 && cameraSection->gimbalYaw()->rawValue().toDouble() == 0.0) { cameraSection->setSpecifyGimbal(false); } } if (cameraSection->cameraModeSupported() && cameraSection->specifyCameraMode() && cameraSection->cameraMode()->rawValue().toInt() == 0) { cameraSection->setSpecifyCameraMode(false); } } } _recalcAll(); // Adjust current item int newVIIndex; if (viIndex >= _visualItems->count()) { newVIIndex = _visualItems->count() - 1; } else { newVIIndex = viIndex; } setCurrentPlanViewSeqNum(_visualItems->value<VisualMissionItem*>(newVIIndex)->sequenceNumber(), true); setDirty(true); if (_visualItems->count() == 1) { _allItemsRemoved(); } } void MissionController::removeAll(void) { if (_visualItems) { _deinitAllVisualItems(); _visualItems->clearAndDeleteContents(); _visualItems->deleteLater(); _settingsItem = nullptr; _takeoffMissionItem = nullptr; _visualItems = new QmlObjectListModel(this); _addMissionSettings(_visualItems); _initAllVisualItems(); setDirty(true); _resetMissionFlightStatus(); _allItemsRemoved(); } } bool MissionController::_loadJsonMissionFileV1(const QJsonObject& json, QmlObjectListModel* visualItems, QString& errorString) { // Validate root object keys QList<JsonHelper::KeyValidateInfo> rootKeyInfoList = { { _jsonPlannedHomePositionKey, QJsonValue::Object, true }, { _jsonItemsKey, QJsonValue::Array, true }, { _jsonMavAutopilotKey, QJsonValue::Double, true }, { _jsonComplexItemsKey, QJsonValue::Array, true }, }; if (!JsonHelper::validateKeys(json, rootKeyInfoList, errorString)) { return false; } setGlobalAltitudeMode(QGroundControlQmlGlobal::AltitudeModeNone); // Mixed mode // Read complex items QList<SurveyComplexItem*> surveyItems; QJsonArray complexArray(json[_jsonComplexItemsKey].toArray()); qCDebug(MissionControllerLog) << "Json load: complex item count" << complexArray.count(); for (int i=0; i<complexArray.count(); i++) { const QJsonValue& itemValue = complexArray[i]; if (!itemValue.isObject()) { errorString = QStringLiteral("Mission item is not an object"); return false; } SurveyComplexItem* item = new SurveyComplexItem(_masterController, _flyView, QString() /* kmlFile */, visualItems /* parent */); const QJsonObject itemObject = itemValue.toObject(); if (item->load(itemObject, itemObject["id"].toInt(), errorString)) { surveyItems.append(item); } else { return false; } } // Read simple items, interspersing complex items into the full list int nextSimpleItemIndex= 0; int nextComplexItemIndex= 0; int nextSequenceNumber = 1; // Start with 1 since home is in 0 QJsonArray itemArray(json[_jsonItemsKey].toArray()); MissionSettingsItem* settingsItem = _addMissionSettings(visualItems); if (json.contains(_jsonPlannedHomePositionKey)) { SimpleMissionItem* item = new SimpleMissionItem(_masterController, _flyView, true /* forLoad */, visualItems); if (item->load(json[_jsonPlannedHomePositionKey].toObject(), 0, errorString)) { settingsItem->setInitialHomePositionFromUser(item->coordinate()); item->deleteLater(); } else { return false; } } qCDebug(MissionControllerLog) << "Json load: simple item loop start simpleItemCount:ComplexItemCount" << itemArray.count() << surveyItems.count(); do { qCDebug(MissionControllerLog) << "Json load: simple item loop nextSimpleItemIndex:nextComplexItemIndex:nextSequenceNumber" << nextSimpleItemIndex << nextComplexItemIndex << nextSequenceNumber; // If there is a complex item that should be next in sequence add it in if (nextComplexItemIndex < surveyItems.count()) { SurveyComplexItem* complexItem = surveyItems[nextComplexItemIndex]; if (complexItem->sequenceNumber() == nextSequenceNumber) { qCDebug(MissionControllerLog) << "Json load: injecting complex item expectedSequence:actualSequence:" << nextSequenceNumber << complexItem->sequenceNumber(); visualItems->append(complexItem); nextSequenceNumber = complexItem->lastSequenceNumber() + 1; nextComplexItemIndex++; continue; } } // Add the next available simple item if (nextSimpleItemIndex < itemArray.count()) { const QJsonValue& itemValue = itemArray[nextSimpleItemIndex++]; if (!itemValue.isObject()) { errorString = QStringLiteral("Mission item is not an object"); return false; } const QJsonObject itemObject = itemValue.toObject(); SimpleMissionItem* item = new SimpleMissionItem(_masterController, _flyView, true /* forLoad */, visualItems); if (item->load(itemObject, itemObject["id"].toInt(), errorString)) { if (TakeoffMissionItem::isTakeoffCommand(item->mavCommand())) { // This needs to be a TakeoffMissionItem TakeoffMissionItem* takeoffItem = new TakeoffMissionItem(_masterController, _flyView, settingsItem, true /* forLoad */, visualItems); takeoffItem->load(itemObject, itemObject["id"].toInt(), errorString); item->deleteLater(); item = takeoffItem; } qCDebug(MissionControllerLog) << "Json load: adding simple item expectedSequence:actualSequence" << nextSequenceNumber << item->sequenceNumber(); nextSequenceNumber = item->lastSequenceNumber() + 1; visualItems->append(item); } else { return false; } } } while (nextSimpleItemIndex < itemArray.count() || nextComplexItemIndex < surveyItems.count()); return true; } bool MissionController::_loadJsonMissionFileV2(const QJsonObject& json, QmlObjectListModel* visualItems, QString& errorString) { // Validate root object keys QList<JsonHelper::KeyValidateInfo> rootKeyInfoList = { { _jsonPlannedHomePositionKey, QJsonValue::Array, true }, { _jsonItemsKey, QJsonValue::Array, true }, { _jsonFirmwareTypeKey, QJsonValue::Double, true }, { _jsonVehicleTypeKey, QJsonValue::Double, false }, { _jsonCruiseSpeedKey, QJsonValue::Double, false }, { _jsonHoverSpeedKey, QJsonValue::Double, false }, { _jsonGlobalPlanAltitudeModeKey, QJsonValue::Double, false }, }; if (!JsonHelper::validateKeys(json, rootKeyInfoList, errorString)) { return false; } setGlobalAltitudeMode(QGroundControlQmlGlobal::AltitudeModeNone); // Mixed mode qCDebug(MissionControllerLog) << "MissionController::_loadJsonMissionFileV2 itemCount:" << json[_jsonItemsKey].toArray().count(); AppSettings* appSettings = qgcApp()->toolbox()->settingsManager()->appSettings(); // Get the firmware/vehicle type from the plan file MAV_AUTOPILOT planFileFirmwareType = static_cast<MAV_AUTOPILOT>(json[_jsonFirmwareTypeKey].toInt()); MAV_TYPE planFileVehicleType = static_cast<MAV_TYPE> (QGCMAVLink::vehicleClassToMavType(appSettings->offlineEditingVehicleClass()->rawValue().toInt())); if (json.contains(_jsonVehicleTypeKey)) { planFileVehicleType = static_cast<MAV_TYPE>(json[_jsonVehicleTypeKey].toInt()); } // Update firmware/vehicle offline settings if we aren't connect to a vehicle if (_masterController->offline()) { appSettings->offlineEditingFirmwareClass()->setRawValue(QGCMAVLink::firmwareClass(static_cast<MAV_AUTOPILOT>(json[_jsonFirmwareTypeKey].toInt()))); if (json.contains(_jsonVehicleTypeKey)) { appSettings->offlineEditingVehicleClass()->setRawValue(QGCMAVLink::vehicleClass(planFileVehicleType)); } } // The controller vehicle always tracks the Plan file firmware/vehicle types so update it _controllerVehicle->stopTrackingFirmwareVehicleTypeChanges(); _controllerVehicle->_offlineFirmwareTypeSettingChanged(planFileFirmwareType); _controllerVehicle->_offlineVehicleTypeSettingChanged(planFileVehicleType); if (json.contains(_jsonCruiseSpeedKey)) { appSettings->offlineEditingCruiseSpeed()->setRawValue(json[_jsonCruiseSpeedKey].toDouble()); } if (json.contains(_jsonHoverSpeedKey)) { appSettings->offlineEditingHoverSpeed()->setRawValue(json[_jsonHoverSpeedKey].toDouble()); } if (json.contains(_jsonGlobalPlanAltitudeModeKey)) { setGlobalAltitudeMode(json[_jsonGlobalPlanAltitudeModeKey].toVariant().value<QGroundControlQmlGlobal::AltitudeMode>()); } QGeoCoordinate homeCoordinate; if (!JsonHelper::loadGeoCoordinate(json[_jsonPlannedHomePositionKey], true /* altitudeRequired */, homeCoordinate, errorString)) { return false; } MissionSettingsItem* settingsItem = new MissionSettingsItem(_masterController, _flyView, visualItems); settingsItem->setCoordinate(homeCoordinate); visualItems->insert(0, settingsItem); qCDebug(MissionControllerLog) << "plannedHomePosition" << homeCoordinate; // Read mission items int nextSequenceNumber = 1; // Start with 1 since home is in 0 const QJsonArray rgMissionItems(json[_jsonItemsKey].toArray()); for (int i=0; i<rgMissionItems.count(); i++) { // Convert to QJsonObject const QJsonValue& itemValue = rgMissionItems[i]; if (!itemValue.isObject()) { errorString = tr("Mission item %1 is not an object").arg(i); return false; } const QJsonObject itemObject = itemValue.toObject(); // Load item based on type QList<JsonHelper::KeyValidateInfo> itemKeyInfoList = { { VisualMissionItem::jsonTypeKey, QJsonValue::String, true }, }; if (!JsonHelper::validateKeys(itemObject, itemKeyInfoList, errorString)) { return false; } QString itemType = itemObject[VisualMissionItem::jsonTypeKey].toString(); if (itemType == VisualMissionItem::jsonTypeSimpleItemValue) { SimpleMissionItem* simpleItem = new SimpleMissionItem(_masterController, _flyView, true /* forLoad */, visualItems); if (simpleItem->load(itemObject, nextSequenceNumber, errorString)) { if (TakeoffMissionItem::isTakeoffCommand(static_cast<MAV_CMD>(simpleItem->command()))) { // This needs to be a TakeoffMissionItem TakeoffMissionItem* takeoffItem = new TakeoffMissionItem(_masterController, _flyView, settingsItem, true /* forLoad */, this); takeoffItem->load(itemObject, nextSequenceNumber, errorString); simpleItem->deleteLater(); simpleItem = takeoffItem; } qCDebug(MissionControllerLog) << "Loading simple item: nextSequenceNumber:command" << nextSequenceNumber << simpleItem->command(); nextSequenceNumber = simpleItem->lastSequenceNumber() + 1; visualItems->append(simpleItem); } else { return false; } } else if (itemType == VisualMissionItem::jsonTypeComplexItemValue) { QList<JsonHelper::KeyValidateInfo> complexItemKeyInfoList = { { ComplexMissionItem::jsonComplexItemTypeKey, QJsonValue::String, true }, }; if (!JsonHelper::validateKeys(itemObject, complexItemKeyInfoList, errorString)) { return false; } QString complexItemType = itemObject[ComplexMissionItem::jsonComplexItemTypeKey].toString(); if (complexItemType == SurveyComplexItem::jsonComplexItemTypeValue) { qCDebug(MissionControllerLog) << "Loading Survey: nextSequenceNumber" << nextSequenceNumber; SurveyComplexItem* surveyItem = new SurveyComplexItem(_masterController, _flyView, QString() /* kmlFile */, visualItems); if (!surveyItem->load(itemObject, nextSequenceNumber++, errorString)) { return false; } nextSequenceNumber = surveyItem->lastSequenceNumber() + 1; qCDebug(MissionControllerLog) << "Survey load complete: nextSequenceNumber" << nextSequenceNumber; visualItems->append(surveyItem); } else if (complexItemType == FixedWingLandingComplexItem::jsonComplexItemTypeValue) { qCDebug(MissionControllerLog) << "Loading Fixed Wing Landing Pattern: nextSequenceNumber" << nextSequenceNumber; FixedWingLandingComplexItem* landingItem = new FixedWingLandingComplexItem(_masterController, _flyView, visualItems); if (!landingItem->load(itemObject, nextSequenceNumber++, errorString)) { return false; } nextSequenceNumber = landingItem->lastSequenceNumber() + 1; qCDebug(MissionControllerLog) << "FW Landing Pattern load complete: nextSequenceNumber" << nextSequenceNumber; visualItems->append(landingItem); } else if (complexItemType == VTOLLandingComplexItem::jsonComplexItemTypeValue) { qCDebug(MissionControllerLog) << "Loading VTOL Landing Pattern: nextSequenceNumber" << nextSequenceNumber; VTOLLandingComplexItem* landingItem = new VTOLLandingComplexItem(_masterController, _flyView, visualItems); if (!landingItem->load(itemObject, nextSequenceNumber++, errorString)) { return false; } nextSequenceNumber = landingItem->lastSequenceNumber() + 1; qCDebug(MissionControllerLog) << "VTOL Landing Pattern load complete: nextSequenceNumber" << nextSequenceNumber; visualItems->append(landingItem); } else if (complexItemType == StructureScanComplexItem::jsonComplexItemTypeValue) { qCDebug(MissionControllerLog) << "Loading Structure Scan: nextSequenceNumber" << nextSequenceNumber; StructureScanComplexItem* structureItem = new StructureScanComplexItem(_masterController, _flyView, QString() /* kmlFile */, visualItems); if (!structureItem->load(itemObject, nextSequenceNumber++, errorString)) { return false; } nextSequenceNumber = structureItem->lastSequenceNumber() + 1; qCDebug(MissionControllerLog) << "Structure Scan load complete: nextSequenceNumber" << nextSequenceNumber; visualItems->append(structureItem); } else if (complexItemType == CorridorScanComplexItem::jsonComplexItemTypeValue) { qCDebug(MissionControllerLog) << "Loading Corridor Scan: nextSequenceNumber" << nextSequenceNumber; CorridorScanComplexItem* corridorItem = new CorridorScanComplexItem(_masterController, _flyView, QString() /* kmlFile */, visualItems); if (!corridorItem->load(itemObject, nextSequenceNumber++, errorString)) { return false; } nextSequenceNumber = corridorItem->lastSequenceNumber() + 1; qCDebug(MissionControllerLog) << "Corridor Scan load complete: nextSequenceNumber" << nextSequenceNumber; visualItems->append(corridorItem); } else { errorString = tr("Unsupported complex item type: %1").arg(complexItemType); } } else { errorString = tr("Unknown item type: %1").arg(itemType); return false; } } // Fix up the DO_JUMP commands jump sequence number by finding the item with the matching doJumpId for (int i=0; i<visualItems->count(); i++) { if (visualItems->value<VisualMissionItem*>(i)->isSimpleItem()) { SimpleMissionItem* doJumpItem = visualItems->value<SimpleMissionItem*>(i); if (doJumpItem->command() == MAV_CMD_DO_JUMP) { bool found = false; int findDoJumpId = static_cast<int>(doJumpItem->missionItem().param1()); for (int j=0; j<visualItems->count(); j++) { if (visualItems->value<VisualMissionItem*>(j)->isSimpleItem()) { SimpleMissionItem* targetItem = visualItems->value<SimpleMissionItem*>(j); if (targetItem->missionItem().doJumpId() == findDoJumpId) { doJumpItem->missionItem().setParam1(targetItem->sequenceNumber()); found = true; break; } } } if (!found) { errorString = tr("Could not find doJumpId: %1").arg(findDoJumpId); return false; } } } } return true; } bool MissionController::_loadItemsFromJson(const QJsonObject& json, QmlObjectListModel* visualItems, QString& errorString) { // V1 file format has no file type key and version key is string. Convert to new format. if (!json.contains(JsonHelper::jsonFileTypeKey)) { json[JsonHelper::jsonFileTypeKey] = _jsonFileTypeValue; } int fileVersion; JsonHelper::validateExternalQGCJsonFile(json, _jsonFileTypeValue, // expected file type 1, // minimum supported version 2, // maximum supported version fileVersion, errorString); if (fileVersion == 1) { return _loadJsonMissionFileV1(json, visualItems, errorString); } else { return _loadJsonMissionFileV2(json, visualItems, errorString); } } bool MissionController::_loadTextMissionFile(QTextStream& stream, QmlObjectListModel* visualItems, QString& errorString) { bool firstItem = true; bool plannedHomePositionInFile = false; QString firstLine = stream.readLine(); const QStringList& version = firstLine.split(" "); bool versionOk = false; if (version.size() == 3 && version[0] == "QGC" && version[1] == "WPL") { if (version[2] == "110") { // ArduPilot file, planned home position is already in position 0 versionOk = true; plannedHomePositionInFile = true; } else if (version[2] == "120") { // Old QGC file, no planned home position versionOk = true; plannedHomePositionInFile = false; } } if (versionOk) { MissionSettingsItem* settingsItem = _addMissionSettings(visualItems); while (!stream.atEnd()) { SimpleMissionItem* item = new SimpleMissionItem(_masterController, _flyView, true /* forLoad */, visualItems); if (item->load(stream)) { if (firstItem && plannedHomePositionInFile) { settingsItem->setInitialHomePositionFromUser(item->coordinate()); } else { if (TakeoffMissionItem::isTakeoffCommand(static_cast<MAV_CMD>(item->command()))) { // This needs to be a TakeoffMissionItem TakeoffMissionItem* takeoffItem = new TakeoffMissionItem(_masterController, _flyView, settingsItem, true /* forLoad */, visualItems); takeoffItem->load(stream); item->deleteLater(); item = takeoffItem; } visualItems->append(item); } firstItem = false; } else { errorString = tr("The mission file is corrupted."); return false; } } } else { errorString = tr("The mission file is not compatible with this version of %1.").arg(qgcApp()->applicationName()); return false; } if (!plannedHomePositionInFile) { // Update sequence numbers in DO_JUMP commands to take into account added home position in index 0 for (int i=1; i<visualItems->count(); i++) { SimpleMissionItem* item = qobject_cast<SimpleMissionItem*>(visualItems->get(i)); if (item && item->command() == MAV_CMD_DO_JUMP) { item->missionItem().setParam1(static_cast<int>(item->missionItem().param1()) + 1); } } } return true; } void MissionController::_initLoadedVisualItems(QmlObjectListModel* loadedVisualItems) { if (_visualItems) { _deinitAllVisualItems(); _visualItems->deleteLater(); } _settingsItem = nullptr; _takeoffMissionItem = nullptr; _visualItems = loadedVisualItems; if (_visualItems->count() == 0) { _addMissionSettings(_visualItems); } else { _settingsItem = _visualItems->value<MissionSettingsItem*>(0); } MissionController::_scanForAdditionalSettings(_visualItems, _masterController); _initAllVisualItems(); if (_visualItems->count() > 1) { _firstItemAdded(); } else { _allItemsRemoved(); } } bool MissionController::load(const QJsonObject& json, QString& errorString) { QString errorStr; QString errorMessage = tr("Mission: %1"); QmlObjectListModel* loadedVisualItems = new QmlObjectListModel(this); if (!_loadJsonMissionFileV2(json, loadedVisualItems, errorStr)) { errorString = errorMessage.arg(errorStr); return false; } _initLoadedVisualItems(loadedVisualItems); return true; } bool MissionController::loadJsonFile(QFile& file, QString& errorString) { QString errorStr; QString errorMessage = tr("Mission: %1"); QJsonDocument jsonDoc; QByteArray bytes = file.readAll(); if (!JsonHelper::isJsonFile(bytes, jsonDoc, errorStr)) { errorString = errorMessage.arg(errorStr); return false; } QJsonObject json = jsonDoc.object(); QmlObjectListModel* loadedVisualItems = new QmlObjectListModel(this); if (!_loadItemsFromJson(json, loadedVisualItems, errorStr)) { errorString = errorMessage.arg(errorStr); return false; } _initLoadedVisualItems(loadedVisualItems); return true; } bool MissionController::loadTextFile(QFile& file, QString& errorString) { QString errorStr; QString errorMessage = tr("Mission: %1"); QByteArray bytes = file.readAll(); QTextStream stream(bytes); setGlobalAltitudeMode(QGroundControlQmlGlobal::AltitudeModeNone); // Mixed mode QmlObjectListModel* loadedVisualItems = new QmlObjectListModel(this); if (!_loadTextMissionFile(stream, loadedVisualItems, errorStr)) { errorString = errorMessage.arg(errorStr); return false; } _initLoadedVisualItems(loadedVisualItems); return true; } int MissionController::readyForSaveState(void) const { for (int i=0; i<_visualItems->count(); i++) { VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i)); if (visualItem->readyForSaveState() != VisualMissionItem::ReadyForSave) { return visualItem->readyForSaveState(); } } return VisualMissionItem::ReadyForSave; } void MissionController::save(QJsonObject& json) { json[JsonHelper::jsonVersionKey] = _missionFileVersion; // Mission settings MissionSettingsItem* settingsItem = _visualItems->value<MissionSettingsItem*>(0); if (!settingsItem) { qWarning() << "First item is not MissionSettingsItem"; return; } QJsonValue coordinateValue; JsonHelper::saveGeoCoordinate(settingsItem->coordinate(), true /* writeAltitude */, coordinateValue); json[_jsonPlannedHomePositionKey] = coordinateValue; json[_jsonFirmwareTypeKey] = _controllerVehicle->firmwareType(); json[_jsonVehicleTypeKey] = _controllerVehicle->vehicleType(); json[_jsonCruiseSpeedKey] = _controllerVehicle->defaultCruiseSpeed(); json[_jsonHoverSpeedKey] = _controllerVehicle->defaultHoverSpeed(); json[_jsonGlobalPlanAltitudeModeKey] = _globalAltMode; // Save the visual items QJsonArray rgJsonMissionItems; for (int i=0; i<_visualItems->count(); i++) { VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i)); visualItem->save(rgJsonMissionItems); } // Mission settings has a special case for end mission action if (settingsItem) { QList<MissionItem*> rgMissionItems; if (_convertToMissionItems(_visualItems, rgMissionItems, this /* missionItemParent */)) { QJsonObject saveObject; MissionItem* missionItem = rgMissionItems[rgMissionItems.count() - 1]; missionItem->save(saveObject); rgJsonMissionItems.append(saveObject); } for (int i=0; i<rgMissionItems.count(); i++) { rgMissionItems[i]->deleteLater(); } } json[_jsonItemsKey] = rgJsonMissionItems; } void MissionController::_calcPrevWaypointValues(VisualMissionItem* currentItem, VisualMissionItem* prevItem, double* azimuth, double* distance, double* altDifference) { QGeoCoordinate currentCoord = currentItem->coordinate(); QGeoCoordinate prevCoord = prevItem->exitCoordinate(); // Convert to fixed altitudes *altDifference = currentItem->amslEntryAlt() - prevItem->amslExitAlt(); *distance = prevCoord.distanceTo(currentCoord); *azimuth = prevCoord.azimuthTo(currentCoord); } double MissionController::_calcDistanceToHome(VisualMissionItem* currentItem, VisualMissionItem* homeItem) { QGeoCoordinate currentCoord = currentItem->coordinate(); QGeoCoordinate homeCoord = homeItem->exitCoordinate(); bool distanceOk = false; distanceOk = true; return distanceOk ? homeCoord.distanceTo(currentCoord) : 0.0; } FlightPathSegment* MissionController::_createFlightPathSegmentWorker(VisualItemPair& pair) { QGeoCoordinate coord1 = pair.first->isSimpleItem() ? pair.first->coordinate() : pair.first->exitCoordinate(); QGeoCoordinate coord2 = pair.second->coordinate(); double coord1Alt = pair.first->isSimpleItem() ? pair.first->amslEntryAlt() : pair.first->amslExitAlt(); double coord2Alt = pair.second->amslEntryAlt(); FlightPathSegment* segment = new FlightPathSegment(coord1, coord1Alt, coord2, coord2Alt, !_flyView /* queryTerrainData */, this); auto coord1Notifier = pair.first->isSimpleItem() ? &VisualMissionItem::coordinateChanged : &VisualMissionItem::exitCoordinateChanged; auto coord2Notifier = &VisualMissionItem::coordinateChanged; auto coord1AltNotifier = pair.first->isSimpleItem() ? &VisualMissionItem::amslEntryAltChanged : &VisualMissionItem::amslExitAltChanged; auto coord2AltNotifier = &VisualMissionItem::amslEntryAltChanged; connect(pair.first, coord1Notifier, segment, &FlightPathSegment::setCoordinate1); connect(pair.second, coord2Notifier, segment, &FlightPathSegment::setCoordinate2); connect(pair.first, coord1AltNotifier, segment, &FlightPathSegment::setCoord1AMSLAlt); connect(pair.second, coord2AltNotifier, segment, &FlightPathSegment::setCoord2AMSLAlt); connect(pair.second, &VisualMissionItem::coordinateChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(segment, &FlightPathSegment::totalDistanceChanged, this, &MissionController::recalcTerrainProfile, Qt::QueuedConnection); connect(segment, &FlightPathSegment::coord1AMSLAltChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(segment, &FlightPathSegment::coord2AMSLAltChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(segment, &FlightPathSegment::amslTerrainHeightsChanged, this, &MissionController::recalcTerrainProfile, Qt::QueuedConnection); connect(segment, &FlightPathSegment::terrainCollisionChanged, this, &MissionController::recalcTerrainProfile, Qt::QueuedConnection); return segment; } FlightPathSegment* MissionController::_addFlightPathSegment(FlightPathSegmentHashTable& prevItemPairHashTable, VisualItemPair& pair) { FlightPathSegment* segment = nullptr; if (prevItemPairHashTable.contains(pair)) { // Pair already exists and connected, just re-use _flightPathSegmentHashTable[pair] = segment = prevItemPairHashTable.take(pair); } else { segment = _createFlightPathSegmentWorker(pair); _flightPathSegmentHashTable[pair] = segment; } _simpleFlightPathSegments.append(segment); return segment; } void MissionController::_recalcROISpecialVisuals(void) { return; VisualMissionItem* lastCoordinateItem = qobject_cast<VisualMissionItem*>(_visualItems->get(0)); bool roiActive = false; for (int i=1; i<_visualItems->count(); i++) { VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i)); SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(visualItem); VisualItemPair viPair; if (simpleItem) { if (roiActive) { if (_isROICancelItem(simpleItem)) { roiActive = false; } } else { if (_isROIBeginItem(simpleItem)) { roiActive = true; } } } if (visualItem->specifiesCoordinate() && !visualItem->isStandaloneCoordinate()) { viPair = VisualItemPair(lastCoordinateItem, visualItem); if (_flightPathSegmentHashTable.contains(viPair)) { _flightPathSegmentHashTable[viPair]->setSpecialVisual(roiActive); } lastCoordinateItem = visualItem; } } } void MissionController::_recalcFlightPathSegments(void) { VisualItemPair lastSegmentVisualItemPair; int segmentCount = 0; bool firstCoordinateNotFound = true; VisualMissionItem* lastFlyThroughVI = qobject_cast<VisualMissionItem*>(_visualItems->get(0)); bool linkEndToHome = false; bool linkStartToHome = _controllerVehicle->rover() ? true : false; bool foundRTL = false; bool homePositionValid = _settingsItem->coordinate().isValid(); bool roiActive = false; bool previousItemIsIncomplete = false; qCDebug(MissionControllerLog) << "_recalcFlightPathSegments homePositionValid" << homePositionValid; FlightPathSegmentHashTable oldSegmentTable = _flightPathSegmentHashTable; _missionContainsVTOLTakeoff = false; _flightPathSegmentHashTable.clear(); _waypointPath.clear(); // Note: Although visual support for _incompleteComplexItemLines is still in the codebase. The support for populating the list is not. // This is due to the initial implementation being buggy and incomplete with respect to correctly generating the line set. // So for now we leave the code for displaying them in, but none are ever added until we have time to implement the correct support. _simpleFlightPathSegments.beginReset(); _directionArrows.beginReset(); _incompleteComplexItemLines.beginReset(); _simpleFlightPathSegments.clear(); _directionArrows.clear(); _incompleteComplexItemLines.clearAndDeleteContents(); // Mission Settings item needs to start with no segment lastFlyThroughVI->setSimpleFlighPathSegment(nullptr); // Grovel through the list of items keeping track of things needed to correctly draw waypoints lines for (int i=1; i<_visualItems->count(); i++) { VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i)); SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(visualItem); ComplexMissionItem* complexItem = qobject_cast<ComplexMissionItem*>(visualItem); visualItem->setSimpleFlighPathSegment(nullptr); if (simpleItem) { if (roiActive) { if (_isROICancelItem(simpleItem)) { roiActive = false; } } else { if (_isROIBeginItem(simpleItem)) { roiActive = true; } } MAV_CMD command = simpleItem->mavCommand(); switch (command) { case MAV_CMD_NAV_TAKEOFF: case MAV_CMD_NAV_VTOL_TAKEOFF: _missionContainsVTOLTakeoff = command == MAV_CMD_NAV_VTOL_TAKEOFF; if (!linkEndToHome) { // If we still haven't found the first coordinate item and we hit a takeoff command this means the mission starts from the ground. // Link the first item back to home to show that. if (firstCoordinateNotFound) { linkStartToHome = true; } } break; case MAV_CMD_NAV_RETURN_TO_LAUNCH: linkEndToHome = true; foundRTL = true; break; default: break; } } // No need to add waypoint segments after an RTL. if (foundRTL) { break; } if (visualItem->specifiesCoordinate() && !visualItem->isStandaloneCoordinate()) { // Incomplete items are complex items which are waiting for the user to complete setup before there visuals can become valid. // They may not yet have valid entry/exit coordinates associated with them while in the incomplete state. // For examples a Survey item which has no polygon set yet. if (complexItem && complexItem->isIncomplete()) { // We don't link lines from a valid item to an incomplete item previousItemIsIncomplete = true; } else if (previousItemIsIncomplete) { // We also don't link lines from an incomplete item to a valid item. previousItemIsIncomplete = false; firstCoordinateNotFound = false; lastFlyThroughVI = visualItem; } else { if (lastFlyThroughVI != _settingsItem || (homePositionValid && linkStartToHome)) { bool addDirectionArrow = false; if (i != 1) { // Direction arrows are added to the second segment and every 5 segments thereafter. // The reason for start with second segment is to prevent an arrow being added in between the home position // and a takeoff item which may be right over each other. In that case the arrow points in a random direction. if (firstCoordinateNotFound || !lastFlyThroughVI->isSimpleItem() || !visualItem->isSimpleItem()) { addDirectionArrow = true; } else if (segmentCount > 5) { segmentCount = 0; addDirectionArrow = true; } segmentCount++; } lastSegmentVisualItemPair = VisualItemPair(lastFlyThroughVI, visualItem); if (!_flyView || addDirectionArrow) { FlightPathSegment* segment = _addFlightPathSegment(oldSegmentTable, lastSegmentVisualItemPair); segment->setSpecialVisual(roiActive); if (addDirectionArrow) { _directionArrows.append(segment); } lastFlyThroughVI->setSimpleFlighPathSegment(segment); } } firstCoordinateNotFound = false; _waypointPath.append(QVariant::fromValue(visualItem->coordinate())); lastFlyThroughVI = visualItem; } } } if (linkStartToHome && homePositionValid) { _waypointPath.prepend(QVariant::fromValue(_settingsItem->coordinate())); } if (linkEndToHome && lastFlyThroughVI != _settingsItem && homePositionValid) { lastSegmentVisualItemPair = VisualItemPair(lastFlyThroughVI, _settingsItem); if (_flyView) { _waypointPath.append(QVariant::fromValue(_settingsItem->coordinate())); } FlightPathSegment* segment = _addFlightPathSegment(oldSegmentTable, lastSegmentVisualItemPair); segment->setSpecialVisual(roiActive); lastFlyThroughVI->setSimpleFlighPathSegment(segment); } // Add direction arrow to last segment if (lastSegmentVisualItemPair.first) { FlightPathSegment* coordVector = nullptr; // The pair may not be in the hash, this can happen in the fly view where only segments with arrows on them are added to hash. // check for that first and add if needed if (_flightPathSegmentHashTable.contains(lastSegmentVisualItemPair)) { // Pair exists in the new table already just reuse it coordVector = _flightPathSegmentHashTable[lastSegmentVisualItemPair]; } else if (oldSegmentTable.contains(lastSegmentVisualItemPair)) { // Pair already exists in old table, pull from old to new and reuse _flightPathSegmentHashTable[lastSegmentVisualItemPair] = coordVector = oldSegmentTable.take(lastSegmentVisualItemPair); } else { // Create a new segment. Since this is the fly view there is no need to wire change signals. coordVector = new FlightPathSegment(lastSegmentVisualItemPair.first->isSimpleItem() ? lastSegmentVisualItemPair.first->coordinate() : lastSegmentVisualItemPair.first->exitCoordinate(), lastSegmentVisualItemPair.first->isSimpleItem() ? lastSegmentVisualItemPair.first->amslEntryAlt() : lastSegmentVisualItemPair.first->amslExitAlt(), lastSegmentVisualItemPair.second->coordinate(), lastSegmentVisualItemPair.second->amslEntryAlt(), !_flyView /* queryTerrainData */, this); _flightPathSegmentHashTable[lastSegmentVisualItemPair] = coordVector; } _directionArrows.append(coordVector); } _simpleFlightPathSegments.endReset(); _directionArrows.endReset(); _incompleteComplexItemLines.endReset(); // Anything left in the old table is an obsolete line object that can go qDeleteAll(oldSegmentTable); emit _recalcMissionFlightStatusSignal(); if (_waypointPath.count() == 0) { // MapPolyLine has a bug where if you change from a path which has elements to an empty path the line drawn // is not cleared from the map. This hack works around that since it causes the previous lines to be remove // as then doesn't draw anything on the map. _waypointPath.append(QVariant::fromValue(QGeoCoordinate(0, 0))); _waypointPath.append(QVariant::fromValue(QGeoCoordinate(0, 0))); } emit waypointPathChanged(); emit recalcTerrainProfile(); } void MissionController::_updateBatteryInfo(int waypointIndex) { if (_missionFlightStatus.mAhBattery != 0) { _missionFlightStatus.hoverAmpsTotal = (_missionFlightStatus.hoverTime / 60.0) * _missionFlightStatus.hoverAmps; _missionFlightStatus.cruiseAmpsTotal = (_missionFlightStatus.cruiseTime / 60.0) * _missionFlightStatus.cruiseAmps; _missionFlightStatus.batteriesRequired = ceil((_missionFlightStatus.hoverAmpsTotal + _missionFlightStatus.cruiseAmpsTotal) / _missionFlightStatus.ampMinutesAvailable); // FIXME: Battery change point code pretty much doesn't work. The reason is that is treats complex items as a black box. It needs to be able to look // inside complex items in order to determine a swap point that is interior to a complex item. Current the swap point display in PlanToolbar is // disabled to do this problem. if (waypointIndex != -1 && _missionFlightStatus.batteriesRequired == 2 && _missionFlightStatus.batteryChangePoint == -1) { _missionFlightStatus.batteryChangePoint = waypointIndex - 1; } } } void MissionController::_addHoverTime(double hoverTime, double hoverDistance, int waypointIndex) { _missionFlightStatus.totalTime += hoverTime; _missionFlightStatus.hoverTime += hoverTime; _missionFlightStatus.hoverDistance += hoverDistance; _missionFlightStatus.totalDistance += hoverDistance; _updateBatteryInfo(waypointIndex); } void MissionController::_addCruiseTime(double cruiseTime, double cruiseDistance, int waypointIndex) { _missionFlightStatus.totalTime += cruiseTime; _missionFlightStatus.cruiseTime += cruiseTime; _missionFlightStatus.cruiseDistance += cruiseDistance; _missionFlightStatus.totalDistance += cruiseDistance; _updateBatteryInfo(waypointIndex); } /// Adds the specified time to the appropriate hover or cruise time values. /// @param vtolInHover true: vtol is currrent in hover mode /// @param hoverTime Amount of time tp add to hover /// @param cruiseTime Amount of time to add to cruise /// @param extraTime Amount of additional time to add to hover/cruise /// @param seqNum Sequence number of waypoint for these values, -1 for no waypoint associated void MissionController::_addTimeDistance(bool vtolInHover, double hoverTime, double cruiseTime, double extraTime, double distance, int seqNum) { if (_controllerVehicle->vtol()) { if (vtolInHover) { _addHoverTime(hoverTime, distance, seqNum); _addHoverTime(extraTime, 0, -1); } else { _addCruiseTime(cruiseTime, distance, seqNum); _addCruiseTime(extraTime, 0, -1); } } else { if (_controllerVehicle->multiRotor()) { _addHoverTime(hoverTime, distance, seqNum); _addHoverTime(extraTime, 0, -1); } else { _addCruiseTime(cruiseTime, distance, seqNum); _addCruiseTime(extraTime, 0, -1); } } } void MissionController::_recalcMissionFlightStatus() { if (!_visualItems->count()) { return; } bool firstCoordinateItem = true; VisualMissionItem* lastFlyThroughVI = qobject_cast<VisualMissionItem*>(_visualItems->get(0)); bool homePositionValid = _settingsItem->coordinate().isValid(); qCDebug(MissionControllerLog) << "_recalcMissionFlightStatus"; // If home position is valid we can calculate distances between all waypoints. // If home position is not valid we can only calculate distances between waypoints which are // both relative altitude. // No values for first item lastFlyThroughVI->setAltDifference(0); lastFlyThroughVI->setAzimuth(0); lastFlyThroughVI->setDistance(0); lastFlyThroughVI->setDistanceFromStart(0); _minAMSLAltitude = _maxAMSLAltitude = _settingsItem->coordinate().altitude(); _resetMissionFlightStatus(); bool linkStartToHome = false; bool foundRTL = false; double totalHorizontalDistance = 0; for (int i=0; i<_visualItems->count(); i++) { VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i)); SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(item); ComplexMissionItem* complexItem = qobject_cast<ComplexMissionItem*>(item); if (simpleItem && simpleItem->mavCommand() == MAV_CMD_NAV_RETURN_TO_LAUNCH) { foundRTL = true; } // Assume the worst item->setAzimuth(0); item->setDistance(0); item->setDistanceFromStart(0); // Gimbal states reflect the state AFTER executing the item // ROI commands cancel out previous gimbal yaw/pitch if (simpleItem) { switch (simpleItem->command()) { case MAV_CMD_NAV_ROI: case MAV_CMD_DO_SET_ROI_LOCATION: case MAV_CMD_DO_SET_ROI_WPNEXT_OFFSET: _missionFlightStatus.gimbalYaw = qQNaN(); _missionFlightStatus.gimbalPitch = qQNaN(); break; default: break; } } // Look for specific gimbal changes double gimbalYaw = item->specifiedGimbalYaw(); if (!qIsNaN(gimbalYaw) || _planViewSettings->showGimbalOnlyWhenSet()->rawValue().toBool()) { _missionFlightStatus.gimbalYaw = gimbalYaw; } double gimbalPitch = item->specifiedGimbalPitch(); if (!qIsNaN(gimbalPitch) || _planViewSettings->showGimbalOnlyWhenSet()->rawValue().toBool()) { _missionFlightStatus.gimbalPitch = gimbalPitch; } // We don't need to do any more processing if: // Mission Settings Item // We are after an RTL command if (i != 0 && !foundRTL) { // We must set the mission flight status prior to querying for any values from the item. This is because things like // current speed, gimbal, vtol state impact the values. item->setMissionFlightStatus(_missionFlightStatus); // Link back to home if first item is takeoff and we have home position if (firstCoordinateItem && simpleItem && (simpleItem->mavCommand() == MAV_CMD_NAV_TAKEOFF || simpleItem->mavCommand() == MAV_CMD_NAV_VTOL_TAKEOFF)) { if (homePositionValid) { linkStartToHome = true; if (_controllerVehicle->multiRotor() || _controllerVehicle->vtol()) { // We have to special case takeoff, assuming vehicle takes off straight up to specified altitude double azimuth, distance, altDifference; _calcPrevWaypointValues(_settingsItem, simpleItem, &azimuth, &distance, &altDifference); double takeoffTime = qAbs(altDifference) / _appSettings->offlineEditingAscentSpeed()->rawValue().toDouble(); _addHoverTime(takeoffTime, 0, -1); } } } _addTimeDistance(_missionFlightStatus.vtolMode == QGCMAVLink::VehicleClassMultiRotor, 0, 0, item->additionalTimeDelay(), 0, -1); if (item->specifiesCoordinate()) { // Keep track of the min/max AMSL altitude for entire mission so we can calculate altitude percentages in terrain status display if (simpleItem) { double amslAltitude = item->amslEntryAlt(); _minAMSLAltitude = std::min(_minAMSLAltitude, amslAltitude); _maxAMSLAltitude = std::max(_maxAMSLAltitude, amslAltitude); } else { // Complex item double complexMinAMSLAltitude = complexItem->minAMSLAltitude(); double complexMaxAMSLAltitude = complexItem->maxAMSLAltitude(); _minAMSLAltitude = std::min(_minAMSLAltitude, complexMinAMSLAltitude); _maxAMSLAltitude = std::max(_maxAMSLAltitude, complexMaxAMSLAltitude); } if (!item->isStandaloneCoordinate()) { firstCoordinateItem = false; // Update vehicle yaw assuming direction to next waypoint and/or mission item change if (simpleItem) { double newVehicleYaw = simpleItem->specifiedVehicleYaw(); if (qIsNaN(newVehicleYaw)) { // No specific vehicle yaw set. Current vehicle yaw is determined from flight path segment direction. if (simpleItem != lastFlyThroughVI) { _missionFlightStatus.vehicleYaw = lastFlyThroughVI->exitCoordinate().azimuthTo(simpleItem->coordinate()); } } else { _missionFlightStatus.vehicleYaw = newVehicleYaw; } simpleItem->setMissionVehicleYaw(_missionFlightStatus.vehicleYaw); } if (lastFlyThroughVI != _settingsItem || linkStartToHome) { // This is a subsequent waypoint or we are forcing the first waypoint back to home double azimuth, distance, altDifference; _calcPrevWaypointValues(item, lastFlyThroughVI, &azimuth, &distance, &altDifference); totalHorizontalDistance += distance; item->setAltDifference(altDifference); item->setAzimuth(azimuth); item->setDistance(distance); item->setDistanceFromStart(totalHorizontalDistance); _missionFlightStatus.maxTelemetryDistance = qMax(_missionFlightStatus.maxTelemetryDistance, _calcDistanceToHome(item, _settingsItem)); // Calculate time/distance double hoverTime = distance / _missionFlightStatus.hoverSpeed; double cruiseTime = distance / _missionFlightStatus.cruiseSpeed; _addTimeDistance(_missionFlightStatus.vtolMode == QGCMAVLink::VehicleClassMultiRotor, hoverTime, cruiseTime, 0, distance, item->sequenceNumber()); } if (complexItem) { // Add in distance/time inside complex items as well double distance = complexItem->complexDistance(); _missionFlightStatus.maxTelemetryDistance = qMax(_missionFlightStatus.maxTelemetryDistance, complexItem->greatestDistanceTo(complexItem->exitCoordinate())); double hoverTime = distance / _missionFlightStatus.hoverSpeed; double cruiseTime = distance / _missionFlightStatus.cruiseSpeed; _addTimeDistance(_missionFlightStatus.vtolMode == QGCMAVLink::VehicleClassMultiRotor, hoverTime, cruiseTime, 0, distance, item->sequenceNumber()); totalHorizontalDistance += distance; } lastFlyThroughVI = item; } } } // Speed, VTOL states changes are processed last since they take affect on the next item double newSpeed = item->specifiedFlightSpeed(); if (!qIsNaN(newSpeed)) { if (_controllerVehicle->multiRotor()) { _missionFlightStatus.hoverSpeed = newSpeed; } else if (_controllerVehicle->vtol()) { if (_missionFlightStatus.vtolMode == QGCMAVLink::VehicleClassMultiRotor) { _missionFlightStatus.hoverSpeed = newSpeed; } else { _missionFlightStatus.cruiseSpeed = newSpeed; } } else { _missionFlightStatus.cruiseSpeed = newSpeed; } _missionFlightStatus.vehicleSpeed = newSpeed; } // Update VTOL state if (simpleItem && _controllerVehicle->vtol()) { switch (simpleItem->command()) { case MAV_CMD_NAV_TAKEOFF: // This will do a fixed wing style takeoff case MAV_CMD_NAV_VTOL_TAKEOFF: // Vehicle goes straight up and then transitions to FW case MAV_CMD_NAV_LAND: _missionFlightStatus.vtolMode = QGCMAVLink::VehicleClassFixedWing; break; case MAV_CMD_NAV_VTOL_LAND: _missionFlightStatus.vtolMode = QGCMAVLink::VehicleClassMultiRotor; break; case MAV_CMD_DO_VTOL_TRANSITION: { int transitionState = simpleItem->missionItem().param1(); if (transitionState == MAV_VTOL_STATE_MC) { _missionFlightStatus.vtolMode = QGCMAVLink::VehicleClassMultiRotor; } else if (transitionState == MAV_VTOL_STATE_FW) { _missionFlightStatus.vtolMode = QGCMAVLink::VehicleClassFixedWing; } } break; default: break; } } } lastFlyThroughVI->setMissionVehicleYaw(_missionFlightStatus.vehicleYaw); // Add the information for the final segment back to home if (foundRTL && lastFlyThroughVI != _settingsItem && homePositionValid) { double azimuth, distance, altDifference; _calcPrevWaypointValues(lastFlyThroughVI, _settingsItem, &azimuth, &distance, &altDifference); // Calculate time/distance double hoverTime = distance / _missionFlightStatus.hoverSpeed; double cruiseTime = distance / _missionFlightStatus.cruiseSpeed; double landTime = qAbs(altDifference) / _appSettings->offlineEditingDescentSpeed()->rawValue().toDouble(); _addTimeDistance(_missionFlightStatus.vtolMode == QGCMAVLink::VehicleClassMultiRotor, hoverTime, cruiseTime, distance, landTime, -1); } if (_missionFlightStatus.mAhBattery != 0 && _missionFlightStatus.batteryChangePoint == -1) { _missionFlightStatus.batteryChangePoint = 0; } emit missionMaxTelemetryChanged (_missionFlightStatus.maxTelemetryDistance); emit missionDistanceChanged (_missionFlightStatus.totalDistance); emit missionHoverDistanceChanged (_missionFlightStatus.hoverDistance); emit missionCruiseDistanceChanged (_missionFlightStatus.cruiseDistance); emit missionTimeChanged (); emit missionHoverTimeChanged (); emit missionCruiseTimeChanged (); emit batteryChangePointChanged (_missionFlightStatus.batteryChangePoint); emit batteriesRequiredChanged (_missionFlightStatus.batteriesRequired); emit minAMSLAltitudeChanged (_minAMSLAltitude); emit maxAMSLAltitudeChanged (_maxAMSLAltitude); // Walk the list again calculating altitude percentages double altRange = _maxAMSLAltitude - _minAMSLAltitude; for (int i=0; i<_visualItems->count(); i++) { VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i)); if (item->specifiesCoordinate()) { double amslAlt = item->amslEntryAlt(); if (altRange == 0.0) { item->setAltPercent(0.0); item->setTerrainPercent(qQNaN()); item->setTerrainCollision(false); } else { item->setAltPercent((amslAlt - _minAMSLAltitude) / altRange); double terrainAltitude = item->terrainAltitude(); if (qIsNaN(terrainAltitude)) { item->setTerrainPercent(qQNaN()); item->setTerrainCollision(false); } else { item->setTerrainPercent((terrainAltitude - _minAMSLAltitude) / altRange); item->setTerrainCollision(amslAlt < terrainAltitude); } } } } _updateTimer.start(UPDATE_TIMEOUT); emit recalcTerrainProfile(); } // This will update the sequence numbers to be sequential starting from 0 void MissionController::_recalcSequence(void) { if (_inRecalcSequence) { // Don't let this call recurse due to signalling return; } // Setup ascending sequence numbers for all visual items _inRecalcSequence = true; int sequenceNumber = 0; for (int i=0; i<_visualItems->count(); i++) { VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i)); item->setSequenceNumber(sequenceNumber); sequenceNumber = item->lastSequenceNumber() + 1; } _inRecalcSequence = false; } // This will update the child item hierarchy void MissionController::_recalcChildItems(void) { VisualMissionItem* currentParentItem = qobject_cast<VisualMissionItem*>(_visualItems->get(0)); currentParentItem->childItems()->clear(); for (int i=1; i<_visualItems->count(); i++) { VisualMissionItem* item = _visualItems->value<VisualMissionItem*>(i); item->setParentItem(nullptr); item->setHasCurrentChildItem(false); // Set up non-coordinate item child hierarchy if (item->specifiesCoordinate()) { item->childItems()->clear(); currentParentItem = item; } else if (item->isSimpleItem()) { item->setParentItem(currentParentItem); currentParentItem->childItems()->append(item); if (item->isCurrentItem()) { currentParentItem->setHasCurrentChildItem(true); } } } } void MissionController::_setPlannedHomePositionFromFirstCoordinate(const QGeoCoordinate& clickCoordinate) { bool foundFirstCoordinate = false; QGeoCoordinate firstCoordinate; if (_settingsItem->coordinate().isValid()) { return; } // Set the planned home position to be a delta from first coordinate for (int i=1; i<_visualItems->count(); i++) { VisualMissionItem* item = _visualItems->value<VisualMissionItem*>(i); if (item->specifiesCoordinate() && item->coordinate().isValid()) { foundFirstCoordinate = true; firstCoordinate = item->coordinate(); break; } } // No item specifying a coordinate was found, in this case it we have a clickCoordinate use that if (!foundFirstCoordinate) { firstCoordinate = clickCoordinate; } if (firstCoordinate.isValid()) { QGeoCoordinate plannedHomeCoord = firstCoordinate.atDistanceAndAzimuth(30, 0); plannedHomeCoord.setAltitude(0); _settingsItem->setInitialHomePositionFromUser(plannedHomeCoord); } } void MissionController::_recalcAllWithCoordinate(const QGeoCoordinate& coordinate) { if (!_flyView) { _setPlannedHomePositionFromFirstCoordinate(coordinate); } _recalcSequence(); _recalcChildItems(); emit _recalcFlightPathSegmentsSignal(); _updateTimer.start(UPDATE_TIMEOUT); } void MissionController::_recalcAll(void) { QGeoCoordinate emptyCoord; _recalcAllWithCoordinate(emptyCoord); } /// Initializes a new set of mission items void MissionController::_initAllVisualItems(void) { // Setup home position at index 0 if (!_settingsItem) { _settingsItem = qobject_cast<MissionSettingsItem*>(_visualItems->get(0)); if (!_settingsItem) { qWarning() << "First item not MissionSettingsItem"; return; } } connect(_settingsItem, &MissionSettingsItem::coordinateChanged, this, &MissionController::_recalcAll); connect(_settingsItem, &MissionSettingsItem::coordinateChanged, this, &MissionController::plannedHomePositionChanged); for (int i=0; i<_visualItems->count(); i++) { VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i)); _initVisualItem(item); TakeoffMissionItem* takeoffItem = qobject_cast<TakeoffMissionItem*>(item); if (takeoffItem) { _takeoffMissionItem = takeoffItem; } } _recalcAll(); connect(_visualItems, &QmlObjectListModel::dirtyChanged, this, &MissionController::_visualItemsDirtyChanged); connect(_visualItems, &QmlObjectListModel::countChanged, this, &MissionController::_updateContainsItems); emit visualItemsChanged(); emit containsItemsChanged(containsItems()); emit plannedHomePositionChanged(plannedHomePosition()); if (!_flyView) { setCurrentPlanViewSeqNum(0, true); } setDirty(false); } void MissionController::_deinitAllVisualItems(void) { disconnect(_settingsItem, &MissionSettingsItem::coordinateChanged, this, &MissionController::_recalcAll); disconnect(_settingsItem, &MissionSettingsItem::coordinateChanged, this, &MissionController::plannedHomePositionChanged); for (int i=0; i<_visualItems->count(); i++) { _deinitVisualItem(qobject_cast<VisualMissionItem*>(_visualItems->get(i))); } disconnect(_visualItems, &QmlObjectListModel::dirtyChanged, this, &MissionController::dirtyChanged); disconnect(_visualItems, &QmlObjectListModel::countChanged, this, &MissionController::_updateContainsItems); } void MissionController::_initVisualItem(VisualMissionItem* visualItem) { setDirty(false); connect(visualItem, &VisualMissionItem::specifiesCoordinateChanged, this, &MissionController::_recalcFlightPathSegmentsSignal, Qt::QueuedConnection); connect(visualItem, &VisualMissionItem::specifiedFlightSpeedChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(visualItem, &VisualMissionItem::specifiedGimbalYawChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(visualItem, &VisualMissionItem::specifiedGimbalPitchChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(visualItem, &VisualMissionItem::specifiedVehicleYawChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(visualItem, &VisualMissionItem::terrainAltitudeChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(visualItem, &VisualMissionItem::additionalTimeDelayChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(visualItem, &VisualMissionItem::currentVTOLModeChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(visualItem, &VisualMissionItem::lastSequenceNumberChanged, this, &MissionController::_recalcSequence); if (visualItem->isSimpleItem()) { // We need to track commandChanged on simple item since recalc has special handling for takeoff command SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(visualItem); if (simpleItem) { connect(&simpleItem->missionItem()._commandFact, &Fact::valueChanged, this, &MissionController::_itemCommandChanged); } else { qWarning() << "isSimpleItem == true, yet not SimpleMissionItem"; } } else { ComplexMissionItem* complexItem = qobject_cast<ComplexMissionItem*>(visualItem); if (complexItem) { connect(complexItem, &ComplexMissionItem::complexDistanceChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(complexItem, &ComplexMissionItem::greatestDistanceToChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(complexItem, &ComplexMissionItem::minAMSLAltitudeChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(complexItem, &ComplexMissionItem::maxAMSLAltitudeChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(complexItem, &ComplexMissionItem::isIncompleteChanged, this, &MissionController::_recalcFlightPathSegmentsSignal, Qt::QueuedConnection); } else { qWarning() << "ComplexMissionItem not found"; } } } void MissionController::_deinitVisualItem(VisualMissionItem* visualItem) { // Disconnect all signals disconnect(visualItem, nullptr, nullptr, nullptr); } void MissionController::_itemCommandChanged(void) { _recalcChildItems(); emit _recalcFlightPathSegmentsSignal(); } void MissionController::_managerVehicleChanged(Vehicle* managerVehicle) { if (_managerVehicle) { _missionManager->disconnect(this); _managerVehicle->disconnect(this); _managerVehicle = nullptr; _missionManager = nullptr; } _managerVehicle = managerVehicle; if (!_managerVehicle) { qWarning() << "MissionController::managerVehicleChanged managerVehicle=NULL"; return; } _missionManager = _managerVehicle->missionManager(); connect(_missionManager, &MissionManager::newMissionItemsAvailable, this, &MissionController::_newMissionItemsAvailableFromVehicle); connect(_missionManager, &MissionManager::sendComplete, this, &MissionController::_managerSendComplete); connect(_missionManager, &MissionManager::removeAllComplete, this, &MissionController::_managerRemoveAllComplete); connect(_missionManager, &MissionManager::inProgressChanged, this, &MissionController::_inProgressChanged); connect(_missionManager, &MissionManager::progressPct, this, &MissionController::_progressPctChanged); connect(_missionManager, &MissionManager::currentIndexChanged, this, &MissionController::_currentMissionIndexChanged); connect(_missionManager, &MissionManager::lastCurrentIndexChanged, this, &MissionController::resumeMissionIndexChanged); connect(_missionManager, &MissionManager::resumeMissionReady, this, &MissionController::resumeMissionReady); connect(_missionManager, &MissionManager::resumeMissionUploadFail, this, &MissionController::resumeMissionUploadFail); connect(_managerVehicle, &Vehicle::defaultCruiseSpeedChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(_managerVehicle, &Vehicle::defaultHoverSpeedChanged, this, &MissionController::_recalcMissionFlightStatusSignal, Qt::QueuedConnection); connect(_managerVehicle, &Vehicle::vehicleTypeChanged, this, &MissionController::complexMissionItemNamesChanged); emit complexMissionItemNamesChanged(); emit resumeMissionIndexChanged(); } void MissionController::_inProgressChanged(bool inProgress) { emit syncInProgressChanged(inProgress); } bool MissionController::_findPreviousAltitude(int newIndex, double* prevAltitude, int* prevAltitudeMode) { bool found = false; double foundAltitude = 0; int foundAltitudeMode = QGroundControlQmlGlobal::AltitudeModeNone; if (newIndex > _visualItems->count()) { return false; } newIndex--; for (int i=newIndex; i>0; i--) { VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i)); if (visualItem->specifiesCoordinate() && !visualItem->isStandaloneCoordinate()) { if (visualItem->isSimpleItem()) { SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(visualItem); if (simpleItem->specifiesAltitude()) { foundAltitude = simpleItem->altitude()->rawValue().toDouble(); foundAltitudeMode = simpleItem->altitudeMode(); found = true; break; } } } } if (found) { *prevAltitude = foundAltitude; *prevAltitudeMode = foundAltitudeMode; } return found; } double MissionController::_normalizeLat(double lat) { // Normalize latitude to range: 0 to 180, S to N return lat + 90.0; } double MissionController::_normalizeLon(double lon) { // Normalize longitude to range: 0 to 360, W to E return lon + 180.0; } /// Add the Mission Settings complex item to the front of the items MissionSettingsItem* MissionController::_addMissionSettings(QmlObjectListModel* visualItems) { qCDebug(MissionControllerLog) << "_addMissionSettings"; MissionSettingsItem* settingsItem = new MissionSettingsItem(_masterController, _flyView, visualItems); visualItems->insert(0, settingsItem); if (visualItems == _visualItems) { _settingsItem = settingsItem; } return settingsItem; } void MissionController::_centerHomePositionOnMissionItems(QmlObjectListModel *visualItems) { qCDebug(MissionControllerLog) << "_centerHomePositionOnMissionItems"; if (visualItems->count() > 1) { double north = 0.0; double south = 0.0; double east = 0.0; double west = 0.0; bool firstCoordSet = false; for (int i=1; i<visualItems->count(); i++) { VisualMissionItem* item = qobject_cast<VisualMissionItem*>(visualItems->get(i)); if (item->specifiesCoordinate()) { if (firstCoordSet) { double lat = _normalizeLat(item->coordinate().latitude()); double lon = _normalizeLon(item->coordinate().longitude()); north = fmax(north, lat); south = fmin(south, lat); east = fmax(east, lon); west = fmin(west, lon); } else { firstCoordSet = true; north = _normalizeLat(item->coordinate().latitude()); south = north; east = _normalizeLon(item->coordinate().longitude()); west = east; } } } if (firstCoordSet) { _settingsItem->setInitialHomePositionFromUser(QGeoCoordinate((south + ((north - south) / 2)) - 90.0, (west + ((east - west) / 2)) - 180.0, 0.0)); } } } int MissionController::resumeMissionIndex(void) const { int resumeIndex = 0; if (_flyView) { resumeIndex = _missionManager->lastCurrentIndex() + (_controllerVehicle->firmwarePlugin()->sendHomePositionToVehicle() ? 0 : 1); if (resumeIndex > 1 && resumeIndex != _visualItems->value<VisualMissionItem*>(_visualItems->count() - 1)->sequenceNumber()) { // Resume at the item previous to the item we were heading towards resumeIndex--; } else { resumeIndex = 0; } } return resumeIndex; } int MissionController::currentMissionIndex(void) const { if (!_flyView) { return -1; } else { int currentIndex = _missionManager->currentIndex(); if (!_controllerVehicle->firmwarePlugin()->sendHomePositionToVehicle()) { currentIndex++; } return currentIndex; } } void MissionController::_currentMissionIndexChanged(int sequenceNumber) { if (_flyView) { if (!_controllerVehicle->firmwarePlugin()->sendHomePositionToVehicle()) { sequenceNumber++; } for (int i=0; i<_visualItems->count(); i++) { VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i)); item->setIsCurrentItem(item->sequenceNumber() == sequenceNumber); } emit currentMissionIndexChanged(currentMissionIndex()); } } bool MissionController::syncInProgress(void) const { return _missionManager->inProgress(); } bool MissionController::dirty(void) const { return _visualItems ? _visualItems->dirty() : false; } void MissionController::setDirty(bool dirty) { if (_visualItems) { _visualItems->setDirty(dirty); } } void MissionController::_scanForAdditionalSettings(QmlObjectListModel* visualItems, PlanMasterController* masterController) { // First we look for a Landing Patterns which are at the end if (!FixedWingLandingComplexItem::scanForItem(visualItems, _flyView, masterController)) { VTOLLandingComplexItem::scanForItem(visualItems, _flyView, masterController); } int scanIndex = 0; while (scanIndex < visualItems->count()) { VisualMissionItem* visualItem = visualItems->value<VisualMissionItem*>(scanIndex); qCDebug(MissionControllerLog) << "MissionController::_scanForAdditionalSettings count:scanIndex" << visualItems->count() << scanIndex; if (!_flyView) { MissionSettingsItem* settingsItem = qobject_cast<MissionSettingsItem*>(visualItem); if (settingsItem) { scanIndex++; settingsItem->scanForMissionSettings(visualItems, scanIndex); continue; } } SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(visualItem); if (simpleItem) { scanIndex++; simpleItem->scanForSections(visualItems, scanIndex, masterController); } else { // Complex item, can't have sections scanIndex++; } } } void MissionController::_updateContainsItems(void) { emit containsItemsChanged(containsItems()); } bool MissionController::containsItems(void) const { return _visualItems ? _visualItems->count() > 1 : false; } void MissionController::removeAllFromVehicle(void) { if (_masterController->offline()) { qCWarning(MissionControllerLog) << "MissionControllerLog::removeAllFromVehicle called while offline"; } else if (syncInProgress()) { qCWarning(MissionControllerLog) << "MissionControllerLog::removeAllFromVehicle called while syncInProgress"; } else { _itemsRequested = true; _missionManager->removeAll(); } } QStringList MissionController::complexMissionItemNames(void) const { QStringList complexItems; complexItems.append(SurveyComplexItem::name); complexItems.append(CorridorScanComplexItem::name); if (_controllerVehicle->multiRotor() || _controllerVehicle->vtol()) { complexItems.append(StructureScanComplexItem::name); } // Note: The landing pattern items are not added here since they have there own button which adds them return qgcApp()->toolbox()->corePlugin()->complexMissionItemNames(_controllerVehicle, complexItems); } void MissionController::resumeMission(int resumeIndex) { if (!_controllerVehicle->firmwarePlugin()->sendHomePositionToVehicle()) { resumeIndex--; } _missionManager->generateResumeMission(resumeIndex); } QGeoCoordinate MissionController::plannedHomePosition(void) const { if (_settingsItem) { return _settingsItem->coordinate(); } else { return QGeoCoordinate(); } } void MissionController::applyDefaultMissionAltitude(void) { double defaultAltitude = _appSettings->defaultMissionItemAltitude()->rawValue().toDouble(); for (int i=1; i<_visualItems->count(); i++) { VisualMissionItem* item = _visualItems->value<VisualMissionItem*>(i); item->applyNewAltitude(defaultAltitude); } } void MissionController::_progressPctChanged(double progressPct) { if (!QGC::fuzzyCompare(progressPct, _progressPct)) { _progressPct = progressPct; emit progressPctChanged(progressPct); } } void MissionController::_visualItemsDirtyChanged(bool dirty) { // We could connect signal to signal and not need this but this is handy for setting a breakpoint on emit dirtyChanged(dirty); } bool MissionController::showPlanFromManagerVehicle (void) { qCDebug(MissionControllerLog) << "showPlanFromManagerVehicle _flyView" << _flyView; if (_masterController->offline()) { qCWarning(MissionControllerLog) << "MissionController::showPlanFromManagerVehicle called while offline"; return true; // stops further propagation of showPlanFromManagerVehicle due to error } else { if (!_managerVehicle->initialPlanRequestComplete()) { // The vehicle hasn't completed initial load, we can just wait for newMissionItemsAvailable to be signalled automatically qCDebug(MissionControllerLog) << "showPlanFromManagerVehicle: !initialPlanRequestComplete, wait for signal"; return true; } else if (syncInProgress()) { // If the sync is already in progress, newMissionItemsAvailable will be signalled automatically when it is done. So no need to do anything. qCDebug(MissionControllerLog) << "showPlanFromManagerVehicle: syncInProgress wait for signal"; return true; } else { // Fake a _newMissionItemsAvailable with the current items qCDebug(MissionControllerLog) << "showPlanFromManagerVehicle: sync complete simulate signal"; _itemsRequested = true; _newMissionItemsAvailableFromVehicle(false /* removeAllRequested */); return false; } } } void MissionController::_managerSendComplete(bool error) { // Fly view always reloads on send complete if (!error && _flyView) { showPlanFromManagerVehicle(); } } void MissionController::_managerRemoveAllComplete(bool error) { if (!error) { // Remove all from vehicle so we always update showPlanFromManagerVehicle(); } } bool MissionController::_isROIBeginItem(SimpleMissionItem* simpleItem) { return simpleItem->mavCommand() == MAV_CMD_DO_SET_ROI_LOCATION || simpleItem->mavCommand() == MAV_CMD_DO_SET_ROI_WPNEXT_OFFSET || (simpleItem->mavCommand() == MAV_CMD_DO_SET_ROI && static_cast<int>(simpleItem->missionItem().param1()) == MAV_ROI_LOCATION); } bool MissionController::_isROICancelItem(SimpleMissionItem* simpleItem) { return simpleItem->mavCommand() == MAV_CMD_DO_SET_ROI_NONE || (simpleItem->mavCommand() == MAV_CMD_DO_SET_ROI && static_cast<int>(simpleItem->missionItem().param1()) == MAV_ROI_NONE); } void MissionController::setCurrentPlanViewSeqNum(int sequenceNumber, bool force) { if (_visualItems && (force || sequenceNumber != _currentPlanViewSeqNum)) { bool foundLand = false; int takeoffSeqNum = -1; int landSeqNum = -1; int lastFlyThroughSeqNum = -1; _splitSegment = nullptr; _currentPlanViewItem = nullptr; _currentPlanViewSeqNum = -1; _currentPlanViewVIIndex = -1; _onlyInsertTakeoffValid = !_planViewSettings->takeoffItemNotRequired()->rawValue().toBool() && _visualItems->count() == 1; // First item must be takeoff _isInsertTakeoffValid = true; _isInsertLandValid = true; _isROIActive = false; _isROIBeginCurrentItem = false; _flyThroughCommandsAllowed = true; _previousCoordinate = QGeoCoordinate(); for (int viIndex=0; viIndex<_visualItems->count(); viIndex++) { VisualMissionItem* pVI = qobject_cast<VisualMissionItem*>(_visualItems->get(viIndex)); SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(pVI); int currentSeqNumber = pVI->sequenceNumber(); if (sequenceNumber != 0 && currentSeqNumber <= sequenceNumber) { if (pVI->specifiesCoordinate() && !pVI->isStandaloneCoordinate()) { // Coordinate based flight commands prior to where the takeoff would be inserted _isInsertTakeoffValid = false; } } if (qobject_cast<TakeoffMissionItem*>(pVI)) { takeoffSeqNum = currentSeqNumber; _isInsertTakeoffValid = false; } if (!foundLand) { if (simpleItem) { switch (simpleItem->mavCommand()) { case MAV_CMD_NAV_LAND: case MAV_CMD_NAV_VTOL_LAND: case MAV_CMD_DO_LAND_START: case MAV_CMD_NAV_RETURN_TO_LAUNCH: foundLand = true; landSeqNum = currentSeqNumber; break; default: break; } } else { FixedWingLandingComplexItem* fwLanding = qobject_cast<FixedWingLandingComplexItem*>(pVI); if (fwLanding) { foundLand = true; landSeqNum = currentSeqNumber; } } } if (simpleItem) { // Remember previous coordinate if (currentSeqNumber < sequenceNumber && simpleItem->specifiesCoordinate() && !simpleItem->isStandaloneCoordinate()) { _previousCoordinate = simpleItem->coordinate(); } // ROI state handling if (currentSeqNumber <= sequenceNumber) { if (_isROIActive) { if (_isROICancelItem(simpleItem)) { _isROIActive = false; } } else { if (_isROIBeginItem(simpleItem)) { _isROIActive = true; } } } if (currentSeqNumber == sequenceNumber && _isROIBeginItem(simpleItem)) { _isROIBeginCurrentItem = true; } } if (viIndex != 0) { // Complex items are assumed to be fly through if (!simpleItem || (simpleItem->specifiesCoordinate() && !simpleItem->isStandaloneCoordinate())) { lastFlyThroughSeqNum = currentSeqNumber; } } if (currentSeqNumber == sequenceNumber) { pVI->setIsCurrentItem(true); pVI->setHasCurrentChildItem(false); _currentPlanViewItem = pVI; _currentPlanViewSeqNum = sequenceNumber; _currentPlanViewVIIndex = viIndex; if (pVI->specifiesCoordinate()) { if (!pVI->isStandaloneCoordinate()) { // Determine split segment used to display line split editing ui. for (int j=viIndex-1; j>0; j--) { VisualMissionItem* pPrev = qobject_cast<VisualMissionItem*>(_visualItems->get(j)); if (pPrev->specifiesCoordinate() && !pPrev->isStandaloneCoordinate()) { VisualItemPair splitPair(pPrev, pVI); if (_flightPathSegmentHashTable.contains(splitPair)) { _splitSegment = _flightPathSegmentHashTable[splitPair]; } } } } } else if (pVI->parentItem()) { pVI->parentItem()->setHasCurrentChildItem(true); } } else { pVI->setIsCurrentItem(false); } } if (takeoffSeqNum != -1) { // Takeoff item was found which means mission starts from ground if (sequenceNumber < takeoffSeqNum) { // Land is only valid after the takeoff item. _isInsertLandValid = false; // Fly through commands are not allowed prior to the takeoff command _flyThroughCommandsAllowed = false; } } if (lastFlyThroughSeqNum != -1) { // Land item must be after any fly through coordinates if (sequenceNumber < lastFlyThroughSeqNum) { _isInsertLandValid = false; } } if (foundLand) { // Can't have more than one land sequence _isInsertLandValid = false; if (sequenceNumber >= landSeqNum) { // Can't have fly through commands after a land item _flyThroughCommandsAllowed = false; } } // These are not valid when only takeoff is allowed _isInsertLandValid = _isInsertLandValid && !_onlyInsertTakeoffValid; _flyThroughCommandsAllowed = _flyThroughCommandsAllowed && !_onlyInsertTakeoffValid; emit currentPlanViewSeqNumChanged(); emit currentPlanViewVIIndexChanged(); emit currentPlanViewItemChanged(); emit splitSegmentChanged(); emit onlyInsertTakeoffValidChanged(); emit isInsertTakeoffValidChanged(); emit isInsertLandValidChanged(); emit isROIActiveChanged(); emit isROIBeginCurrentItemChanged(); emit flyThroughCommandsAllowedChanged(); emit previousCoordinateChanged(); } } void MissionController::_updateTimeout() { QGeoCoordinate firstCoordinate; QGeoCoordinate takeoffCoordinate; QGCGeoBoundingCube boundingCube; double north = 0.0; double south = 180.0; double east = 0.0; double west = 360.0; double minAlt = QGCGeoBoundingCube::MaxAlt; double maxAlt = QGCGeoBoundingCube::MinAlt; for (int i = 1; i < _visualItems->count(); i++) { VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i)); if(item->isSimpleItem()) { SimpleMissionItem* pSimpleItem = qobject_cast<SimpleMissionItem*>(item); if(pSimpleItem) { switch(pSimpleItem->command()) { case MAV_CMD_NAV_TAKEOFF: case MAV_CMD_NAV_WAYPOINT: case MAV_CMD_NAV_LAND: if(pSimpleItem->coordinate().isValid()) { if((MAV_CMD)pSimpleItem->command() == MAV_CMD_NAV_TAKEOFF) { takeoffCoordinate = pSimpleItem->coordinate(); } else if(!firstCoordinate.isValid()) { firstCoordinate = pSimpleItem->coordinate(); } double lat = pSimpleItem->coordinate().latitude() + 90.0; double lon = pSimpleItem->coordinate().longitude() + 180.0; double alt = pSimpleItem->coordinate().altitude(); north = fmax(north, lat); south = fmin(south, lat); east = fmax(east, lon); west = fmin(west, lon); minAlt = fmin(minAlt, alt); maxAlt = fmax(maxAlt, alt); } break; default: break; } } } else { ComplexMissionItem* pComplexItem = qobject_cast<ComplexMissionItem*>(item); if(pComplexItem) { QGCGeoBoundingCube bc = pComplexItem->boundingCube(); if(bc.isValid()) { if(!firstCoordinate.isValid() && pComplexItem->coordinate().isValid()) { firstCoordinate = pComplexItem->coordinate(); } north = fmax(north, bc.pointNW.latitude() + 90.0); south = fmin(south, bc.pointSE.latitude() + 90.0); east = fmax(east, bc.pointNW.longitude() + 180.0); west = fmin(west, bc.pointSE.longitude() + 180.0); minAlt = fmin(minAlt, bc.pointNW.altitude()); maxAlt = fmax(maxAlt, bc.pointSE.altitude()); } } } } //-- Figure out where this thing is taking off from if(!takeoffCoordinate.isValid()) { if(firstCoordinate.isValid()) { takeoffCoordinate = firstCoordinate; } else { takeoffCoordinate = plannedHomePosition(); } } //-- Build bounding "cube" boundingCube = QGCGeoBoundingCube( QGeoCoordinate(north - 90.0, west - 180.0, minAlt), QGeoCoordinate(south - 90.0, east - 180.0, maxAlt)); if(_travelBoundingCube != boundingCube || _takeoffCoordinate != takeoffCoordinate) { _takeoffCoordinate = takeoffCoordinate; _travelBoundingCube = boundingCube; emit missionBoundingCubeChanged(); qCDebug(MissionControllerLog) << "Bounding cube:" << _travelBoundingCube.pointNW << _travelBoundingCube.pointSE; } } void MissionController::_complexBoundingBoxChanged() { _updateTimer.start(UPDATE_TIMEOUT); } bool MissionController::isEmpty(void) const { return _visualItems->count() <= 1; } void MissionController::_takeoffItemNotRequiredChanged(void) { // Force a recalc of allowed bits setCurrentPlanViewSeqNum(_currentPlanViewSeqNum, true /* force */); } QString MissionController::surveyComplexItemName(void) const { return SurveyComplexItem::name; } QString MissionController::corridorScanComplexItemName(void) const { return CorridorScanComplexItem::name; } QString MissionController::structureScanComplexItemName(void) const { return StructureScanComplexItem::name; } void MissionController::_allItemsRemoved(void) { // When there are no mission items we track changes to firmware/vehicle type. This allows a vehicle connection // to adjust these items. _controllerVehicle->trackFirmwareVehicleTypeChanges(); } void MissionController::_firstItemAdded(void) { // As soon as the first item is added we lock the firmware/vehicle type to current values. So if you then connect a vehicle // it will not affect these values. _controllerVehicle->stopTrackingFirmwareVehicleTypeChanges(); } MissionController::SendToVehiclePreCheckState MissionController::sendToVehiclePreCheck(void) { if (_managerVehicle->isOfflineEditingVehicle()) { return SendToVehiclePreCheckStateNoActiveVehicle; } if (_managerVehicle->armed() && _managerVehicle->flightMode() == _managerVehicle->missionFlightMode()) { return SendToVehiclePreCheckStateActiveMission; } if (_controllerVehicle->firmwareType() != _managerVehicle->firmwareType() || QGCMAVLink::vehicleClass(_controllerVehicle->vehicleType()) != QGCMAVLink::vehicleClass(_managerVehicle->vehicleType())) { return SendToVehiclePreCheckStateFirwmareVehicleMismatch; } return SendToVehiclePreCheckStateOk; } QGroundControlQmlGlobal::AltitudeMode MissionController::globalAltitudeMode(void) { return _globalAltMode; } QGroundControlQmlGlobal::AltitudeMode MissionController::globalAltitudeModeDefault(void) { if (_globalAltMode == QGroundControlQmlGlobal::AltitudeModeNone) { return QGroundControlQmlGlobal::AltitudeModeRelative; } else { return _globalAltMode; } } void MissionController::setGlobalAltitudeMode(QGroundControlQmlGlobal::AltitudeMode altMode) { if (_globalAltMode != altMode) { _globalAltMode = altMode; emit globalAltitudeModeChanged(); } }
44.603559
203
0.6544
pestophagous
339ff395054a6144a88967b7f059cc5963f2b4f1
5,019
hpp
C++
src/mods/GameFunctions/PositionController.hpp
praydog/dx11_mod_base
cfbce80313b782813a959c2d2ceb69705643a6cd
[ "MIT" ]
1
2022-03-26T22:57:55.000Z
2022-03-26T22:57:55.000Z
src/mods/GameFunctions/PositionController.hpp
praydog/dx11_mod_base
cfbce80313b782813a959c2d2ceb69705643a6cd
[ "MIT" ]
null
null
null
src/mods/GameFunctions/PositionController.hpp
praydog/dx11_mod_base
cfbce80313b782813a959c2d2ceb69705643a6cd
[ "MIT" ]
null
null
null
#pragma once #include <mods/GameFunctions/GameFunc.hpp> namespace GameFunctions { class Transform_SetPosition : public GameFunc<void> { private: typedef void (__cdecl *f_set_pos)(void *rcx, void *transform, Vec3 newPos); f_set_pos set_pos; void *transform = nullptr; void invoke() override { throw std::bad_function_call(); } void operator()() override{ invoke(); } uintptr_t get_thread_context(uint32_t unk) override { GameFunc::get_thread_context(); } public: Transform_SetPosition() { fAddr += 0x258BC0; set_pos = (f_set_pos)fAddr; } Transform_SetPosition(void *transformObj) : Transform_SetPosition() { transform = transformObj; } void invoke(void *transformObj, Vec3 newPos) { transform = transformObj; invoke(newPos); } void invoke(Vec3 newPos) { if(transform != nullptr && !IsBadReadPtr(transform, 8)) set_pos(NULL, transform, newPos); } void operator()(void* transformObj, Vec3 newPos) { invoke(transformObj, newPos); } void operator()(Vec3 newPos) { invoke( newPos); } void set_transform(void *obj) {transform = obj; } void *get_transform() const { return transform; } //Change character pos and colliders pos. Only for character obj. static void set_player_pos(uintptr_t character, Vec3 newPos) { if(character == 0) return; auto gameObj = *(uintptr_t*)(character + 0x10); auto transformGameObj = *(uintptr_t*)(gameObj + 0x18); auto cachedCharController = *(uintptr_t*)(character + 0x2F0); auto cachedSubCharController = *(uintptr_t*)(character + 0x2F8); if(cachedCharController == 0 || cachedSubCharController == 0) return; Transform_SetPosition setPos((void*)transformGameObj); setPos(newPos); *(bool*)(cachedCharController + 0x30) = false; *(bool*)(cachedSubCharController + 0x30) = false; *(Vec3*)(cachedCharController + 0x140) = newPos; *(Vec3*)(cachedCharController + 0x150) = newPos; *(Vec3*)(cachedCharController + 0x160) = newPos; *(Vec3*)(cachedSubCharController + 0x140) = newPos; *(Vec3*)(cachedSubCharController + 0x150) = newPos; *(Vec3*)(cachedSubCharController + 0x160) = newPos; *(bool*)(cachedCharController + 0x30) = true; *(bool*)(cachedSubCharController + 0x30) = true; } }; class PositionErrorCorrector : public GameFunc<void> { private: typedef void(__cdecl* f_set_pos)(void* rcx, void* corrector, Vec3 newPos); f_set_pos set_pos; uintptr_t setPosAddr = 0x11D3FD0; typedef void(__cdecl* f_stop_internal)(void* rcx, void* corrector); f_stop_internal def_stop_internal; uintptr_t stopInternalAddr = 0x11D3CA0; typedef void(__cdecl* f_restatrt)(void* rcx, void* corrector); f_restatrt def_restart; uintptr_t restartAddr = 0x11CF640; void* corrector = nullptr; void invoke() override { throw std::bad_function_call(); } void operator()() override { invoke(); } bool check_ptrs() { if (!IsBadReadPtr((void*)threadContext, 8) && !IsBadReadPtr(corrector, 8)) return true; return false; } void check_thread_context() { if (threadContext == 0) threadContext = get_thread_context(); } bool full_check() { check_thread_context(); return check_ptrs(); } public: PositionErrorCorrector() { setPosAddr += fAddr; set_pos = (f_set_pos)setPosAddr; stopInternalAddr += fAddr; def_stop_internal = (f_stop_internal)stopInternalAddr; restartAddr += fAddr; def_restart = (f_restatrt)(restartAddr); threadContext = get_thread_context(); } PositionErrorCorrector(void* correctorObj) : PositionErrorCorrector() { corrector = correctorObj; } void set_corrector(void* obj) { corrector = obj; } void set_position(Vec3 newPos) { threadContext = get_thread_context(); if(full_check()) set_pos((void*)threadContext, corrector, newPos); } void set_position(void *correctorObj, Vec3 newPos) { corrector = correctorObj; set_position(newPos); } void stop_internal() { threadContext = get_thread_context(); if(full_check()) def_stop_internal((void*)threadContext, corrector); } void stop_internal(void *correctorObj) { corrector = correctorObj; stop_internal(); } void restart() { threadContext = get_thread_context(); if(full_check()) def_restart((void*)threadContext, corrector); } void restart(void *correctorObj) { corrector = correctorObj; restart(); } }; class SetSafePosition : public GameFunc<void> { private: typedef void(__cdecl* f_set_pos)(void* rcx, void* player, Vec3 pos); f_set_pos set_safe_pos; const ptrdiff_t setSafePosOffs = 0x162DE10; void invoke() override { } void operator()() override { } public: SetSafePosition() { fAddr += setSafePosOffs; set_safe_pos = (f_set_pos)fAddr; } void invoke(void *player, Vec3 pos) { set_safe_pos(nullptr, player, pos); } void operator()(void* player, Vec3 pos) { set_safe_pos(nullptr, player, pos); } }; }
22.110132
84
0.687986
praydog
33a2f24aafaed2b130a041eb68d80854b5af7cd2
1,552
cpp
C++
aws-cpp-sdk-pinpoint/source/model/OverrideButtonConfiguration.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-pinpoint/source/model/OverrideButtonConfiguration.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-pinpoint/source/model/OverrideButtonConfiguration.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/pinpoint/model/OverrideButtonConfiguration.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Pinpoint { namespace Model { OverrideButtonConfiguration::OverrideButtonConfiguration() : m_buttonAction(ButtonAction::NOT_SET), m_buttonActionHasBeenSet(false), m_linkHasBeenSet(false) { } OverrideButtonConfiguration::OverrideButtonConfiguration(JsonView jsonValue) : m_buttonAction(ButtonAction::NOT_SET), m_buttonActionHasBeenSet(false), m_linkHasBeenSet(false) { *this = jsonValue; } OverrideButtonConfiguration& OverrideButtonConfiguration::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("ButtonAction")) { m_buttonAction = ButtonActionMapper::GetButtonActionForName(jsonValue.GetString("ButtonAction")); m_buttonActionHasBeenSet = true; } if(jsonValue.ValueExists("Link")) { m_link = jsonValue.GetString("Link"); m_linkHasBeenSet = true; } return *this; } JsonValue OverrideButtonConfiguration::Jsonize() const { JsonValue payload; if(m_buttonActionHasBeenSet) { payload.WithString("ButtonAction", ButtonActionMapper::GetNameForButtonAction(m_buttonAction)); } if(m_linkHasBeenSet) { payload.WithString("Link", m_link); } return payload; } } // namespace Model } // namespace Pinpoint } // namespace Aws
20.421053
101
0.749356
perfectrecall
33a31f6c043bcbdc46062e11f8f25778446fdd91
1,267
cc
C++
Code/1177-tree-diameter.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
2
2019-12-06T14:08:57.000Z
2020-01-15T15:25:32.000Z
Code/1177-tree-diameter.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
1
2020-01-15T16:29:16.000Z
2020-01-26T12:40:13.000Z
Code/1177-tree-diameter.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
null
null
null
class Solution { unordered_map<int, unordered_set<int>> m; unordered_map<int, unordered_map<int, int>> dp; public: int treeDiameter(vector<vector<int>>& edges) { for (auto &edge : edges) { m[edge[0]].insert(edge[1]); m[edge[1]].insert(edge[0]); } int result = 0; for (auto it = m.begin(); it != m.end(); ++it) { if ((it->second).size() == 1) { result = max(result, helper(it->first, it->first, edges)); } } return result; } int helper(int currentIndex, int lastIndex, vector<vector<int>>& edges) { // cout << currentIndex <<" " << lastIndex << " ========" << endl; if (currentIndex >= edges.size()) { return 0; } if (dp[currentIndex][lastIndex] != 0) { return dp[currentIndex][lastIndex]; } int tmp = 0; for (auto it = m[currentIndex].begin(); it != m[currentIndex].end(); ++it) { if (*it != lastIndex) { tmp = max(tmp, helper(*it, currentIndex, edges) + 1); } } dp[currentIndex][lastIndex] = tmp; // cout << currentIndex <<" " << lastIndex << " "<< tmp << endl; return tmp; } };
35.194444
84
0.48382
SMartQi
33a5dd2e39d8208721052f3670c61097721a6d2c
125,725
cpp
C++
src/module.cpp
tay10r/ispc
33cd2311acaeeff5d870ae182f526fe08ecdbe3a
[ "BSD-3-Clause" ]
null
null
null
src/module.cpp
tay10r/ispc
33cd2311acaeeff5d870ae182f526fe08ecdbe3a
[ "BSD-3-Clause" ]
null
null
null
src/module.cpp
tay10r/ispc
33cd2311acaeeff5d870ae182f526fe08ecdbe3a
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010-2021, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** @file module.cpp @brief Impementation of the Module class, which collects the result of compiling a source file and then generates output (object files, etc.) */ #include "module.h" #include "builtins.h" #include "ctx.h" #include "expr.h" #include "func.h" #include "llvmutil.h" #include "opt.h" #include "stmt.h" #include "sym.h" #include "type.h" #include "util.h" #include <algorithm> #include <ctype.h> #include <fcntl.h> #include <set> #include <sstream> #include <stdarg.h> #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #ifdef ISPC_HOST_IS_WINDOWS #include <io.h> #include <windows.h> #define strcasecmp stricmp #endif #include <clang/Basic/TargetInfo.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/Utils.h> #include <clang/Lex/PreprocessorOptions.h> #include <llvm/Analysis/TargetTransformInfo.h> #include <llvm/Bitcode/BitcodeWriter.h> #include <llvm/IR/CFG.h> #include <llvm/IR/DataLayout.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/IRPrintingPasses.h> #include <llvm/IR/InstIterator.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/Intrinsics.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/LegacyPassManager.h> #include <llvm/IR/Module.h> #include <llvm/IR/Type.h> #include <llvm/IR/Verifier.h> #include <llvm/PassRegistry.h> #include <llvm/Support/CommandLine.h> #include <llvm/Support/DynamicLibrary.h> #include <llvm/Support/FileUtilities.h> #include <llvm/Support/FormattedStream.h> #include <llvm/Support/Host.h> #include <llvm/Support/ToolOutputFile.h> #include <llvm/Support/raw_ostream.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Target/TargetOptions.h> #include <llvm/Transforms/IPO.h> #include <llvm/Transforms/Utils/ValueMapper.h> #ifdef ISPC_GENX_ENABLED #include <LLVMSPIRVLib/LLVMSPIRVLib.h> #include <fstream> #if defined(_WIN64) #define OCLOC_LIBRARY_NAME "ocloc64.dll" #elif defined(_WIN32) #define OCLOC_LIBRARY_NAME "ocloc32.dll" #elif defined(__linux__) #define OCLOC_LIBRARY_NAME "libocloc.so" #else #error "Unexpected platform" #endif #endif /*! list of files encountered by the parser. this allows emitting of the module file's dependencies via the -MMM option */ std::set<std::string> registeredDependencies; /*! this is where the parser tells us that it has seen the given file name in the CPP hash */ void RegisterDependency(const std::string &fileName) { if (fileName[0] != '<' && fileName != "stdlib.ispc") registeredDependencies.insert(fileName); } static void lDeclareSizeAndPtrIntTypes(SymbolTable *symbolTable) { const Type *ptrIntType = (g->target->is32Bit()) ? AtomicType::VaryingInt32 : AtomicType::VaryingInt64; ptrIntType = ptrIntType->GetAsUnboundVariabilityType(); symbolTable->AddType("intptr_t", ptrIntType, SourcePos()); symbolTable->AddType("uintptr_t", ptrIntType->GetAsUnsignedType(), SourcePos()); symbolTable->AddType("ptrdiff_t", ptrIntType, SourcePos()); const Type *sizeType = (g->target->is32Bit() || g->opt.force32BitAddressing) ? AtomicType::VaryingUInt32 : AtomicType::VaryingUInt64; sizeType = sizeType->GetAsUnboundVariabilityType(); symbolTable->AddType("size_t", sizeType, SourcePos()); } /** After compilation completes, there's often a lot of extra debugging metadata left around that isn't needed any more--for example, for static functions that weren't actually used, function information for functions that were inlined, etc. This function takes a llvm::Module and tries to strip out all of this extra stuff. */ static void lStripUnusedDebugInfo(llvm::Module *module) { return; } /////////////////////////////////////////////////////////////////////////// // Module Module::Module(const char *fn) { // It's a hack to do this here, but it must be done after the target // information has been set (so e.g. the vector width is known...) In // particular, if we're compiling to multiple targets with different // vector widths, this needs to be redone each time through. InitLLVMUtil(g->ctx, *g->target); filename = fn; errorCount = 0; symbolTable = new SymbolTable; ast = new AST; lDeclareSizeAndPtrIntTypes(symbolTable); module = new llvm::Module(!IsStdin(filename) ? filename : "<stdin>", *g->ctx); module->setTargetTriple(g->target->GetTripleString()); diBuilder = NULL; diCompileUnit = NULL; // DataLayout information supposed to be managed in single place in Target class. module->setDataLayout(g->target->getDataLayout()->getStringRepresentation()); if (g->generateDebuggingSymbols) { llvm::TimeTraceScope TimeScope("Create Debug Data"); // To enable debug information on Windows, we have to let llvm know, that // debug information should be emitted in CodeView format. if (g->target_os == TargetOS::windows) { module->addModuleFlag(llvm::Module::Warning, "CodeView", 1); } else { // When we link with CM, "Dwarf version" and "Debug info version" is already set // so we don't need to do this here. Otherwise VerifyModule will be broken. if (!g->target->isGenXTarget()) { module->addModuleFlag(llvm::Module::Warning, "Dwarf Version", g->generateDWARFVersion); } } diBuilder = new llvm::DIBuilder(*module); // Let the DIBuilder know that we're starting a new compilation // unit. if (IsStdin(filename)) { // Unfortunately we can't yet call Error() since the global 'm' // variable hasn't been initialized yet. Error(SourcePos(), "Can't emit debugging information with no " "source file on disk.\n"); ++errorCount; delete diBuilder; diBuilder = NULL; } else { std::string directory, name; GetDirectoryAndFileName(g->currentDirectory, filename, &directory, &name); char producerString[512]; #if defined(BUILD_VERSION) && defined(BUILD_DATE) snprintf(producerString, sizeof(producerString), "ispc version %s (build %s on %s)", ISPC_VERSION, BUILD_VERSION, BUILD_DATE); #else snprintf(producerString, sizeof(producerString), "ispc version %s (built on %s)", ISPC_VERSION, __DATE__); #endif auto srcFile = diBuilder->createFile(name, directory); diCompileUnit = diBuilder->createCompileUnit(llvm::dwarf::DW_LANG_C99, /* lang */ srcFile, /* filename */ producerString, /* producer */ g->opt.level > 0 /* is optimized */, "-g", /* command line args */ 0 /* run time version */); } } } extern FILE *yyin; extern int yyparse(); typedef struct yy_buffer_state *YY_BUFFER_STATE; extern void yy_switch_to_buffer(YY_BUFFER_STATE); extern YY_BUFFER_STATE yy_scan_string(const char *); extern YY_BUFFER_STATE yy_create_buffer(FILE *, int); extern void yy_delete_buffer(YY_BUFFER_STATE); int Module::CompileFile() { llvm::TimeTraceScope CompileFileTimeScope( "CompileFile", llvm::StringRef(filename + ("_" + std::string(g->target->GetISAString())))); extern void ParserInit(); ParserInit(); // FIXME: it'd be nice to do this in the Module constructor, but this // function ends up calling into routines that expect the global // variable 'm' to be initialized and available (which it isn't until // the Module constructor returns...) { llvm::TimeTraceScope TimeScope("DefineStdlib"); DefineStdlib(symbolTable, g->ctx, module, g->includeStdlib); } bool runPreprocessor = g->runCPP; if (runPreprocessor) { llvm::TimeTraceScope TimeScope("Frontend parser"); if (!IsStdin(filename)) { // Try to open the file first, since otherwise we crash in the // preprocessor if the file doesn't exist. FILE *f = fopen(filename, "r"); if (!f) { perror(filename); return 1; } fclose(f); } std::string buffer; llvm::raw_string_ostream os(buffer); execPreprocessor(!IsStdin(filename) ? filename : "-", &os); YY_BUFFER_STATE strbuf = yy_scan_string(os.str().c_str()); yyparse(); yy_delete_buffer(strbuf); } else { llvm::TimeTraceScope TimeScope("Frontend parser"); // No preprocessor, just open up the file if it's not stdin.. FILE *f = NULL; if (IsStdin(filename)) { f = stdin; } else { f = fopen(filename, "r"); if (f == NULL) { perror(filename); return 1; } } yyin = f; yy_switch_to_buffer(yy_create_buffer(yyin, 4096)); yyparse(); fclose(f); } if (g->NoOmitFramePointer) for (llvm::Function &f : *module) f.addFnAttr("no-frame-pointer-elim", "true"); for (llvm::Function &f : *module) g->target->markFuncWithTargetAttr(&f); ast->GenerateIR(); if (diBuilder) diBuilder->finalize(); llvm::TimeTraceScope TimeScope("Optimize"); if (errorCount == 0) Optimize(module, g->opt.level); return errorCount; } void Module::AddTypeDef(const std::string &name, const Type *type, SourcePos pos) { // Typedefs are easy; just add the mapping between the given name and // the given type. symbolTable->AddType(name.c_str(), type, pos); } void Module::AddGlobalVariable(const std::string &name, const Type *type, Expr *initExpr, bool isConst, StorageClass storageClass, SourcePos pos) { // These may be NULL due to errors in parsing; just gracefully return // here if so. if (name == "" || type == NULL) { Assert(errorCount > 0); return; } if (symbolTable->LookupFunction(name.c_str())) { Error(pos, "Global variable \"%s\" shadows previously-declared " "function.", name.c_str()); return; } if (storageClass == SC_EXTERN_C) { Error(pos, "extern \"C\" qualifier can only be used for " "functions."); return; } if (type->IsVoidType()) { Error(pos, "\"void\" type global variable is illegal."); return; } type = ArrayType::SizeUnsizedArrays(type, initExpr); if (type == NULL) return; const ArrayType *at = CastType<ArrayType>(type); if (at != NULL && at->TotalElementCount() == 0) { Error(pos, "Illegal to declare a global variable with unsized " "array dimensions that aren't set with an initializer " "expression."); return; } llvm::Type *llvmType = type->LLVMStorageType(g->ctx); if (llvmType == NULL) return; // See if we have an initializer expression for the global. If so, // make sure it's a compile-time constant! llvm::Constant *llvmInitializer = NULL; ConstExpr *constValue = NULL; if (storageClass == SC_EXTERN) { if (initExpr != NULL) Error(pos, "Initializer can't be provided with \"extern\" " "global variable \"%s\".", name.c_str()); } else { if (initExpr != NULL) { initExpr = TypeCheck(initExpr); if (initExpr != NULL) { // We need to make sure the initializer expression is // the same type as the global. (But not if it's an // ExprList; they don't have types per se / can't type // convert themselves anyway.) if (llvm::dyn_cast<ExprList>(initExpr) == NULL) initExpr = TypeConvertExpr(initExpr, type, "initializer"); if (initExpr != NULL) { initExpr = Optimize(initExpr); // Fingers crossed, now let's see if we've got a // constant value.. std::pair<llvm::Constant *, bool> initPair = initExpr->GetStorageConstant(type); llvmInitializer = initPair.first; // If compiling for multitarget, skip initialization for // indentified scenarios unless it's static if (llvmInitializer != NULL) { if ((storageClass != SC_STATIC) && (initPair.second == true)) { if (g->isMultiTargetCompilation == true) { Error(initExpr->pos, "Initializer for global variable \"%s\" " "is not a constant for multi-target compilation.", name.c_str()); return; } Warning(initExpr->pos, "Initializer for global variable \"%s\" " "is a constant for single-target compilation " "but not for multi-target compilation.", name.c_str()); } if (type->IsConstType()) // Try to get a ConstExpr associated with // the symbol. This llvm::dyn_cast can // validly fail, for example for types like // StructTypes where a ConstExpr can't // represent their values. constValue = llvm::dyn_cast<ConstExpr>(initExpr); } else Error(initExpr->pos, "Initializer for global variable \"%s\" " "must be a constant.", name.c_str()); } } } // If no initializer was provided or if we couldn't get a value // above, initialize it with zeros.. if (llvmInitializer == NULL) llvmInitializer = llvm::Constant::getNullValue(llvmType); } Symbol *sym = symbolTable->LookupVariable(name.c_str()); llvm::GlobalVariable *oldGV = NULL; if (sym != NULL) { // We've already seen either a declaration or a definition of this // global. // If the type doesn't match with the previous one, issue an error. if (!Type::Equal(sym->type, type) || (sym->storageClass != SC_EXTERN && sym->storageClass != SC_EXTERN_C && sym->storageClass != storageClass)) { Error(pos, "Definition of variable \"%s\" conflicts with " "definition at %s:%d.", name.c_str(), sym->pos.name, sym->pos.first_line); return; } llvm::GlobalVariable *gv = llvm::dyn_cast<llvm::GlobalVariable>(sym->storagePtr); Assert(gv != NULL); // And issue an error if this is a redefinition of a variable if (gv->hasInitializer() && sym->storageClass != SC_EXTERN && sym->storageClass != SC_EXTERN_C) { Error(pos, "Redefinition of variable \"%s\" is illegal. " "(Previous definition at %s:%d.)", sym->name.c_str(), sym->pos.name, sym->pos.first_line); return; } // Now, we either have a redeclaration of a global, or a definition // of a previously-declared global. First, save the pointer to the // previous llvm::GlobalVariable oldGV = gv; } else { sym = new Symbol(name, pos, type, storageClass); symbolTable->AddVariable(sym); } sym->constValue = constValue; llvm::GlobalValue::LinkageTypes linkage = (sym->storageClass == SC_STATIC) ? llvm::GlobalValue::InternalLinkage : llvm::GlobalValue::ExternalLinkage; // Note that the NULL llvmInitializer is what leads to "extern" // declarations coming up extern and not defining storage (a bit // subtle)... sym->storagePtr = new llvm::GlobalVariable(*module, llvmType, isConst, linkage, llvmInitializer, sym->name.c_str()); // Patch up any references to the previous GlobalVariable (e.g. from a // declaration of a global that was later defined.) if (oldGV != NULL) { oldGV->replaceAllUsesWith(sym->storagePtr); oldGV->removeFromParent(); sym->storagePtr->setName(sym->name.c_str()); } if (diBuilder) { llvm::DIFile *file = pos.GetDIFile(); llvm::DINamespace *diSpace = pos.GetDINamespace(); // llvm::MDFile *file = pos.GetDIFile(); llvm::GlobalVariable *sym_GV_storagePtr = llvm::dyn_cast<llvm::GlobalVariable>(sym->storagePtr); Assert(sym_GV_storagePtr); llvm::DIGlobalVariableExpression *var = diBuilder->createGlobalVariableExpression( diSpace, name, name, file, pos.first_line, sym->type->GetDIType(diSpace), (sym->storageClass == SC_STATIC)); sym_GV_storagePtr->addDebugInfo(var); /*#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 Assert(var.Verify()); #else // LLVM 3.7+ // comming soon #endif*/ } } /** Given an arbitrary type, see if it or any of the leaf types contained in it has a type that's illegal to have exported to C/C++ code. (Note that it's fine for the original struct or a contained struct to be varying, so long as all of its members have bound 'uniform' variability.) This functions returns true and issues an error if are any illegal types are found and returns false otherwise. */ static bool lRecursiveCheckValidParamType(const Type *t, bool vectorOk, bool soaOk, const std::string &name, SourcePos pos) { const StructType *st = CastType<StructType>(t); if (st != NULL) { for (int i = 0; i < st->GetElementCount(); ++i) if (!lRecursiveCheckValidParamType(st->GetElementType(i), soaOk, vectorOk, name, pos)) return false; return true; } // Vector types are also not supported, pending ispc properly // supporting the platform ABI. (Pointers to vector types are ok, // though.) (https://github.com/ispc/ispc/issues/363)... if (vectorOk == false && CastType<VectorType>(t) != NULL) return false; const SequentialType *seqt = CastType<SequentialType>(t); if (seqt != NULL) return lRecursiveCheckValidParamType(seqt->GetElementType(), soaOk, vectorOk, name, pos); const PointerType *pt = CastType<PointerType>(t); if (pt != NULL) { // Only allow exported uniform pointers // Uniform pointers to varying data, however, are ok. if (pt->IsVaryingType()) return false; else return lRecursiveCheckValidParamType(pt->GetBaseType(), true, true, name, pos); } if (t->IsSOAType() && soaOk) { Warning(pos, "Exported function parameter \"%s\" points to SOA type.", name.c_str()); return false; } if (t->IsVaryingType() && !vectorOk) return false; else { if (t->IsVaryingType()) { Warning(pos, "Exported function parameter \"%s\" points to varying type", name.c_str()); } return true; } } /** Given a Symbol representing a function parameter, see if it or any contained types are varying. If so, issue an error. (This function should only be called for parameters to 'export'ed functions, where varying parameters is illegal. */ static void lCheckExportedParameterTypes(const Type *type, const std::string &name, SourcePos pos) { if (lRecursiveCheckValidParamType(type, false, false, name, pos) == false) { if (const PointerType *pt = CastType<PointerType>(type)) { bool isSOAType = false; while (pt) { if (pt->GetBaseType()->IsSOAType()) { isSOAType = true; Error(pos, "SOA type parameter \"%s\" is illegal " "in an exported function.", name.c_str()); } pt = CastType<PointerType>(pt->GetBaseType()); } if (!isSOAType) { Error(pos, "Varying pointer type parameter \"%s\" is illegal " "in an exported function.", name.c_str()); } } if (CastType<StructType>(type->GetBaseType())) Error(pos, "Struct parameter \"%s\" with vector typed " "member(s) is illegal in an exported function.", name.c_str()); else if (CastType<VectorType>(type)) Error(pos, "Vector-typed parameter \"%s\" is illegal in an exported " "function.", name.c_str()); else Error(pos, "Varying parameter \"%s\" is illegal in an exported function.", name.c_str()); } } #ifdef ISPC_GENX_ENABLED // For gen target we have the same limitations in input parameters as for "export" functions static void lCheckTaskParameterTypes(const Type *type, const std::string &name, SourcePos pos) { if (lRecursiveCheckValidParamType(type, false, false, name, pos) == false) { if (CastType<PointerType>(type)) Error(pos, "Varying pointer type parameter \"%s\" is illegal " "in an \"task\" for genx-* targets.", name.c_str()); if (CastType<StructType>(type->GetBaseType())) Error(pos, "Struct parameter \"%s\" with vector typed " "member(s) is illegal in an \"task\" for genx-* targets.", name.c_str()); else if (CastType<VectorType>(type)) Error(pos, "Vector-typed parameter \"%s\" is illegal in an \"task\" " "for genx-* targets.", name.c_str()); else Error(pos, "Varying parameter \"%s\" is illegal in an \"task\" for genx-* targets.", name.c_str()); } } #endif /** Given a function type, loop through the function parameters and see if any are StructTypes. If so, issue an error; this is currently broken (https://github.com/ispc/ispc/issues/3). */ static void lCheckForStructParameters(const FunctionType *ftype, SourcePos pos) { for (int i = 0; i < ftype->GetNumParameters(); ++i) { const Type *type = ftype->GetParameterType(i); if (CastType<StructType>(type) != NULL) { Error(pos, "Passing structs to/from application functions by value " "is currently not supported. Use a reference, a const reference, " "a pointer, or a const pointer to the struct instead."); return; } } } /** We've got a declaration for a function to process. This function does all the work of creating the corresponding llvm::Function instance, adding the symbol for the function to the symbol table and doing various sanity checks. This function returns true upon success and false if any errors were encountered. */ void Module::AddFunctionDeclaration(const std::string &name, const FunctionType *functionType, StorageClass storageClass, bool isInline, bool isNoInline, bool isVectorCall, SourcePos pos) { Assert(functionType != NULL); // If a global variable with the same name has already been declared // issue an error. if (symbolTable->LookupVariable(name.c_str()) != NULL) { Error(pos, "Function \"%s\" shadows previously-declared global variable. " "Ignoring this definition.", name.c_str()); return; } std::vector<Symbol *> overloadFuncs; symbolTable->LookupFunction(name.c_str(), &overloadFuncs); if (overloadFuncs.size() > 0) { for (unsigned int i = 0; i < overloadFuncs.size(); ++i) { Symbol *overloadFunc = overloadFuncs[i]; const FunctionType *overloadType = CastType<FunctionType>(overloadFunc->type); if (overloadType == NULL) { Assert(m->errorCount == 0); continue; } // Check for a redeclaration of a function with the same name // and type. This also hits when we have previously declared // the function and are about to define it. if (Type::Equal(overloadFunc->type, functionType)) return; if (functionType->isExported || overloadType->isExported) Error(pos, "Illegal to provide \"export\" qualifier for " "functions with the same name but different types. " "(Previous function declaration (%s:%d).)", overloadFunc->pos.name, overloadFunc->pos.first_line); // If all of the parameter types match but the return type is // different, return an error--overloading by return type isn't // allowed. const FunctionType *ofType = CastType<FunctionType>(overloadFunc->type); Assert(ofType != NULL); if (ofType->GetNumParameters() == functionType->GetNumParameters()) { int i; for (i = 0; i < functionType->GetNumParameters(); ++i) { if (Type::Equal(ofType->GetParameterType(i), functionType->GetParameterType(i)) == false) break; } if (i == functionType->GetNumParameters()) { std::string thisRetType = functionType->GetReturnTypeString(); std::string otherRetType = ofType->GetReturnTypeString(); Error(pos, "Illegal to overload function by return " "type only. This function returns \"%s\" while " "previous declaration at %s:%d returns \"%s\".", thisRetType.c_str(), overloadFunc->pos.name, overloadFunc->pos.first_line, otherRetType.c_str()); return; } } } } if (storageClass == SC_EXTERN_C) { // Make sure the user hasn't supplied both an 'extern "C"' and a // 'task' qualifier with the function if (functionType->isTask) { Error(pos, "\"task\" qualifier is illegal with C-linkage extern " "function \"%s\". Ignoring this function.", name.c_str()); return; } std::vector<Symbol *> funcs; symbolTable->LookupFunction(name.c_str(), &funcs); if (funcs.size() > 0) { if (funcs.size() > 1) { // Multiple functions with this name have already been declared; // can't overload here Error(pos, "Can't overload extern \"C\" function \"%s\"; " "%d functions with the same name have already been declared.", name.c_str(), (int)funcs.size()); return; } // One function with the same name has been declared; see if it // has the same type as this one, in which case it's ok. if (Type::Equal(funcs[0]->type, functionType)) return; else { Error(pos, "Can't overload extern \"C\" function \"%s\".", name.c_str()); return; } } } // Get the LLVM FunctionType bool disableMask = (storageClass == SC_EXTERN_C); llvm::FunctionType *llvmFunctionType = functionType->LLVMFunctionType(g->ctx, disableMask); if (llvmFunctionType == NULL) return; // And create the llvm::Function llvm::GlobalValue::LinkageTypes linkage = (storageClass == SC_STATIC || isInline) ? llvm::GlobalValue::InternalLinkage : llvm::GlobalValue::ExternalLinkage; // For gen target all functions except genx kernel must be internal. // Genx kernel functions are "export"-qualified functions and tasks. if (g->target->isGenXTarget() && !functionType->isExported && !functionType->isTask) linkage = llvm::GlobalValue::InternalLinkage; std::string functionName = name; if (storageClass != SC_EXTERN_C) { functionName += functionType->Mangle(); // If we treat generic as smth, we should have appropriate mangling if (g->mangleFunctionsWithTarget) { functionName += g->target->GetISAString(); } } llvm::Function *function = llvm::Function::Create(llvmFunctionType, linkage, functionName.c_str(), module); if (g->target_os == TargetOS::windows) { // Make export functions callable from DLLs. if ((g->dllExport) && (storageClass != SC_STATIC)) { function->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); } } if (isNoInline && isInline) { Error(pos, "Illegal to use \"noinline\" and \"inline\" qualifiers together on function \"%s\".", name.c_str()); return; } // Set function attributes: we never throw exceptions function->setDoesNotThrow(); if (storageClass != SC_EXTERN_C && isInline) { function->addFnAttr(llvm::Attribute::AlwaysInline); } if (isVectorCall) { if ((storageClass != SC_EXTERN_C)) { Error(pos, "Illegal to use \"__vectorcall\" qualifier on non-extern function \"%s\".", name.c_str()); return; } if (g->target_os != TargetOS::windows) { Error(pos, "Illegal to use \"__vectorcall\" qualifier on function \"%s\" for non-Windows OS.", name.c_str()); return; } } if (isNoInline) { function->addFnAttr(llvm::Attribute::NoInline); } if (functionType->isTask) { if (!g->target->isGenXTarget()) { // This also applies transitively to members I think? function->addParamAttr(0, llvm::Attribute::NoAlias); } } if (((isVectorCall) && (storageClass == SC_EXTERN_C)) || (storageClass != SC_EXTERN_C)) { g->target->markFuncWithCallingConv(function); } g->target->markFuncWithTargetAttr(function); // Make sure that the return type isn't 'varying' or vector typed if // the function is 'export'ed. if (functionType->isExported && lRecursiveCheckValidParamType(functionType->GetReturnType(), false, false, name, pos) == false) Error(pos, "Illegal to return a \"varying\" or vector type from " "exported function \"%s\"", name.c_str()); if (functionType->isTask && functionType->GetReturnType()->IsVoidType() == false) Error(pos, "Task-qualified functions must have void return type."); if (g->target->isGenXTarget() && Type::Equal(functionType->GetReturnType(), AtomicType::Void) == false && functionType->isExported) { // TODO_GEN: According to CM requirements kernel should have void type. It is strong restriction to ISPC // language so we would need to think more about it in the future. Error(pos, "Export-qualified functions must have void return type with \"genx\" target."); } if (functionType->isExported || functionType->isExternC || (g->target->isGenXTarget() && functionType->isTask)) { lCheckForStructParameters(functionType, pos); } // Loop over all of the arguments; process default values if present // and do other checks and parameter attribute setting. bool seenDefaultArg = false; int nArgs = functionType->GetNumParameters(); for (int i = 0; i < nArgs; ++i) { const Type *argType = functionType->GetParameterType(i); const std::string &argName = functionType->GetParameterName(i); Expr *defaultValue = functionType->GetParameterDefault(i); const SourcePos &argPos = functionType->GetParameterSourcePos(i); // If the function is exported or in case of gen target is task, make sure that the parameter // doesn't have any funky stuff going on in it. // JCB nomosoa - Varying is now a-ok. if (functionType->isExported) lCheckExportedParameterTypes(argType, argName, argPos); #ifdef ISPC_GENX_ENABLED if (g->target->isGenXTarget() && functionType->isTask) lCheckTaskParameterTypes(argType, argName, argPos); #endif // ISPC assumes that no pointers alias. (It should be possible to // specify when this is not the case, but this should be the // default.) Set parameter attributes accordingly. (Only for // uniform pointers, since varying pointers are int vectors...) if (!functionType->isTask && ((CastType<PointerType>(argType) != NULL && argType->IsUniformType() && // Exclude SOA argument because it is a pair {struct *, int} // instead of pointer !CastType<PointerType>(argType)->IsSlice()) || CastType<ReferenceType>(argType) != NULL)) { function->addParamAttr(i, llvm::Attribute::NoAlias); #if 0 int align = 4 * RoundUpPow2(g->target->nativeVectorWidth); function->addAttribute(i+1, llvm::Attribute::constructAlignmentFromInt(align)); #endif } if (symbolTable->LookupFunction(argName.c_str())) Warning(argPos, "Function parameter \"%s\" shadows a function " "declared in global scope.", argName.c_str()); if (defaultValue != NULL) seenDefaultArg = true; else if (seenDefaultArg) { // Once one parameter has provided a default value, then all of // the following ones must have them as well. Error(argPos, "Parameter \"%s\" is missing default: all " "parameters after the first parameter with a default value " "must have default values as well.", argName.c_str()); } } // If llvm gave us back a Function * with a different name than the one // we asked for, then there's already a function with that same // (mangled) name in the llvm::Module. In that case, erase the one we // tried to add and just work with the one it already had. if (function->getName() != functionName) { function->eraseFromParent(); function = module->getFunction(functionName); } // Finally, we know all is good and we can add the function to the // symbol table Symbol *funSym = new Symbol(name, pos, functionType, storageClass); funSym->function = function; bool ok = symbolTable->AddFunction(funSym); Assert(ok); } void Module::AddFunctionDefinition(const std::string &name, const FunctionType *type, Stmt *code) { Symbol *sym = symbolTable->LookupFunction(name.c_str(), type); if (sym == NULL || code == NULL) { Assert(m->errorCount > 0); return; } sym->pos = code->pos; // FIXME: because we encode the parameter names in the function type, // we need to override the function type here in case the function had // earlier been declared with anonymous parameter names but is now // defined with actual names. This is yet another reason we shouldn't // include the names in FunctionType... sym->type = type; ast->AddFunction(sym, code); } void Module::AddExportedTypes(const std::vector<std::pair<const Type *, SourcePos>> &types) { for (int i = 0; i < (int)types.size(); ++i) { if (CastType<StructType>(types[i].first) == NULL && CastType<VectorType>(types[i].first) == NULL && CastType<EnumType>(types[i].first) == NULL) Error(types[i].second, "Only struct, vector, and enum types, " "not \"%s\", are allowed in type export lists.", types[i].first->GetString().c_str()); else exportedTypes.push_back(types[i]); } } bool Module::writeOutput(OutputType outputType, OutputFlags flags, const char *outFileName, const char *depTargetFileName, const char *sourceFileName, DispatchHeaderInfo *DHI) { if (diBuilder && (outputType != Header) && (outputType != Deps)) lStripUnusedDebugInfo(module); Assert(module); // In LLVM_3_4 after r195494 and r195504 revisions we should pass // "Debug Info Version" constant to the module. LLVM will ignore // our Debug Info metadata without it. if (g->generateDebuggingSymbols == true) { // For GenX target: when we link with CM, "Dwarf version" and "Debug info version" is already set // so we don't need to do this here. Otherwise VerifyModule will be broken. if (!g->target->isGenXTarget()) { module->addModuleFlag(llvm::Module::Warning, "Debug Info Version", llvm::DEBUG_METADATA_VERSION); } } // SIC! (verifyModule() == TRUE) means "failed", see llvm-link code. if ((outputType != Header) && (outputType != Deps) && (outputType != HostStub) && (outputType != DevStub) && llvm::verifyModule(*module)) { FATAL("Resulting module verification failed!"); } if (outFileName) { // First, issue a warning if the output file suffix and the type of // file being created seem to mismatch. This can help catch missing // command-line arguments specifying the output file type. const char *suffix = strrchr(outFileName, '.'); if (suffix != NULL) { ++suffix; const char *fileType = NULL; switch (outputType) { case Asm: if (strcasecmp(suffix, "s")) fileType = "assembly"; break; case Bitcode: if (strcasecmp(suffix, "bc")) fileType = "LLVM bitcode"; break; case BitcodeText: if (strcasecmp(suffix, "ll")) fileType = "LLVM assembly"; break; case Object: if (strcasecmp(suffix, "o") && strcasecmp(suffix, "obj")) fileType = "object"; break; #ifdef ISPC_GENX_ENABLED case ZEBIN: if (strcasecmp(suffix, "bin")) fileType = "L0 binary"; break; case SPIRV: if (strcasecmp(suffix, "spv")) fileType = "spir-v"; break; #endif case Header: if (strcasecmp(suffix, "h") && strcasecmp(suffix, "hh") && strcasecmp(suffix, "hpp")) fileType = "header"; break; case Deps: break; case DevStub: if (strcasecmp(suffix, "c") && strcasecmp(suffix, "cc") && strcasecmp(suffix, "c++") && strcasecmp(suffix, "cxx") && strcasecmp(suffix, "cpp")) fileType = "dev-side offload stub"; break; case HostStub: if (strcasecmp(suffix, "c") && strcasecmp(suffix, "cc") && strcasecmp(suffix, "c++") && strcasecmp(suffix, "cxx") && strcasecmp(suffix, "cpp")) fileType = "host-side offload stub"; break; default: Assert(0 /* swtich case not handled */); return 1; } if (fileType != NULL) Warning(SourcePos(), "Emitting %s file, but filename \"%s\" " "has suffix \"%s\"?", fileType, outFileName, suffix); } } if (outputType == Header) { if (DHI) return writeDispatchHeader(DHI); else return writeHeader(outFileName); } else if (outputType == Deps) return writeDeps(outFileName, 0 != (flags & GenerateMakeRuleForDeps), depTargetFileName, sourceFileName); else if (outputType == HostStub) return writeHostStub(outFileName); else if (outputType == DevStub) return writeDevStub(outFileName); else if ((outputType == Bitcode) || (outputType == BitcodeText)) return writeBitcode(module, outFileName, outputType); #ifdef ISPC_GENX_ENABLED else if (outputType == SPIRV) return writeSPIRV(module, outFileName); else if (outputType == ZEBIN) return writeZEBin(module, outFileName); #endif else return writeObjectFileOrAssembly(outputType, outFileName); } bool Module::writeBitcode(llvm::Module *module, const char *outFileName, OutputType outputType) { // Get a file descriptor corresponding to where we want the output to // go. If we open it, it'll be closed by the llvm::raw_fd_ostream // destructor. int fd; if (!strcmp(outFileName, "-")) fd = 1; // stdout else { int flags = O_CREAT | O_WRONLY | O_TRUNC; #ifdef ISPC_HOST_IS_WINDOWS flags |= O_BINARY; fd = _open(outFileName, flags, 0644); #else fd = open(outFileName, flags, 0644); #endif // ISPC_HOST_IS_WINDOWS if (fd == -1) { perror(outFileName); return false; } } llvm::raw_fd_ostream fos(fd, (fd != 1), false); if (outputType == Bitcode) llvm::WriteBitcodeToFile(*module, fos); else if (outputType == BitcodeText) module->print(fos, nullptr); return true; } #ifdef ISPC_GENX_ENABLED bool Module::translateToSPIRV(llvm::Module *module, std::stringstream &ss) { std::string err; SPIRV::TranslatorOpts Opts; Opts.enableAllExtensions(); // Pass this option to open source SPIR-V translator. // This option will break internal version of SPIR-V translator. llvm::cl::opt<bool> SPIRVAllowUnknownIntrinsics( "spirv-allow-unknown-intrinsics", llvm::cl::init(true), llvm::cl::desc("Unknown LLVM intrinsics will be translated as external function " "calls in SPIR-V")); llvm::cl::opt<bool> SPIRVAllowExtraDIExpressions( "spirv-allow-extra-diexpressions", llvm::cl::init(true), llvm::cl::desc("Allow DWARF operations not listed in the OpenCL.DebugInfo.100 " "specification (experimental, may produce incompatible SPIR-V " "module)")); Opts.setSPIRVAllowUnknownIntrinsicsEnabled(SPIRVAllowUnknownIntrinsics); Opts.setAllowExtraDIExpressionsEnabled(SPIRVAllowExtraDIExpressions); Opts.setDesiredBIsRepresentation(SPIRV::BIsRepresentation::SPIRVFriendlyIR); Opts.setDebugInfoEIS(SPIRV::DebugInfoEIS::OpenCL_DebugInfo_100); bool success = llvm::writeSpirv(module, Opts, ss, err); if (!success) { fprintf(stderr, "Fails to save LLVM as SPIR-V: %s \n", err.c_str()); return false; } return true; } bool Module::writeSPIRV(llvm::Module *module, const char *outFileName) { std::stringstream translatedStream; bool success = translateToSPIRV(module, translatedStream); if (!success) { return false; } if (!strcmp(outFileName, "-")) { std::cout << translatedStream.rdbuf(); } else { std::ofstream fos(outFileName, std::ios::binary); fos << translatedStream.rdbuf(); } return true; } // Translate ISPC CPU name to Neo representation static std::string translateCPU(const std::string &CPU) { auto It = ISPCToNeoCPU.find(CPU); Assert(It != ISPCToNeoCPU.end() && "Unexpected CPU"); return It->second; } // Copy outputs. Required file should have provided extension (it is // different for different binary kinds). static void saveOutput(uint32_t numOutputs, uint8_t **dataOutputs, uint64_t *lenOutputs, char **nameOutputs, std::vector<char> &oclocRes) { const std::string &requiredExtension = ".bin"; llvm::ArrayRef<const uint8_t *> outBins{dataOutputs, numOutputs}; llvm::ArrayRef<uint64_t> outLens{lenOutputs, numOutputs}; llvm::ArrayRef<const char *> outNames{nameOutputs, numOutputs}; auto zip = llvm::zip(outBins, outLens, outNames); using ZipTy = typename decltype(zip)::value_type; auto binIt = std::find_if(zip.begin(), zip.end(), [&requiredExtension](ZipTy File) { llvm::StringRef name{std::get<2>(File)}; return name.endswith(requiredExtension); }); Assert(binIt != zip.end() && "Output binary is missing"); llvm::ArrayRef<uint8_t> binRef{std::get<0>(*binIt), static_cast<std::size_t>(std::get<1>(*binIt))}; oclocRes.assign(binRef.begin(), binRef.end()); } bool Module::writeZEBin(llvm::Module *module, const char *outFileName) { std::stringstream translatedStream; bool success = translateToSPIRV(module, translatedStream); if (!success) { return false; } const std::string &translatedStr = translatedStream.str(); std::vector<char> spirStr(translatedStr.begin(), translatedStr.end()); const std::string CPUName = g->target->getCPU(); const std::string neoCPU = translateCPU(CPUName); invokePtr invoke; freeOutputPtr freeOutput; auto oclocLib = llvm::sys::DynamicLibrary::getPermanentLibrary(OCLOC_LIBRARY_NAME); if (!oclocLib.isValid()) { Error(SourcePos(), "Cannot open '" OCLOC_LIBRARY_NAME "'\n"); return false; } invoke = reinterpret_cast<invokePtr>(oclocLib.getAddressOfSymbol("oclocInvoke")); if (!invoke) { Error(SourcePos(), "oclocInvoke symbol is missing \n"); return false; } freeOutput = reinterpret_cast<freeOutputPtr>(oclocLib.getAddressOfSymbol("oclocFreeOutput")); if (!freeOutput) { Error(SourcePos(), "oclocFreeOutput symbol is missing \n"); return false; } std::string options{"-vc-codegen -no-optimize"}; // Add debug option to VC backend of "-g" is set to ISPC if (g->generateDebuggingSymbols) { options.append(" -g"); } if (g->vcOpts != "") { options.append(" " + g->vcOpts); } std::string internalOptions; // Use L0 binary internalOptions.append(" -binary-format=").append("ze"); const char *spvFileName = "ispc_spirv"; std::vector<const char *> oclocArgs; oclocArgs.push_back("ocloc"); oclocArgs.push_back("compile"); oclocArgs.push_back("-device"); oclocArgs.push_back(neoCPU.c_str()); oclocArgs.push_back("-spirv_input"); oclocArgs.push_back("-file"); oclocArgs.push_back(spvFileName); oclocArgs.push_back("-options"); oclocArgs.push_back(options.c_str()); oclocArgs.push_back("-internal_options"); oclocArgs.push_back(internalOptions.c_str()); uint32_t numOutputs = 0; uint8_t **dataOutputs = nullptr; uint64_t *lenOutputs = nullptr; char **nameOutputs = nullptr; static_assert(alignof(uint8_t) == alignof(char), "Possible unaligned access"); auto *spvSource = reinterpret_cast<const uint8_t *>(spirStr.data()); const uint64_t spvLen = spirStr.size(); if (invoke(oclocArgs.size(), oclocArgs.data(), 1, &spvSource, &spvLen, &spvFileName, 0, nullptr, nullptr, nullptr, &numOutputs, &dataOutputs, &lenOutputs, &nameOutputs)) { Error(SourcePos(), "Call to oclocInvoke failed \n"); return false; } std::vector<char> oclocRes; saveOutput(numOutputs, dataOutputs, lenOutputs, nameOutputs, oclocRes); if (freeOutput(&numOutputs, &dataOutputs, &lenOutputs, &nameOutputs)) { Error(SourcePos(), "Call to oclocFreeOutput failed \n"); return false; } if (!strcmp(outFileName, "-")) { std::cout.write(oclocRes.data(), oclocRes.size()); } else { std::ofstream fos(outFileName, std::ios::binary); fos.write(oclocRes.data(), oclocRes.size()); } return true; } #endif // ISPC_GENX_ENABLED bool Module::writeObjectFileOrAssembly(OutputType outputType, const char *outFileName) { llvm::TargetMachine *targetMachine = g->target->GetTargetMachine(); return writeObjectFileOrAssembly(targetMachine, module, outputType, outFileName); } bool Module::writeObjectFileOrAssembly(llvm::TargetMachine *targetMachine, llvm::Module *module, OutputType outputType, const char *outFileName) { // Figure out if we're generating object file or assembly output, and // set binary output for object files llvm::CodeGenFileType fileType = (outputType == Object) ? llvm::CGFT_ObjectFile : llvm::CGFT_AssemblyFile; bool binary = (fileType == llvm::CGFT_ObjectFile); llvm::sys::fs::OpenFlags flags = binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text; std::error_code error; std::unique_ptr<llvm::ToolOutputFile> of(new llvm::ToolOutputFile(outFileName, error, flags)); if (error) { Error(SourcePos(), "Cannot open output file \"%s\".\n", outFileName); return false; } llvm::legacy::PassManager pm; { llvm::raw_fd_ostream &fos(of->os()); // Third parameter is for generation of .dwo file, which is separate DWARF // file for ELF targets. We don't support it currently. if (targetMachine->addPassesToEmitFile(pm, fos, nullptr, fileType)) { FATAL("Failed to add passes to emit object file!"); } // Finally, run the passes to emit the object file/assembly pm.run(*module); // Success; tell tool_output_file to keep the final output file. of->keep(); } return true; } /** Given a pointer to an element of a structure, see if it is a struct type or an array of a struct type. If so, return a pointer to the underlying struct type. */ static const StructType *lGetElementStructType(const Type *t) { const StructType *st = CastType<StructType>(t); if (st != NULL) return st; const ArrayType *at = CastType<ArrayType>(t); if (at != NULL) return lGetElementStructType(at->GetElementType()); return NULL; } static bool lContainsPtrToVarying(const StructType *st) { int numElts = st->GetElementCount(); for (int j = 0; j < numElts; ++j) { const Type *t = st->GetElementType(j); if (t->IsVaryingType()) return true; } return false; } /** Emits a declaration for the given struct to the given file. This function first makes sure that declarations for any structs that are (recursively) members of this struct are emitted first. */ static void lEmitStructDecl(const StructType *st, std::vector<const StructType *> *emittedStructs, FILE *file, bool emitUnifs = true) { // if we're emitting this for a generic dispatch header file and it's // struct that only contains uniforms, don't bother if we're emitting uniforms if (!emitUnifs && !lContainsPtrToVarying(st)) { return; } // Has this struct type already been declared? (This happens if it's a // member of another struct for which we emitted a declaration // previously.) for (int i = 0; i < (int)emittedStructs->size(); ++i) if (Type::EqualIgnoringConst(st, (*emittedStructs)[i])) return; // Otherwise first make sure any contained structs have been declared. for (int i = 0; i < st->GetElementCount(); ++i) { const StructType *elementStructType = lGetElementStructType(st->GetElementType(i)); if (elementStructType != NULL) lEmitStructDecl(elementStructType, emittedStructs, file, emitUnifs); } // And now it's safe to declare this one emittedStructs->push_back(st); fprintf(file, "#ifndef __ISPC_STRUCT_%s__\n", st->GetCStructName().c_str()); fprintf(file, "#define __ISPC_STRUCT_%s__\n", st->GetCStructName().c_str()); char sSOA[48]; bool pack, needsAlign = false; llvm::Type *stype = st->LLVMType(g->ctx); const llvm::DataLayout *DL = g->target->getDataLayout(); if (!(pack = llvm::dyn_cast<llvm::StructType>(stype)->isPacked())) for (int i = 0; !needsAlign && (i < st->GetElementCount()); ++i) { const Type *ftype = st->GetElementType(i)->GetAsNonConstType(); needsAlign |= ftype->IsVaryingType() && (CastType<StructType>(ftype) == NULL); } if (st->GetSOAWidth() > 0) // This has to match the naming scheme in // StructType::GetCDeclaration(). snprintf(sSOA, sizeof(sSOA), "_SOA%d", st->GetSOAWidth()); else *sSOA = '\0'; if (!needsAlign) fprintf(file, "%sstruct %s%s {\n", (pack) ? "packed " : "", st->GetCStructName().c_str(), sSOA); else { unsigned uABI = DL->getABITypeAlignment(stype); fprintf(file, "__ISPC_ALIGNED_STRUCT__(%u) %s%s {\n", uABI, st->GetCStructName().c_str(), sSOA); } for (int i = 0; i < st->GetElementCount(); ++i) { const Type *ftype = st->GetElementType(i)->GetAsNonConstType(); std::string d = ftype->GetCDeclaration(st->GetElementName(i)); fprintf(file, " "); if (needsAlign && ftype->IsVaryingType() && (CastType<StructType>(ftype) == NULL)) { unsigned uABI = DL->getABITypeAlignment(ftype->LLVMType(g->ctx)); fprintf(file, "__ISPC_ALIGN__(%u) ", uABI); } // Don't expand arrays, pointers and structures: // their insides will be expanded automatically. if (!ftype->IsArrayType() && !ftype->IsPointerType() && ftype->IsVaryingType() && (CastType<StructType>(ftype) == NULL)) { fprintf(file, "%s[%d];\n", d.c_str(), g->target->getVectorWidth()); } else { fprintf(file, "%s;\n", d.c_str()); } } fprintf(file, "};\n"); fprintf(file, "#endif\n\n"); } /** Given a set of structures that we want to print C declarations of in a header file, emit their declarations. */ static void lEmitStructDecls(std::vector<const StructType *> &structTypes, FILE *file, bool emitUnifs = true) { std::vector<const StructType *> emittedStructs; fprintf(file, "\n#ifndef __ISPC_ALIGN__\n" "#if defined(__clang__) || !defined(_MSC_VER)\n" "// Clang, GCC, ICC\n" "#define __ISPC_ALIGN__(s) __attribute__((aligned(s)))\n" "#define __ISPC_ALIGNED_STRUCT__(s) struct __ISPC_ALIGN__(s)\n" "#else\n" "// Visual Studio\n" "#define __ISPC_ALIGN__(s) __declspec(align(s))\n" "#define __ISPC_ALIGNED_STRUCT__(s) __ISPC_ALIGN__(s) struct\n" "#endif\n" "#endif\n\n"); for (unsigned int i = 0; i < structTypes.size(); ++i) lEmitStructDecl(structTypes[i], &emittedStructs, file, emitUnifs); } /** Emit C declarations of enumerator types to the generated header file. */ static void lEmitEnumDecls(const std::vector<const EnumType *> &enumTypes, FILE *file) { if (enumTypes.size() == 0) return; fprintf(file, "///////////////////////////////////////////////////////////////////////////\n"); fprintf(file, "// Enumerator types with external visibility from ispc code\n"); fprintf(file, "///////////////////////////////////////////////////////////////////////////\n\n"); for (unsigned int i = 0; i < enumTypes.size(); ++i) { fprintf(file, "#ifndef __ISPC_ENUM_%s__\n", enumTypes[i]->GetEnumName().c_str()); fprintf(file, "#define __ISPC_ENUM_%s__\n", enumTypes[i]->GetEnumName().c_str()); std::string declaration = enumTypes[i]->GetCDeclaration(""); fprintf(file, "%s {\n", declaration.c_str()); // Print the individual enumerators for (int j = 0; j < enumTypes[i]->GetEnumeratorCount(); ++j) { const Symbol *e = enumTypes[i]->GetEnumerator(j); Assert(e->constValue != NULL); unsigned int enumValue; int count = e->constValue->GetValues(&enumValue); Assert(count == 1); // Always print an initializer to set the value. We could be // 'clever' here and detect whether the implicit value given by // one plus the previous enumerator value (or zero, for the // first enumerator) is the same as the value stored with the // enumerator, though that doesn't seem worth the trouble... fprintf(file, " %s = %d%c\n", e->name.c_str(), enumValue, (j < enumTypes[i]->GetEnumeratorCount() - 1) ? ',' : ' '); } fprintf(file, "};\n"); fprintf(file, "#endif\n\n"); } } /** Print declarations of VectorTypes used in 'export'ed parts of the program in the header file. */ static void lEmitVectorTypedefs(const std::vector<const VectorType *> &types, FILE *file) { if (types.size() == 0) return; fprintf(file, "///////////////////////////////////////////////////////////////////////////\n"); fprintf(file, "// Vector types with external visibility from ispc code\n"); fprintf(file, "///////////////////////////////////////////////////////////////////////////\n\n"); for (unsigned int i = 0; i < types.size(); ++i) { std::string baseDecl; const VectorType *vt = types[i]->GetAsNonConstType(); if (!vt->IsUniformType()) // Varying stuff shouldn't be visibile to / used by the // application, so at least make it not simple to access it by // not declaring the type here... continue; int size = vt->GetElementCount(); llvm::Type *ty = vt->LLVMType(g->ctx); int align = g->target->getDataLayout()->getABITypeAlignment(ty); baseDecl = vt->GetBaseType()->GetCDeclaration(""); fprintf(file, "#ifndef __ISPC_VECTOR_%s%d__\n", baseDecl.c_str(), size); fprintf(file, "#define __ISPC_VECTOR_%s%d__\n", baseDecl.c_str(), size); fprintf(file, "#ifdef _MSC_VER\n__declspec( align(%d) ) ", align); fprintf(file, "struct %s%d { %s v[%d]; };\n", baseDecl.c_str(), size, baseDecl.c_str(), size); fprintf(file, "#else\n"); fprintf(file, "struct %s%d { %s v[%d]; } __attribute__ ((aligned(%d)));\n", baseDecl.c_str(), size, baseDecl.c_str(), size, align); fprintf(file, "#endif\n"); fprintf(file, "#endif\n\n"); } fprintf(file, "\n"); } /** Add the given type to the vector, if that type isn't already in there. */ template <typename T> static void lAddTypeIfNew(const Type *type, std::vector<const T *> *exportedTypes) { type = type->GetAsNonConstType(); // Linear search, so this ends up being n^2. It's unlikely this will // matter in practice, though. for (unsigned int i = 0; i < exportedTypes->size(); ++i) if (Type::Equal((*exportedTypes)[i], type)) return; const T *castType = CastType<T>(type); Assert(castType != NULL); exportedTypes->push_back(castType); } /** Given an arbitrary type that appears in the app/ispc interface, add it to an appropriate vector if it is a struct, enum, or short vector type. Then, if it's a struct, recursively process its members to do the same. */ static void lGetExportedTypes(const Type *type, std::vector<const StructType *> *exportedStructTypes, std::vector<const EnumType *> *exportedEnumTypes, std::vector<const VectorType *> *exportedVectorTypes) { const ArrayType *arrayType = CastType<ArrayType>(type); const StructType *structType = CastType<StructType>(type); const FunctionType *ftype = CastType<FunctionType>(type); if (CastType<ReferenceType>(type) != NULL) lGetExportedTypes(type->GetReferenceTarget(), exportedStructTypes, exportedEnumTypes, exportedVectorTypes); else if (CastType<PointerType>(type) != NULL) lGetExportedTypes(type->GetBaseType(), exportedStructTypes, exportedEnumTypes, exportedVectorTypes); else if (arrayType != NULL) lGetExportedTypes(arrayType->GetElementType(), exportedStructTypes, exportedEnumTypes, exportedVectorTypes); else if (structType != NULL) { lAddTypeIfNew(type, exportedStructTypes); for (int i = 0; i < structType->GetElementCount(); ++i) lGetExportedTypes(structType->GetElementType(i), exportedStructTypes, exportedEnumTypes, exportedVectorTypes); } else if (CastType<UndefinedStructType>(type) != NULL) // do nothing ; else if (CastType<EnumType>(type) != NULL) lAddTypeIfNew(type, exportedEnumTypes); else if (CastType<VectorType>(type) != NULL) lAddTypeIfNew(type, exportedVectorTypes); else if (ftype != NULL) { // Handle Return Types lGetExportedTypes(ftype->GetReturnType(), exportedStructTypes, exportedEnumTypes, exportedVectorTypes); // And now the parameter types... for (int j = 0; j < ftype->GetNumParameters(); ++j) lGetExportedTypes(ftype->GetParameterType(j), exportedStructTypes, exportedEnumTypes, exportedVectorTypes); } else Assert(CastType<AtomicType>(type) != NULL); } /** Given a set of functions, return the set of structure and vector types present in the parameters to them. */ static void lGetExportedParamTypes(const std::vector<Symbol *> &funcs, std::vector<const StructType *> *exportedStructTypes, std::vector<const EnumType *> *exportedEnumTypes, std::vector<const VectorType *> *exportedVectorTypes) { for (unsigned int i = 0; i < funcs.size(); ++i) { const FunctionType *ftype = CastType<FunctionType>(funcs[i]->type); Assert(ftype != NULL); // Handle the return type lGetExportedTypes(ftype->GetReturnType(), exportedStructTypes, exportedEnumTypes, exportedVectorTypes); // And now the parameter types... for (int j = 0; j < ftype->GetNumParameters(); ++j) { lGetExportedTypes(ftype->GetParameterType(j), exportedStructTypes, exportedEnumTypes, exportedVectorTypes); } } } static void lPrintFunctionDeclarations(FILE *file, const std::vector<Symbol *> &funcs, bool useExternC = 1, bool rewriteForDispatch = false) { if (useExternC) fprintf(file, "#if defined(__cplusplus) && (! defined(__ISPC_NO_EXTERN_C) || !__ISPC_NO_EXTERN_C )\nextern " "\"C\" {\n#endif // __cplusplus\n"); // fprintf(file, "#ifdef __cplusplus\nextern \"C\" {\n#endif // __cplusplus\n"); for (unsigned int i = 0; i < funcs.size(); ++i) { const FunctionType *ftype = CastType<FunctionType>(funcs[i]->type); Assert(ftype); std::string decl; std::string fname = funcs[i]->name; if (g->calling_conv == CallingConv::x86_vectorcall) { fname = "__vectorcall " + fname; } if (rewriteForDispatch) { decl = ftype->GetCDeclarationForDispatch(fname); } else { decl = ftype->GetCDeclaration(fname); } fprintf(file, " extern %s;\n", decl.c_str()); } if (useExternC) fprintf(file, "#if defined(__cplusplus) && (! defined(__ISPC_NO_EXTERN_C) || !__ISPC_NO_EXTERN_C )\n} /* end " "extern C */\n#endif // __cplusplus\n"); // fprintf(file, "#ifdef __cplusplus\n} /* end extern C */\n#endif // __cplusplus\n"); } static bool lIsExported(const Symbol *sym) { const FunctionType *ft = CastType<FunctionType>(sym->type); Assert(ft); return ft->isExported; } static bool lIsExternC(const Symbol *sym) { const FunctionType *ft = CastType<FunctionType>(sym->type); Assert(ft); return ft->isExternC; } static void lUnescapeStringInPlace(std::string &str) { // There are many more escape sequences, but since this is a path, // we can get away with only supporting the basic ones (i.e. no // octal, hexadecimal or unicode values). for (std::string::iterator it = str.begin(); it != str.end(); ++it) { size_t pos = it - str.begin(); std::string::iterator next = it + 1; if (*it == '\\' && next != str.end()) { switch (*next) { #define UNESCAPE_SEQ(c, esc) \ case c: \ *it = esc; \ str.erase(next); \ it = str.begin() + pos; \ break UNESCAPE_SEQ('\'', '\''); UNESCAPE_SEQ('?', '?'); UNESCAPE_SEQ('\\', '\\'); UNESCAPE_SEQ('a', '\a'); UNESCAPE_SEQ('b', '\b'); UNESCAPE_SEQ('f', '\f'); UNESCAPE_SEQ('n', '\n'); UNESCAPE_SEQ('r', '\r'); UNESCAPE_SEQ('t', '\t'); UNESCAPE_SEQ('v', '\v'); #undef UNESCAPE_SEQ } } } } bool Module::writeDeps(const char *fn, bool generateMakeRule, const char *tn, const char *sn) { if (fn && g->debugPrint) { // We may be passed nullptr for stdout output. printf("\nWriting dependencies to file %s\n", fn); } FILE *file = fn ? fopen(fn, "w") : stdout; if (!file) { perror("fopen"); return false; } if (generateMakeRule) { Assert(tn); fprintf(file, "%s:", tn); // Rules always emit source first. if (sn && !IsStdin(sn)) { fprintf(file, " %s", sn); } std::string unescaped; for (std::set<std::string>::const_iterator it = registeredDependencies.begin(); it != registeredDependencies.end(); ++it) { unescaped = *it; // As this is preprocessor output, paths come escaped. lUnescapeStringInPlace(unescaped); if (sn && !IsStdin(sn) && 0 == strcmp(sn, unescaped.c_str())) // If source has been passed, it's already emitted. continue; fprintf(file, " \\\n"); fprintf(file, " %s", unescaped.c_str()); } fprintf(file, "\n"); } else { for (std::set<std::string>::const_iterator it = registeredDependencies.begin(); it != registeredDependencies.end(); ++it) fprintf(file, "%s\n", it->c_str()); } fclose(file); return true; } std::string emitOffloadParamStruct(const std::string &paramStructName, const Symbol *sym, const FunctionType *fct) { std::stringstream out; out << "struct " << paramStructName << " {" << std::endl; for (int i = 0; i < fct->GetNumParameters(); i++) { const Type *orgParamType = fct->GetParameterType(i); if (orgParamType->IsPointerType() || orgParamType->IsArrayType()) { /* we're passing pointers separately -- no pointers in that struct... */ continue; } // const reference parameters can be passed as copies. const Type *paramType; if (orgParamType->IsReferenceType()) { if (!orgParamType->IsConstType()) { Error(sym->pos, "When emitting offload-stubs, \"export\"ed functions cannot have non-const " "reference-type parameters.\n"); } const ReferenceType *refType = static_cast<const ReferenceType *>(orgParamType); paramType = refType->GetReferenceTarget()->GetAsNonConstType(); } else { paramType = orgParamType->GetAsNonConstType(); } std::string paramName = fct->GetParameterName(i); std::string paramTypeName = paramType->GetString(); std::string tmpArgDecl = paramType->GetCDeclaration(paramName); out << " " << tmpArgDecl << ";" << std::endl; } out << "};" << std::endl; return out.str(); } bool Module::writeDevStub(const char *fn) { FILE *file = fopen(fn, "w"); if (!file) { perror("fopen"); return false; } fprintf(file, "//\n// %s\n// (device stubs automatically generated by the ispc compiler.)\n", fn); fprintf(file, "// DO NOT EDIT THIS FILE.\n//\n\n"); fprintf(file, "#include \"ispc/dev/offload.h\"\n\n"); fprintf(file, "#include <stdint.h>\n\n"); // Collect single linear arrays of the *exported* functions (we'll // treat those as "__kernel"s in IVL -- "extern" functions will only // be used for dev-dev function calls; only "export" functions will // get exported to the host std::vector<Symbol *> exportedFuncs; m->symbolTable->GetMatchingFunctions(lIsExported, &exportedFuncs); // Get all of the struct, vector, and enumerant types used as function // parameters. These vectors may have repeats. std::vector<const StructType *> exportedStructTypes; std::vector<const EnumType *> exportedEnumTypes; std::vector<const VectorType *> exportedVectorTypes; lGetExportedParamTypes(exportedFuncs, &exportedStructTypes, &exportedEnumTypes, &exportedVectorTypes); // And print them lEmitVectorTypedefs(exportedVectorTypes, file); lEmitEnumDecls(exportedEnumTypes, file); lEmitStructDecls(exportedStructTypes, file); fprintf(file, "#ifdef __cplusplus\n"); fprintf(file, "namespace ispc {\n"); fprintf(file, "#endif // __cplusplus\n"); fprintf(file, "\n"); fprintf(file, "///////////////////////////////////////////////////////////////////////////\n"); fprintf(file, "// Functions exported from ispc code\n"); fprintf(file, "// (so the dev stub knows what to call)\n"); fprintf(file, "///////////////////////////////////////////////////////////////////////////\n"); lPrintFunctionDeclarations(file, exportedFuncs, true); fprintf(file, "#ifdef __cplusplus\n"); fprintf(file, "}/* end namespace */\n"); fprintf(file, "#endif // __cplusplus\n"); fprintf(file, "\n"); fprintf(file, "///////////////////////////////////////////////////////////////////////////\n"); fprintf(file, "// actual dev stubs\n"); fprintf(file, "///////////////////////////////////////////////////////////////////////////\n"); fprintf(file, "// note(iw): due to some linking issues offload stubs *only* work under C++\n"); fprintf(file, "extern \"C\" {\n\n"); for (unsigned int i = 0; i < exportedFuncs.size(); ++i) { const Symbol *sym = exportedFuncs[i]; Assert(sym); const FunctionType *fct = CastType<FunctionType>(sym->type); Assert(fct); if (!fct->GetReturnType()->IsVoidType()) { // Error(sym->pos,"When emitting offload-stubs, \"export\"ed functions cannot have non-void return // types.\n"); Warning(sym->pos, "When emitting offload-stubs, ignoring \"export\"ed function with non-void return types.\n"); continue; } // ------------------------------------------------------- // first, emit a struct that holds the parameters // ------------------------------------------------------- std::string paramStructName = std::string("__ispc_dev_stub_") + sym->name; std::string paramStruct = emitOffloadParamStruct(paramStructName, sym, fct); fprintf(file, "%s\n", paramStruct.c_str()); // ------------------------------------------------------- // then, emit a fct stub that unpacks the parameters and pointers // ------------------------------------------------------- fprintf(file, "void __ispc_dev_stub_%s(\n" " uint32_t in_BufferCount,\n" " void** in_ppBufferPointers,\n" " uint64_t* in_pBufferLengths,\n" " void* in_pMiscData,\n" " uint16_t in_MiscDataLength,\n" " void* in_pReturnValue,\n" " uint16_t in_ReturnValueLength)\n", sym->name.c_str()); fprintf(file, "{\n"); fprintf(file, " struct %s args;\n memcpy(&args,in_pMiscData,sizeof(args));\n", paramStructName.c_str()); std::stringstream funcall; funcall << "ispc::" << sym->name << "("; for (int i = 0; i < fct->GetNumParameters(); i++) { // get param type and make it non-const, so we can write while unpacking // const Type *paramType = fct->GetParameterType(i)->GetAsNonConstType(); const Type *paramType; // = fct->GetParameterType(i)->GetAsNonConstType(); const Type *orgParamType = fct->GetParameterType(i); if (orgParamType->IsReferenceType()) { if (!orgParamType->IsConstType()) { Error(sym->pos, "When emitting offload-stubs, \"export\"ed functions cannot have non-const " "reference-type parameters.\n"); } const ReferenceType *refType = static_cast<const ReferenceType *>(orgParamType); paramType = refType->GetReferenceTarget()->GetAsNonConstType(); } else { paramType = orgParamType->GetAsNonConstType(); } std::string paramName = fct->GetParameterName(i); std::string paramTypeName = paramType->GetString(); if (i) funcall << ", "; std::string tmpArgName = std::string("_") + paramName; if (paramType->IsPointerType() || paramType->IsArrayType()) { std::string tmpArgDecl = paramType->GetCDeclaration(tmpArgName); fprintf(file, " %s;\n", tmpArgDecl.c_str()); fprintf(file, " (void *&)%s = ispc_dev_translate_pointer(*in_ppBufferPointers++);\n", tmpArgName.c_str()); funcall << tmpArgName; } else { funcall << "args." << paramName; } } funcall << ");"; fprintf(file, " %s\n", funcall.str().c_str()); fprintf(file, "}\n\n"); } // end extern "C" fprintf(file, "}/* end extern C */\n"); fclose(file); return true; } bool Module::writeHostStub(const char *fn) { FILE *file = fopen(fn, "w"); if (!file) { perror("fopen"); return false; } fprintf(file, "//\n// %s\n// (device stubs automatically generated by the ispc compiler.)\n", fn); fprintf(file, "// DO NOT EDIT THIS FILE.\n//\n\n"); fprintf(file, "#include \"ispc/host/offload.h\"\n\n"); fprintf( file, "// note(iw): Host stubs do not get extern C linkage -- dev-side already uses that for the same symbols.\n\n"); // fprintf(file,"#ifdef __cplusplus\nextern \"C\" {\n#endif // __cplusplus\n"); fprintf(file, "#ifdef __cplusplus\nnamespace ispc {\n#endif // __cplusplus\n\n"); // Collect single linear arrays of the *exported* functions (we'll // treat those as "__kernel"s in IVL -- "extern" functions will only // be used for dev-dev function calls; only "export" functions will // get exported to the host std::vector<Symbol *> exportedFuncs; m->symbolTable->GetMatchingFunctions(lIsExported, &exportedFuncs); // Get all of the struct, vector, and enumerant types used as function // parameters. These vectors may have repeats. std::vector<const StructType *> exportedStructTypes; std::vector<const EnumType *> exportedEnumTypes; std::vector<const VectorType *> exportedVectorTypes; lGetExportedParamTypes(exportedFuncs, &exportedStructTypes, &exportedEnumTypes, &exportedVectorTypes); // And print them lEmitVectorTypedefs(exportedVectorTypes, file); lEmitEnumDecls(exportedEnumTypes, file); lEmitStructDecls(exportedStructTypes, file); fprintf(file, "\n"); fprintf(file, "///////////////////////////////////////////////////////////////////////////\n"); fprintf(file, "// host-side stubs for dev-side ISPC fucntion(s)\n"); fprintf(file, "///////////////////////////////////////////////////////////////////////////\n"); for (unsigned int i = 0; i < exportedFuncs.size(); ++i) { const Symbol *sym = exportedFuncs[i]; Assert(sym); const FunctionType *fct = CastType<FunctionType>(sym->type); Assert(fct); if (!fct->GetReturnType()->IsVoidType()) { Warning(sym->pos, "When emitting offload-stubs, ignoring \"export\"ed function with non-void return types.\n"); continue; } // ------------------------------------------------------- // first, emit a struct that holds the parameters // ------------------------------------------------------- std::string paramStructName = std::string("__ispc_dev_stub_") + sym->name; std::string paramStruct = emitOffloadParamStruct(paramStructName, sym, fct); fprintf(file, "%s\n", paramStruct.c_str()); // ------------------------------------------------------- // then, emit a fct stub that unpacks the parameters and pointers // ------------------------------------------------------- std::string decl = fct->GetCDeclaration(sym->name); fprintf(file, "extern %s {\n", decl.c_str()); int numPointers = 0; fprintf(file, " %s __args;\n", paramStructName.c_str()); // ------------------------------------------------------------------ // write args, and save pointers for later // ------------------------------------------------------------------ std::stringstream pointerArgs; for (int i = 0; i < fct->GetNumParameters(); i++) { const Type *orgParamType = fct->GetParameterType(i); std::string paramName = fct->GetParameterName(i); if (orgParamType->IsPointerType() || orgParamType->IsArrayType()) { /* we're passing pointers separately -- no pointers in that struct... */ if (numPointers) pointerArgs << ","; pointerArgs << "(void*)" << paramName; numPointers++; continue; } fprintf(file, " __args.%s = %s;\n", paramName.c_str(), paramName.c_str()); } // ------------------------------------------------------------------ // writer pointer list // ------------------------------------------------------------------ if (numPointers == 0) pointerArgs << "NULL"; fprintf(file, " void *ptr_args[] = { %s };\n", pointerArgs.str().c_str()); // ------------------------------------------------------------------ // ... and call the kernel with those args // ------------------------------------------------------------------ fprintf(file, " static ispc_kernel_handle_t kernel_handle = NULL;\n"); fprintf(file, " if (!kernel_handle) kernel_handle = ispc_host_get_kernel_handle(\"__ispc_dev_stub_%s\");\n", sym->name.c_str()); fprintf(file, " assert(kernel_handle);\n"); fprintf(file, " ispc_host_call_kernel(kernel_handle,\n" " &__args, sizeof(__args),\n" " ptr_args,%i);\n", numPointers); fprintf(file, "}\n\n"); } // end extern "C" fprintf(file, "#ifdef __cplusplus\n"); fprintf(file, "}/* namespace */\n"); fprintf(file, "#endif // __cplusplus\n"); // fprintf(file, "#ifdef __cplusplus\n"); // fprintf(file, "}/* end extern C */\n"); // fprintf(file, "#endif // __cplusplus\n"); fclose(file); return true; } bool Module::writeHeader(const char *fn) { FILE *f = fopen(fn, "w"); if (!f) { perror("fopen"); return false; } fprintf(f, "//\n// %s\n// (Header automatically generated by the ispc compiler.)\n", fn); fprintf(f, "// DO NOT EDIT THIS FILE.\n//\n\n"); // Create a nice guard string from the filename, turning any // non-number/letter characters into underbars std::string guard = "ISPC_"; const char *p = fn; while (*p) { if (isdigit(*p)) guard += *p; else if (isalpha(*p)) guard += toupper(*p); else guard += "_"; ++p; } if (g->noPragmaOnce) fprintf(f, "#ifndef %s\n#define %s\n\n", guard.c_str(), guard.c_str()); else fprintf(f, "#pragma once\n"); fprintf(f, "#include <stdint.h>\n\n"); if (g->emitInstrumentation) { fprintf(f, "#define ISPC_INSTRUMENTATION 1\n"); fprintf(f, "#if defined(__cplusplus) && (! defined(__ISPC_NO_EXTERN_C) || !__ISPC_NO_EXTERN_C )\nextern \"C\" " "{\n#endif // __cplusplus\n"); fprintf(f, " void ISPCInstrument(const char *fn, const char *note, int line, uint64_t mask);\n"); fprintf(f, "#if defined(__cplusplus) && (! defined(__ISPC_NO_EXTERN_C) || !__ISPC_NO_EXTERN_C )\n} /* end " "extern C */\n#endif // __cplusplus\n"); } // end namespace fprintf(f, "\n"); fprintf(f, "\n#ifdef __cplusplus\nnamespace ispc { /* namespace */\n#endif // __cplusplus\n"); // Collect single linear arrays of the exported and extern "C" // functions std::vector<Symbol *> exportedFuncs, externCFuncs; m->symbolTable->GetMatchingFunctions(lIsExported, &exportedFuncs); m->symbolTable->GetMatchingFunctions(lIsExternC, &externCFuncs); // Get all of the struct, vector, and enumerant types used as function // parameters. These vectors may have repeats. std::vector<const StructType *> exportedStructTypes; std::vector<const EnumType *> exportedEnumTypes; std::vector<const VectorType *> exportedVectorTypes; lGetExportedParamTypes(exportedFuncs, &exportedStructTypes, &exportedEnumTypes, &exportedVectorTypes); lGetExportedParamTypes(externCFuncs, &exportedStructTypes, &exportedEnumTypes, &exportedVectorTypes); // Go through the explicitly exported types for (int i = 0; i < (int)exportedTypes.size(); ++i) { if (const StructType *st = CastType<StructType>(exportedTypes[i].first)) exportedStructTypes.push_back(st->GetAsUniformType()); else if (const EnumType *et = CastType<EnumType>(exportedTypes[i].first)) exportedEnumTypes.push_back(et->GetAsUniformType()); else if (const VectorType *vt = CastType<VectorType>(exportedTypes[i].first)) exportedVectorTypes.push_back(vt->GetAsUniformType()); else FATAL("Unexpected type in export list"); } // And print them lEmitVectorTypedefs(exportedVectorTypes, f); lEmitEnumDecls(exportedEnumTypes, f); lEmitStructDecls(exportedStructTypes, f); // emit function declarations for exported stuff... if (exportedFuncs.size() > 0) { fprintf(f, "\n"); fprintf(f, "///////////////////////////////////////////////////////////////////////////\n"); fprintf(f, "// Functions exported from ispc code\n"); fprintf(f, "///////////////////////////////////////////////////////////////////////////\n"); lPrintFunctionDeclarations(f, exportedFuncs); } #if 0 if (externCFuncs.size() > 0) { fprintf(f, "\n"); fprintf(f, "///////////////////////////////////////////////////////////////////////////\n"); fprintf(f, "// External C functions used by ispc code\n"); fprintf(f, "///////////////////////////////////////////////////////////////////////////\n"); lPrintFunctionDeclarations(f, externCFuncs); } #endif // end namespace fprintf(f, "\n"); fprintf(f, "\n#ifdef __cplusplus\n} /* namespace */\n#endif // __cplusplus\n"); // end guard if (g->noPragmaOnce) fprintf(f, "\n#endif // %s\n", guard.c_str()); fclose(f); return true; } struct DispatchHeaderInfo { bool EmitUnifs; bool EmitFuncs; bool EmitFrontMatter; bool EmitBackMatter; bool Emit4; bool Emit8; bool Emit16; FILE *file; const char *fn; }; bool Module::writeDispatchHeader(DispatchHeaderInfo *DHI) { FILE *f = DHI->file; if (DHI->EmitFrontMatter) { fprintf(f, "//\n// %s\n// (Header automatically generated by the ispc compiler.)\n", DHI->fn); fprintf(f, "// DO NOT EDIT THIS FILE.\n//\n\n"); } // Create a nice guard string from the filename, turning any // non-number/letter characters into underbars std::string guard = "ISPC_"; const char *p = DHI->fn; while (*p) { if (isdigit(*p)) guard += *p; else if (isalpha(*p)) guard += toupper(*p); else guard += "_"; ++p; } if (DHI->EmitFrontMatter) { if (g->noPragmaOnce) fprintf(f, "#ifndef %s\n#define %s\n\n", guard.c_str(), guard.c_str()); else fprintf(f, "#pragma once\n"); fprintf(f, "#include <stdint.h>\n\n"); if (g->emitInstrumentation) { fprintf(f, "#define ISPC_INSTRUMENTATION 1\n"); fprintf(f, "#if defined(__cplusplus) && (! defined(__ISPC_NO_EXTERN_C) || !__ISPC_NO_EXTERN_C )\nextern " "\"C\" {\n#endif // __cplusplus\n"); fprintf(f, " void ISPCInstrument(const char *fn, const char *note, int line, uint64_t mask);\n"); fprintf(f, "#if defined(__cplusplus) && (! defined(__ISPC_NO_EXTERN_C) || !__ISPC_NO_EXTERN_C )\n} /* end " "extern C */\n#endif // __cplusplus\n"); } // end namespace fprintf(f, "\n"); fprintf(f, "\n#ifdef __cplusplus\nnamespace ispc { /* namespace */\n#endif // __cplusplus\n\n"); DHI->EmitFrontMatter = false; } // Collect single linear arrays of the exported and extern "C" // functions std::vector<Symbol *> exportedFuncs, externCFuncs; m->symbolTable->GetMatchingFunctions(lIsExported, &exportedFuncs); m->symbolTable->GetMatchingFunctions(lIsExternC, &externCFuncs); int programCount = g->target->getVectorWidth(); if ((DHI->Emit4 && (programCount == 4)) || (DHI->Emit8 && (programCount == 8)) || (DHI->Emit16 && (programCount == 16))) { // Get all of the struct, vector, and enumerant types used as function // parameters. These vectors may have repeats. std::vector<const StructType *> exportedStructTypes; std::vector<const EnumType *> exportedEnumTypes; std::vector<const VectorType *> exportedVectorTypes; lGetExportedParamTypes(exportedFuncs, &exportedStructTypes, &exportedEnumTypes, &exportedVectorTypes); lGetExportedParamTypes(externCFuncs, &exportedStructTypes, &exportedEnumTypes, &exportedVectorTypes); // Go through the explicitly exported types for (int i = 0; i < (int)exportedTypes.size(); ++i) { if (const StructType *st = CastType<StructType>(exportedTypes[i].first)) exportedStructTypes.push_back(st->GetAsUniformType()); else if (const EnumType *et = CastType<EnumType>(exportedTypes[i].first)) exportedEnumTypes.push_back(et->GetAsUniformType()); else if (const VectorType *vt = CastType<VectorType>(exportedTypes[i].first)) exportedVectorTypes.push_back(vt->GetAsUniformType()); else FATAL("Unexpected type in export list"); } // And print them if (DHI->EmitUnifs) { lEmitVectorTypedefs(exportedVectorTypes, f); lEmitEnumDecls(exportedEnumTypes, f); } lEmitStructDecls(exportedStructTypes, f, DHI->EmitUnifs); // Update flags DHI->EmitUnifs = false; if (programCount == 4) { DHI->Emit4 = false; } else if (programCount == 8) { DHI->Emit8 = false; } else if (programCount == 16) { DHI->Emit16 = false; } } if (DHI->EmitFuncs) { // emit function declarations for exported stuff... if (exportedFuncs.size() > 0) { fprintf(f, "\n"); fprintf(f, "///////////////////////////////////////////////////////////////////////////\n"); fprintf(f, "// Functions exported from ispc code\n"); fprintf(f, "///////////////////////////////////////////////////////////////////////////\n"); lPrintFunctionDeclarations(f, exportedFuncs, 1, true); fprintf(f, "\n"); } DHI->EmitFuncs = false; } if (DHI->EmitBackMatter) { // end namespace fprintf(f, "\n"); fprintf(f, "\n#ifdef __cplusplus\n} /* namespace */\n#endif // __cplusplus\n"); // end guard if (g->noPragmaOnce) fprintf(f, "\n#endif // %s\n", guard.c_str()); DHI->EmitBackMatter = false; } return true; } void Module::execPreprocessor(const char *infilename, llvm::raw_string_ostream *ostream) const { clang::CompilerInstance inst; llvm::raw_fd_ostream stderrRaw(2, false); clang::DiagnosticOptions *diagOptions = new clang::DiagnosticOptions(); clang::TextDiagnosticPrinter *diagPrinter = new clang::TextDiagnosticPrinter(stderrRaw, diagOptions); llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagIDs(new clang::DiagnosticIDs); clang::DiagnosticsEngine *diagEngine = new clang::DiagnosticsEngine(diagIDs, diagOptions, diagPrinter); inst.setDiagnostics(diagEngine); inst.createFileManager(); const std::shared_ptr<clang::TargetOptions> &options = std::make_shared<clang::TargetOptions>(inst.getTargetOpts()); llvm::Triple triple(module->getTargetTriple()); if (triple.getTriple().empty()) { triple.setTriple(llvm::sys::getDefaultTargetTriple()); } options->Triple = triple.getTriple(); clang::TargetInfo *target = clang::TargetInfo::CreateTargetInfo(inst.getDiagnostics(), options); inst.setTarget(target); inst.createSourceManager(inst.getFileManager()); clang::FrontendInputFile inputFile(infilename, clang::InputKind()); inst.InitializeSourceManager(inputFile); // Don't remove comments in the preprocessor, so that we can accurately // track the source file position by handling them ourselves. inst.getPreprocessorOutputOpts().ShowComments = 1; inst.getPreprocessorOutputOpts().ShowCPP = 1; clang::HeaderSearchOptions &headerOpts = inst.getHeaderSearchOpts(); headerOpts.UseBuiltinIncludes = 0; headerOpts.UseStandardSystemIncludes = 0; headerOpts.UseStandardCXXIncludes = 0; #ifndef ISPC_NO_DUMPS if (g->debugPrint) headerOpts.Verbose = 1; #endif for (int i = 0; i < (int)g->includePath.size(); ++i) { headerOpts.AddPath(g->includePath[i], clang::frontend::Angled, false /* not a framework */, true /* ignore sys root */); } clang::PreprocessorOptions &opts = inst.getPreprocessorOpts(); // Add defs for ISPC and PI opts.addMacroDef("ISPC"); opts.addMacroDef("PI=3.1415926535"); // Add defs for ISPC_UINT_IS_DEFINED. // This lets the user know uint* is part of language. opts.addMacroDef("ISPC_UINT_IS_DEFINED"); // Add #define for current compilation target char targetMacro[128]; snprintf(targetMacro, sizeof(targetMacro), "ISPC_TARGET_%s", g->target->GetISAString()); char *p = targetMacro; while (*p) { *p = toupper(*p); if (*p == '-') *p = '_'; ++p; } // Add 'TARGET_WIDTH' macro to expose vector width to user. std::string TARGET_WIDTH = "TARGET_WIDTH=" + std::to_string(g->target->getVectorWidth()); opts.addMacroDef(TARGET_WIDTH); // Add 'TARGET_ELEMENT_WIDTH' macro to expose element width to user. std::string TARGET_ELEMENT_WIDTH = "TARGET_ELEMENT_WIDTH=" + std::to_string(g->target->getDataTypeWidth() / 8); opts.addMacroDef(TARGET_ELEMENT_WIDTH); opts.addMacroDef(targetMacro); if (g->target->is32Bit()) opts.addMacroDef("ISPC_POINTER_SIZE=32"); else opts.addMacroDef("ISPC_POINTER_SIZE=64"); if (g->target->hasHalf()) opts.addMacroDef("ISPC_TARGET_HAS_HALF"); if (g->target->hasRand()) opts.addMacroDef("ISPC_TARGET_HAS_RAND"); if (g->target->hasTranscendentals()) opts.addMacroDef("ISPC_TARGET_HAS_TRANSCENDENTALS"); if (g->opt.forceAlignedMemory) opts.addMacroDef("ISPC_FORCE_ALIGNED_MEMORY"); constexpr int buf_size = 25; char ispc_major[buf_size], ispc_minor[buf_size]; snprintf(ispc_major, buf_size, "ISPC_MAJOR_VERSION=%d", ISPC_VERSION_MAJOR); snprintf(ispc_minor, buf_size, "ISPC_MINOR_VERSION=%d", ISPC_VERSION_MINOR); opts.addMacroDef(ispc_major); opts.addMacroDef(ispc_minor); if (g->target->hasFp64Support()) { opts.addMacroDef("ISPC_FP64_SUPPORTED "); } if (g->includeStdlib) { if (g->opt.disableAsserts) opts.addMacroDef("assert(x)="); else opts.addMacroDef("assert(x)=__assert(#x, x)"); } for (unsigned int i = 0; i < g->cppArgs.size(); ++i) { // Sanity check--should really begin with -D if (g->cppArgs[i].substr(0, 2) == "-D") { opts.addMacroDef(g->cppArgs[i].substr(2)); } } if (g->target->isGenXTarget()) { opts.addMacroDef("taskIndex=__taskIndex()"); opts.addMacroDef("taskCount=__taskCount()"); opts.addMacroDef("taskCount0=__taskCount0()"); opts.addMacroDef("taskCount1=__taskCount1()"); opts.addMacroDef("taskCount2=__taskCount2()"); opts.addMacroDef("taskIndex0=__taskIndex0()"); opts.addMacroDef("taskIndex1=__taskIndex1()"); opts.addMacroDef("taskIndex2=__taskIndex2()"); } inst.getLangOpts().LineComment = 1; inst.createPreprocessor(clang::TU_Complete); diagPrinter->BeginSourceFile(inst.getLangOpts(), &inst.getPreprocessor()); clang::DoPrintPreprocessedInput(inst.getPreprocessor(), ostream, inst.getPreprocessorOutputOpts()); diagPrinter->EndSourceFile(); } // Given an output filename of the form "foo.obj", and an ISA name like // "avx", return a string with the ISA name inserted before the original // filename's suffix, like "foo_avx.obj". static std::string lGetTargetFileName(const char *outFileName, const char *isaString) { int bufferSize = strlen(outFileName) + 16; char *targetOutFileName = new char[bufferSize]; if (strrchr(outFileName, '.') != NULL) { // Copy everything up to the last '.' int count = strrchr(outFileName, '.') - outFileName; strncpy(targetOutFileName, outFileName, count); targetOutFileName[count] = '\0'; // Add the ISA name strncat(targetOutFileName, "_", bufferSize - strlen(targetOutFileName) - 1); strncat(targetOutFileName, isaString, bufferSize - strlen(targetOutFileName) - 1); // And finish with the original file suffix strncat(targetOutFileName, strrchr(outFileName, '.'), bufferSize - strlen(targetOutFileName) - 1); } else { // Can't find a '.' in the filename, so just append the ISA suffix // to what we weregiven strncpy(targetOutFileName, outFileName, bufferSize - 1); targetOutFileName[bufferSize - 1] = '\0'; strncat(targetOutFileName, "_", bufferSize - strlen(targetOutFileName) - 1); strncat(targetOutFileName, isaString, bufferSize - strlen(targetOutFileName) - 1); } return targetOutFileName; } static bool lSymbolIsExported(const Symbol *s) { return s->exportedFunction != NULL; } // Small structure to hold pointers to the various different versions of a // llvm::Function that were compiled for different compilation target ISAs. struct FunctionTargetVariants { FunctionTargetVariants() { for (int i = 0; i < Target::NUM_ISAS; ++i) { func[i] = NULL; FTs[i] = NULL; } } // The func array is indexed with the Target::ISA enumerant. Some // values may be NULL, indicating that the original function wasn't // compiled to the corresponding target ISA. llvm::Function *func[Target::NUM_ISAS]; const FunctionType *FTs[Target::NUM_ISAS]; }; // Given the symbol table for a module, return a map from function names to // FunctionTargetVariants for each function that was defined with the // 'export' qualifier in ispc. static void lGetExportedFunctions(SymbolTable *symbolTable, std::map<std::string, FunctionTargetVariants> &functions) { std::vector<Symbol *> syms; symbolTable->GetMatchingFunctions(lSymbolIsExported, &syms); for (unsigned int i = 0; i < syms.size(); ++i) { FunctionTargetVariants &ftv = functions[syms[i]->name]; ftv.func[g->target->getISA()] = syms[i]->exportedFunction; ftv.FTs[g->target->getISA()] = CastType<FunctionType>(syms[i]->type); } } static llvm::FunctionType *lGetVaryingDispatchType(FunctionTargetVariants &funcs) { llvm::Type *ptrToInt8Ty = llvm::Type::getInt8PtrTy(*g->ctx); llvm::FunctionType *resultFuncTy = NULL; for (int i = 0; i < Target::NUM_ISAS; ++i) { if (funcs.func[i] == NULL) { continue; } else { bool foundVarying = false; const FunctionType *ft = funcs.FTs[i]; resultFuncTy = funcs.func[i]->getFunctionType(); int numArgs = ft->GetNumParameters(); llvm::SmallVector<llvm::Type *, 8> ftype; for (int j = 0; j < numArgs; ++j) { ftype.push_back(resultFuncTy->getParamType(j)); } for (int j = 0; j < numArgs; ++j) { const Type *arg = ft->GetParameterType(j); if (arg->IsPointerType()) { const Type *baseType = CastType<PointerType>(arg)->GetBaseType(); // For each varying type pointed to, swap the LLVM pointer type // with i8 * (as close as we can get to void *) if (baseType->IsVaryingType()) { ftype[j] = ptrToInt8Ty; foundVarying = true; } } } if (foundVarying) { resultFuncTy = llvm::FunctionType::get(resultFuncTy->getReturnType(), ftype, false); } } } // We should've found at least one variant here // or else something fishy is going on. Assert(resultFuncTy); return resultFuncTy; } /** Create the dispatch function for an exported ispc function. This function checks to see which vector ISAs the system the code is running on supports and calls out to the best available variant that was generated at compile time. @param module Module in which to create the dispatch function. @param setISAFunc Pointer to the __set_system_isa() function defined in builtins-dispatch.ll (which is linked into the given module before we get here.) @param systemBestISAPtr Pointer to the module-local __system_best_isa variable, which holds a value of the Target::ISA enumerant giving the most capable ISA that the system supports. @param name Name of the function for which we're generating a dispatch function @param funcs Target-specific variants of the exported function. */ static void lCreateDispatchFunction(llvm::Module *module, llvm::Function *setISAFunc, llvm::Value *systemBestISAPtr, const std::string &name, FunctionTargetVariants &funcs) { // The llvm::Function pointers in funcs are pointers to functions in // different llvm::Modules, so we can't call them directly. Therefore, // we'll start by generating an 'extern' declaration of each one that // we have in the current module so that we can then call out to that. llvm::Function *targetFuncs[Target::NUM_ISAS]; // New helper function checks to see if we need to rewrite the // type for the dispatch function in case of pointers to varyings llvm::FunctionType *ftype = lGetVaryingDispatchType(funcs); // Now we insert type-punned declarations for dispatched functions. // This is needed when compiling modules for a set of architectures // with different vector lengths. Due to restrictions, the return // type is the same across all architectures, however in different // modules it may have dissimilar names. The loop below works this // around. for (int i = 0; i < Target::NUM_ISAS; ++i) { if (funcs.func[i]) { targetFuncs[i] = llvm::Function::Create(ftype, llvm::GlobalValue::ExternalLinkage, funcs.func[i]->getName(), module); g->target->markFuncWithCallingConv(targetFuncs[i]); } else targetFuncs[i] = NULL; } bool voidReturn = ftype->getReturnType()->isVoidTy(); // Now we can emit the definition of the dispatch function.. llvm::Function *dispatchFunc = llvm::Function::Create(ftype, llvm::GlobalValue::ExternalLinkage, name.c_str(), module); g->target->markFuncWithCallingConv(dispatchFunc); llvm::BasicBlock *bblock = llvm::BasicBlock::Create(*g->ctx, "entry", dispatchFunc); // Start by calling out to the function that determines the system's // ISA and sets __system_best_isa, if it hasn't been set yet. llvm::CallInst::Create(setISAFunc, "", bblock); // Now we can load the system's ISA enumerant #if ISPC_LLVM_VERSION >= ISPC_LLVM_11_0 llvm::PointerType *ptr_type = llvm::dyn_cast<llvm::PointerType>(systemBestISAPtr->getType()); Assert(ptr_type); llvm::Value *systemISA = new llvm::LoadInst(ptr_type->getPointerElementType(), systemBestISAPtr, "system_isa", bblock); #else llvm::Value *systemISA = new llvm::LoadInst(systemBestISAPtr, "system_isa", bblock); #endif // Now emit code that works backwards though the available variants of // the function. We'll call out to the first one we find that will run // successfully on the system the code is running on. In working // through the candidate ISAs here backward, we're taking advantage of // the expectation that they are ordered in the Target::ISA enumerant // from least to most capable. for (int i = Target::NUM_ISAS - 1; i >= 0; --i) { if (targetFuncs[i] == NULL) continue; // Emit code to see if the system can run the current candidate // variant successfully--"is the system's ISA enumerant value >= // the enumerant value of the current candidate?" llvm::Value *ok = llvm::CmpInst::Create(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_SGE, systemISA, LLVMInt32(i), "isa_ok", bblock); llvm::BasicBlock *callBBlock = llvm::BasicBlock::Create(*g->ctx, "do_call", dispatchFunc); llvm::BasicBlock *nextBBlock = llvm::BasicBlock::Create(*g->ctx, "next_try", dispatchFunc); llvm::BranchInst::Create(callBBlock, nextBBlock, ok, bblock); // Emit the code to make the call call in callBBlock. // Just pass through all of the args from the dispatch function to // the target-specific function. std::vector<llvm::Value *> args; llvm::Function::arg_iterator argIter = dispatchFunc->arg_begin(); llvm::Function::arg_iterator targsIter = targetFuncs[i]->arg_begin(); for (; argIter != dispatchFunc->arg_end(); ++argIter, ++targsIter) { // Check to see if we rewrote any types in the dispatch function. // If so, create bitcasts for the appropriate pointer types. if (argIter->getType() == targsIter->getType()) { args.push_back(&*argIter); } else { llvm::CastInst *argCast = llvm::CastInst::CreatePointerCast(&*argIter, targsIter->getType(), "dpatch_arg_bitcast", callBBlock); args.push_back(argCast); } } if (voidReturn) { llvm::CallInst *callInst = llvm::CallInst::Create(targetFuncs[i], args, "", callBBlock); if (g->calling_conv == CallingConv::x86_vectorcall) { callInst->setCallingConv(llvm::CallingConv::X86_VectorCall); } llvm::ReturnInst::Create(*g->ctx, callBBlock); } else { llvm::CallInst *callInst = llvm::CallInst::Create(targetFuncs[i], args, "ret_value", callBBlock); if (g->calling_conv == CallingConv::x86_vectorcall) { callInst->setCallingConv(llvm::CallingConv::X86_VectorCall); } llvm::ReturnInst::Create(*g->ctx, callInst, callBBlock); } // Otherwise we'll go on to the next candidate and see about that // one... bblock = nextBBlock; } // We couldn't find a match that the current system was capable of // running. We'll call abort(); this is a bit of a blunt hammer--it // might be preferable to call a user-supplied callback--ISPCError(...) // or some such, but we don't want to start imposing too much of a // runtime library requirement either... llvm::Function *abortFunc = module->getFunction("abort"); Assert(abortFunc); llvm::CallInst::Create(abortFunc, "", bblock); // Return an undef value from the function here; we won't get to this // point at runtime, but LLVM needs all of the basic blocks to be // terminated... if (voidReturn) llvm::ReturnInst::Create(*g->ctx, bblock); else { llvm::Value *undefRet = llvm::UndefValue::get(ftype->getReturnType()); llvm::ReturnInst::Create(*g->ctx, undefRet, bblock); } } // Initialize a dispatch module static llvm::Module *lInitDispatchModule() { llvm::Module *module = new llvm::Module("dispatch_module", *g->ctx); module->setTargetTriple(g->target->GetTripleString()); // DataLayout information supposed to be managed in single place in Target class. module->setDataLayout(g->target->getDataLayout()->getStringRepresentation()); // First, link in the definitions from the builtins-dispatch.ll file. const BitcodeLib *dispatch = g->target_registry->getDispatchLib(g->target_os); Assert(dispatch); AddBitcodeToModule(dispatch, module); return module; } // Complete the creation of a dispatch module. // Given a map that holds the mapping from each of the 'export'ed functions // in the ispc program to the target-specific variants of the function, // create a llvm::Module that has a dispatch function for each exported // function that checks the system's capabilities and picks the most // appropriate compiled variant of the function. static void lEmitDispatchModule(llvm::Module *module, std::map<std::string, FunctionTargetVariants> &functions) { // Get pointers to things we need below llvm::Function *setFunc = module->getFunction("__set_system_isa"); Assert(setFunc != NULL); llvm::Value *systemBestISAPtr = module->getGlobalVariable("__system_best_isa", true); Assert(systemBestISAPtr != NULL); // For each exported function, create the dispatch function std::map<std::string, FunctionTargetVariants>::iterator iter; for (iter = functions.begin(); iter != functions.end(); ++iter) lCreateDispatchFunction(module, setFunc, systemBestISAPtr, iter->first, iter->second); // Do some rudimentary cleanup of the final result and make sure that // the module is all ok. llvm::legacy::PassManager optPM; optPM.add(llvm::createGlobalDCEPass()); optPM.add(llvm::createVerifierPass()); optPM.run(*module); } // Determines if two types are compatible static bool lCompatibleTypes(llvm::Type *Ty1, llvm::Type *Ty2) { while (Ty1->getTypeID() == Ty2->getTypeID()) switch (Ty1->getTypeID()) { case llvm::ArrayType::ArrayTyID: if (Ty1->getArrayNumElements() != Ty2->getArrayNumElements()) return false; Ty1 = Ty1->getArrayElementType(); Ty2 = Ty2->getArrayElementType(); break; case llvm::ArrayType::PointerTyID: Ty1 = Ty1->getPointerElementType(); Ty2 = Ty2->getPointerElementType(); break; case llvm::ArrayType::StructTyID: { llvm::StructType *STy1 = llvm::dyn_cast<llvm::StructType>(Ty1); llvm::StructType *STy2 = llvm::dyn_cast<llvm::StructType>(Ty2); return STy1 && STy2 && STy1->isLayoutIdentical(STy2); } default: // Pointers for compatible simple types are assumed equal return Ty1 == Ty2; } return false; } // Grab all of the global value definitions from the module and change them // to be declarations; we'll emit a single definition of each global in the // final module used with the dispatch functions, so that we don't have // multiple definitions of them, one in each of the target-specific output // files. static void lExtractOrCheckGlobals(llvm::Module *msrc, llvm::Module *mdst, bool check) { llvm::Module::global_iterator iter; llvm::ValueToValueMapTy VMap; for (iter = msrc->global_begin(); iter != msrc->global_end(); ++iter) { llvm::GlobalVariable *gv = &*iter; // Is it a global definition? if (gv->getLinkage() == llvm::GlobalValue::ExternalLinkage && gv->hasInitializer()) { llvm::Type *type = gv->getType()->getElementType(); Symbol *sym = m->symbolTable->LookupVariable(gv->getName().str().c_str()); Assert(sym != NULL); // Check presence and compatibility for the current global if (check) { llvm::GlobalVariable *exist = mdst->getGlobalVariable(gv->getName()); Assert(exist != NULL); // It is possible that the types may not match: for // example, this happens with varying globals if we // compile to different vector widths if (!lCompatibleTypes(exist->getType(), gv->getType())) { Warning(sym->pos, "Mismatch in size/layout of global " "variable \"%s\" with different targets. " "Globals must not include \"varying\" types or arrays " "with size based on programCount when compiling to " "targets with differing vector widths.", gv->getName().str().c_str()); } } // Alternatively, create it anew and make it match the original else { llvm::GlobalVariable *newGlobal = new llvm::GlobalVariable(*mdst, type, gv->isConstant(), llvm::GlobalValue::ExternalLinkage, (llvm::Constant *)nullptr, gv->getName()); VMap[&*iter] = newGlobal; newGlobal->setInitializer(llvm::MapValue(iter->getInitializer(), VMap)); newGlobal->copyAttributesFrom(gv); } // Turn this into an 'extern' declaration by clearing its // initializer. gv->setInitializer(NULL); } } } int Module::CompileAndOutput(const char *srcFile, Arch arch, const char *cpu, std::vector<ISPCTarget> targets, OutputFlags outputFlags, OutputType outputType, const char *outFileName, const char *headerFileName, const char *depsFileName, const char *depsTargetName, const char *hostStubFileName, const char *devStubFileName) { if (targets.size() == 0 || targets.size() == 1) { // We're only compiling to a single target // TODO something wrong here ISPCTarget target = ISPCTarget::none; if (targets.size() == 1) { target = targets[0]; } g->target = new Target(arch, cpu, target, 0 != (outputFlags & GeneratePIC), g->printTarget); if (!g->target->isValid()) return 1; m = new Module(srcFile); if (m->CompileFile() == 0) { llvm::TimeTraceScope TimeScope("Backend"); #ifdef ISPC_GENX_ENABLED if (outputType == Asm || outputType == Object) { if (g->target->isGenXTarget()) { Error(SourcePos(), "%s output is not supported yet for \"genx-*\" targets. ", (outputType == Asm) ? "assembly" : "binary"); return 1; } } if (g->target->isGenXTarget() && outputType == OutputType::Object) { outputType = OutputType::ZEBIN; } if (!g->target->isGenXTarget() && (outputType == OutputType::ZEBIN || outputType == OutputType::SPIRV)) { Error(SourcePos(), "SPIR-V and L0 binary formats are supported for gen target only"); return 1; } #endif if (outFileName != NULL) if (!m->writeOutput(outputType, outputFlags, outFileName)) return 1; if (headerFileName != NULL) if (!m->writeOutput(Module::Header, outputFlags, headerFileName)) return 1; if (depsFileName != NULL || (outputFlags & Module::OutputDepsToStdout)) { std::string targetName; if (depsTargetName) targetName = depsTargetName; else if (outFileName) targetName = outFileName; else if (!IsStdin(srcFile)) { targetName = srcFile; size_t dot = targetName.find_last_of('.'); if (dot != std::string::npos) targetName.erase(dot, std::string::npos); targetName.append(".o"); } else targetName = "a.out"; if (!m->writeOutput(Module::Deps, outputFlags, depsFileName, targetName.c_str(), srcFile)) return 1; } if (hostStubFileName != NULL) if (!m->writeOutput(Module::HostStub, outputFlags, hostStubFileName)) return 1; if (devStubFileName != NULL) if (!m->writeOutput(Module::DevStub, outputFlags, devStubFileName)) return 1; } else ++m->errorCount; int errorCount = m->errorCount; delete m; m = NULL; delete g->target; g->target = NULL; return errorCount > 0; } else { if (IsStdin(srcFile)) { Error(SourcePos(), "Compiling programs from standard input isn't " "supported when compiling for multiple targets. Please use " "an intermediate temporary file."); return 1; } if (cpu != NULL) { Error(SourcePos(), "Illegal to specify cpu type when compiling " "for multiple targets."); return 1; } // The user supplied multiple targets Assert(targets.size() > 1); if (outFileName != NULL && strcmp(outFileName, "-") == 0) { Error(SourcePos(), "Multi-target compilation can't generate output " "to stdout. Please provide an output filename.\n"); return 1; } // Make sure that the function names for 'export'ed functions have // the target ISA appended to them. g->mangleFunctionsWithTarget = true; llvm::TargetMachine *targetMachines[Target::NUM_ISAS]; for (int i = 0; i < Target::NUM_ISAS; ++i) targetMachines[i] = NULL; llvm::Module *dispatchModule = NULL; std::map<std::string, FunctionTargetVariants> exportedFunctions; int errorCount = 0; // Handle creating a "generic" header file for multiple targets // that use exported varyings DispatchHeaderInfo DHI; if (headerFileName != NULL) { DHI.file = fopen(headerFileName, "w"); if (!DHI.file) { perror("fopen"); return false; } DHI.fn = headerFileName; DHI.EmitUnifs = true; DHI.EmitFuncs = true; DHI.EmitFrontMatter = true; DHI.Emit4 = true; DHI.Emit8 = true; DHI.Emit16 = true; // This is toggled later. DHI.EmitBackMatter = false; } for (unsigned int i = 0; i < targets.size(); ++i) { g->target = new Target(arch, cpu, targets[i], 0 != (outputFlags & GeneratePIC), g->printTarget); if (!g->target->isValid()) return 1; // Issue an error if we've already compiled to a variant of // this target ISA. (It doesn't make sense to compile to both // avx and avx-x2, for example.) if (targetMachines[g->target->getISA()] != NULL) { Error(SourcePos(), "Can't compile to multiple variants of %s " "target!\n", g->target->GetISAString()); return 1; } targetMachines[g->target->getISA()] = g->target->GetTargetMachine(); m = new Module(srcFile); int compileFileError = m->CompileFile(); llvm::TimeTraceScope TimeScope("Backend"); if (compileFileError == 0) { // Create the dispatch module, unless already created; // in the latter case, just do the checking bool check = (dispatchModule != NULL); if (!check) dispatchModule = lInitDispatchModule(); lExtractOrCheckGlobals(m->module, dispatchModule, check); // Grab pointers to the exported functions from the module we // just compiled, for use in generating the dispatch function // later. lGetExportedFunctions(m->symbolTable, exportedFunctions); if (outFileName != NULL) { std::string targetOutFileName; const char *isaName = g->target->GetISAString(); targetOutFileName = lGetTargetFileName(outFileName, isaName); if (!m->writeOutput(outputType, outputFlags, targetOutFileName.c_str())) { return 1; } } } else { ++m->errorCount; } errorCount += m->errorCount; if (errorCount != 0) { return 1; } // Only write the generate header file, if desired, the first // time through the loop here. if (headerFileName != NULL) { if (i == targets.size() - 1) { // only print backmatter on the last target. DHI.EmitBackMatter = true; } const char *isaName; isaName = g->target->GetISAString(); std::string targetHeaderFileName = lGetTargetFileName(headerFileName, isaName); // write out a header w/o target name for the first target only if (!m->writeOutput(Module::Header, outputFlags, headerFileName, nullptr, nullptr, &DHI)) { return 1; } if (!m->writeOutput(Module::Header, outputFlags, targetHeaderFileName.c_str())) { return 1; } if (i == targets.size() - 1) { fclose(DHI.file); } } delete g->target; g->target = NULL; // Important: Don't delete the llvm::Module *m here; we need to // keep it around so the llvm::Functions *s stay valid for when // we generate the dispatch module's functions... } // Find the first non-NULL target machine from the targets we // compiled to above. We'll use this as the target machine for // compiling the dispatch module--this is safe in that it is the // least-common-denominator of all of the targets we compiled to. llvm::TargetMachine *firstTargetMachine = NULL; int i = 0; const char *firstISA = ""; ISPCTarget firstTarget = ISPCTarget::none; while (i < Target::NUM_ISAS && firstTargetMachine == NULL) { firstISA = Target::ISAToTargetString((Target::ISA)i); firstTarget = ParseISPCTarget(firstISA); firstTargetMachine = targetMachines[i++]; } Assert(strcmp(firstISA, "") != 0); Assert(firstTarget != ISPCTarget::none); Assert(firstTargetMachine != NULL); g->target = new Target(arch, cpu, firstTarget, 0 != (outputFlags & GeneratePIC), false); if (!g->target->isValid()) { return 1; } if (dispatchModule == NULL) { Error(SourcePos(), "Failed to create dispatch module.\n"); return 1; } lEmitDispatchModule(dispatchModule, exportedFunctions); if (outFileName != NULL) { if ((outputType == Bitcode) || (outputType == BitcodeText)) writeBitcode(dispatchModule, outFileName, outputType); else writeObjectFileOrAssembly(firstTargetMachine, dispatchModule, outputType, outFileName); } if (depsFileName != NULL || (outputFlags & Module::OutputDepsToStdout)) { std::string targetName; if (depsTargetName) targetName = depsTargetName; else if (outFileName) targetName = outFileName; else if (!IsStdin(srcFile)) { targetName = srcFile; size_t dot = targetName.find_last_of('.'); if (dot != std::string::npos) targetName.erase(dot, std::string::npos); targetName.append(".o"); } else targetName = "a.out"; if (!m->writeOutput(Module::Deps, outputFlags, depsFileName, targetName.c_str(), srcFile)) return 1; } delete g->target; g->target = NULL; return errorCount > 0; } }
42.503381
120
0.584681
tay10r
33a7145848f45d8f86a7996d7ba6deb60f2f2b36
4,711
cpp
C++
HelperFunctions/getVkGraphicsPipelineShaderGroupsCreateInfoNV.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
HelperFunctions/getVkGraphicsPipelineShaderGroupsCreateInfoNV.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
HelperFunctions/getVkGraphicsPipelineShaderGroupsCreateInfoNV.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Douglas Kaip * * 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. */ /* * getVkGraphicsPipelineShaderGroupsCreateInfoNV.cpp * * Created on: Sep 10, 2020 * Author: Douglas Kaip */ #include "JVulkanHelperFunctions.hh" #include "slf4j.hh" namespace jvulkan { void getVkGraphicsPipelineShaderGroupsCreateInfoNV( JNIEnv *env, jobject jVkGraphicsPipelineShaderGroupsCreateInfoNVObject, VkGraphicsPipelineShaderGroupsCreateInfoNV *vkGraphicsPipelineShaderGroupsCreateInfoNV, std::vector<void *> *memoryToFree) { jclass theClass = env->GetObjectClass(jVkGraphicsPipelineShaderGroupsCreateInfoNVObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not get class for jVkGraphicsPipelineShaderGroupsCreateInfoNVObject"); return; } //////////////////////////////////////////////////////////////////////// VkStructureType sTypeValue = getSType(env, jVkGraphicsPipelineShaderGroupsCreateInfoNVObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getSType failed."); return; } //////////////////////////////////////////////////////////////////////// jobject jpNextObject = getpNextObject(env, jVkGraphicsPipelineShaderGroupsCreateInfoNVObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getpNext failed."); return; } void *pNext = nullptr; if (jpNextObject != nullptr) { getpNextChain( env, jpNextObject, &pNext, memoryToFree); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getpNextChain failed."); return; } } //////////////////////////////////////////////////////////////////////// jmethodID methodId = env->GetMethodID(theClass, "getGroups", "()Ljava/util/Collection;"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for getGroups"); return; } jobject jCollection = env->CallObjectMethod(jVkGraphicsPipelineShaderGroupsCreateInfoNVObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallObjectMethod"); return; } uint32_t groupCount = 0; VkGraphicsShaderGroupCreateInfoNV *pGroups = nullptr; jvulkan::getVkGraphicsShaderGroupCreateInfoNVCollection( env, jCollection, &pGroups, (int *)&groupCount, memoryToFree); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling getVkGraphicsShaderGroupCreateInfoNVCollection"); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "getPipelines", "()Ljava/util/Collection;"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for getPipelines"); return; } jobject jVkPipelinesObject = env->CallObjectMethod(jVkGraphicsPipelineShaderGroupsCreateInfoNVObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallObjectMethod"); return; } uint32_t pipelineCount = 0; VkPipeline_T **pPipelines = nullptr; jvulkan::getVkPipelineCollection( env, jVkPipelinesObject, &pPipelines, (int *)&pPipelines, memoryToFree); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling getVkPipelineCollection."); return; } vkGraphicsPipelineShaderGroupsCreateInfoNV->sType = sTypeValue; vkGraphicsPipelineShaderGroupsCreateInfoNV->pNext = (void *)pNext; vkGraphicsPipelineShaderGroupsCreateInfoNV->groupCount = groupCount; vkGraphicsPipelineShaderGroupsCreateInfoNV->pGroups = pGroups; vkGraphicsPipelineShaderGroupsCreateInfoNV->pipelineCount = pipelineCount; vkGraphicsPipelineShaderGroupsCreateInfoNV->pPipelines = pPipelines; } }
33.892086
121
0.610062
dkaip
33a809f227a3f1ded6debd42b8ba596b3f1fa7b3
6,270
cpp
C++
driver_massless/FileSettingsLoader.cpp
Massless-io/OpenVRDriver_MasslessPen
bce3c01877752d4e9c2135dec3e56b40e956ae60
[ "BSD-3-Clause-Clear", "CC0-1.0", "BSD-3-Clause" ]
null
null
null
driver_massless/FileSettingsLoader.cpp
Massless-io/OpenVRDriver_MasslessPen
bce3c01877752d4e9c2135dec3e56b40e956ae60
[ "BSD-3-Clause-Clear", "CC0-1.0", "BSD-3-Clause" ]
null
null
null
driver_massless/FileSettingsLoader.cpp
Massless-io/OpenVRDriver_MasslessPen
bce3c01877752d4e9c2135dec3e56b40e956ae60
[ "BSD-3-Clause-Clear", "CC0-1.0", "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2020 Massless Corp. - All Rights Reserved * Author: Jacob Hilton. * You may use, distribute and modify this code under the * terms of the BSD 3-Clause "New" or "Revised" License. * * You should have received a copy of this license with * this file. If not, please email support@massless.io */ #include "FileSettingsLoader.hpp" #include "DriverLog.hpp" FileSettingsLoader::FileSettingsLoader(std::filesystem::path config_path) { nlohmann::json default_json = this->toJson(DriverSettings::make_default()); try { // Try to make file if it doesnt exist with default settings if (!std::filesystem::exists(config_path)) { std::ofstream config_file_stream(config_path); config_file_stream << default_json.dump(4, ' ', true); } } catch (const std::system_error& e) { throw DriverSettingsException(e.code().value(), e.what()); } catch (const std::exception& e) { throw DriverSettingsException(0, e.what()); } // Delay opening ofstream until destructor this->m_isRealFilestream = true; this->m_filePath = config_path; DriverLog("Loading settings from file: %s \n", this->m_filePath.string().c_str()); } FileSettingsLoader::FileSettingsLoader(std::unique_ptr<std::istream> read_stream, std::unique_ptr<std::ostream> write_stream) : m_inStream(std::move(read_stream)), m_outStream(std::move(write_stream)) { } DriverSettings FileSettingsLoader::readSettings() { using json = nlohmann::json; json input_json; try { //#ifndef __INTELLISENSE__ // Intellisense errors on nlohmann::json::parse, but compiles fine and is within spec https://github.com/Microsoft/vscode-cpptools/issues/1901 if (this->m_isRealFilestream) { input_json = nlohmann::json::parse(std::ifstream(this->m_filePath)); } else { this->m_inStream->seekg(0); input_json = nlohmann::json::parse(*this->m_inStream); } //#endif __INTELLISENSE__ } catch (const std::exception & e) { throw DriverSettingsException(0, e.what()); } DriverSettings settings = this->fromJson(input_json); return settings; } void FileSettingsLoader::writeSettings(DriverSettings settings) { try { if (this->m_isRealFilestream) { this->m_outStream = std::make_unique<std::ofstream>(this->m_filePath, std::fstream::trunc); } this->m_outStream->seekp(0); std::string json_string = this->toJson(settings).dump(4, ' ', true); (*this->m_outStream) << json_string; if (this->m_isRealFilestream) { this->m_outStream.reset(); } } catch (const std::exception&) {/* Failed to write settings */ } } DriverSettings FileSettingsLoader::fromJson(nlohmann::json input_json) const { DriverSettings settings = DriverSettings::make_default(); using json = nlohmann::json; auto json_to_opt = [&](DriverSettings::Setting setting) -> std::optional<json> { if (input_json.find(DriverSettings::getKeyString(setting)) != input_json.end()) { return input_json[DriverSettings::getKeyString(setting)]; } return std::nullopt; }; auto load_setting = [&](DriverSettings::Setting setting, std::function<bool(json)> predicate, std::function<DriverSettings::SettingValue(json)> getter) { auto settingValue = json_to_opt(setting); if (settingValue.has_value()) { if (predicate(*settingValue)) { settings.setValue<DriverSettings::SettingValue>(setting, getter(*settingValue)); } else { settings.setValue<DriverSettings::SettingValue>(setting, DriverSettings::invalid_setting_t()); } } }; load_setting(DriverSettings::AttachGizmo, [](json j) -> bool {return j.is_boolean(); }, [](json j) -> DriverSettings::SettingValue { return j.get<bool>(); }); load_setting(DriverSettings::EnableDetailedLogging, [](json j) -> bool {return j.is_boolean(); }, [](json j) -> DriverSettings::SettingValue {return j.get<bool>(); }); load_setting(DriverSettings::Handedness, [](json j) -> bool {return j.is_string(); }, [](json j) -> DriverSettings::SettingValue {return j.get<std::string>(); }); load_setting(DriverSettings::AutoTrackingRefSerial, [](json j) -> bool {return j.is_string(); }, [](json j) -> DriverSettings::SettingValue {return j.get<std::string>(); }); load_setting(DriverSettings::ForcedTrackingRefSerial, [](json j) -> bool {return j.is_string(); }, [](json j) -> DriverSettings::SettingValue {return j.get<std::string>(); }); return settings; } nlohmann::json FileSettingsLoader::toJson(DriverSettings settings) const { nlohmann::json json; if (settings.isValid(DriverSettings::AttachGizmo) && settings.getValue<bool>(DriverSettings::AttachGizmo).has_value()) { json[DriverSettings::getKeyString(DriverSettings::AttachGizmo)] = *settings.getValue<bool>(DriverSettings::AttachGizmo); } if (settings.isValid(DriverSettings::EnableDetailedLogging) && settings.getValue<bool>(DriverSettings::EnableDetailedLogging).has_value()) { json[DriverSettings::getKeyString(DriverSettings::EnableDetailedLogging)] = *settings.getValue<bool>(DriverSettings::EnableDetailedLogging); } if (settings.isValid(DriverSettings::Handedness) && settings.getValue<std::string>(DriverSettings::Handedness).has_value()) { json[DriverSettings::getKeyString(DriverSettings::Handedness)] = *settings.getValue<std::string>(DriverSettings::Handedness); } if (settings.isValid(DriverSettings::AutoTrackingRefSerial) && settings.getValue<std::string>(DriverSettings::AutoTrackingRefSerial).has_value()) { json[DriverSettings::getKeyString(DriverSettings::AutoTrackingRefSerial)] = *settings.getValue<std::string>(DriverSettings::AutoTrackingRefSerial); } if (settings.isValid(DriverSettings::ForcedTrackingRefSerial) && settings.getValue<std::string>(DriverSettings::ForcedTrackingRefSerial).has_value()) { json[DriverSettings::getKeyString(DriverSettings::ForcedTrackingRefSerial)] = *settings.getValue<std::string>(DriverSettings::ForcedTrackingRefSerial); } return json; }
44.785714
179
0.687879
Massless-io
33ac5b4710cbe8c66d7e312b8c99a3a69e257c9e
835
cpp
C++
Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/MinimalPerspective.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/MinimalPerspective.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/MinimalPerspective.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "MinimalPerspective.h" /// Berry #include "berryIViewLayout.h" MinimalPerspective::MinimalPerspective() { } void MinimalPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { // Editors are placed for free. QString editorAreaId = layout->GetEditorArea(); // Hides the editor area. layout->SetEditorAreaVisible(false); layout->AddView("org.mitk.views.minimalview", berry::IPageLayout::LEFT, 0.5f, editorAreaId); }
26.935484
94
0.619162
zhaomengxiao
33b279c7a50d49b839a9a38ae06959c75def0f6c
3,401
cc
C++
src/tint/reader/wgsl/parser_impl_test.cc
encounter/dawn-cmake
64a23ce0ede5f232cc209b69d64164ede6810b65
[ "Apache-2.0" ]
null
null
null
src/tint/reader/wgsl/parser_impl_test.cc
encounter/dawn-cmake
64a23ce0ede5f232cc209b69d64164ede6810b65
[ "Apache-2.0" ]
null
null
null
src/tint/reader/wgsl/parser_impl_test.cc
encounter/dawn-cmake
64a23ce0ede5f232cc209b69d64164ede6810b65
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Tint Authors. // // 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 "src/tint/reader/wgsl/parser_impl_test_helper.h" namespace tint::reader::wgsl { namespace { TEST_F(ParserImplTest, Empty) { auto p = parser(""); ASSERT_TRUE(p->Parse()) << p->error(); } TEST_F(ParserImplTest, Parses) { auto p = parser(R"( @stage(fragment) fn main() -> @location(0) vec4<f32> { return vec4<f32>(.4, .2, .3, 1); } )"); ASSERT_TRUE(p->Parse()) << p->error(); Program program = p->program(); ASSERT_EQ(1u, program.AST().Functions().size()); } TEST_F(ParserImplTest, Parses_ExtraSemicolons) { auto p = parser(R"( ; struct S { a : f32, };; ; fn foo() -> S { ; return S();;; ; };; ; )"); ASSERT_TRUE(p->Parse()) << p->error(); Program program = p->program(); ASSERT_EQ(1u, program.AST().Functions().size()); ASSERT_EQ(1u, program.AST().TypeDecls().size()); } TEST_F(ParserImplTest, HandlesError) { auto p = parser(R"( fn main() -> { // missing return type return; })"); ASSERT_FALSE(p->Parse()); ASSERT_TRUE(p->has_error()); EXPECT_EQ(p->error(), "2:15: unable to determine function return type"); } TEST_F(ParserImplTest, HandlesUnexpectedToken) { auto p = parser(R"( fn main() { } foobar )"); ASSERT_FALSE(p->Parse()); ASSERT_TRUE(p->has_error()); EXPECT_EQ(p->error(), "4:1: unexpected token"); } TEST_F(ParserImplTest, HandlesBadToken_InMiddle) { auto p = parser(R"( fn main() { let f = 0x1p500000000000; // Exponent too big for hex float return; })"); ASSERT_FALSE(p->Parse()); ASSERT_TRUE(p->has_error()); EXPECT_EQ(p->error(), "3:11: exponent is too large for hex float"); } TEST_F(ParserImplTest, HandlesBadToken_AtModuleScope) { auto p = parser(R"( fn main() { return; } 0x1p5000000000000 )"); ASSERT_FALSE(p->Parse()); ASSERT_TRUE(p->has_error()); EXPECT_EQ(p->error(), "5:1: exponent is too large for hex float"); } TEST_F(ParserImplTest, Comments_TerminatedBlockComment) { auto p = parser(R"( /** * Here is my shader. * * /* I can nest /**/ comments. */ * // I can nest line comments too. **/ @stage(fragment) // This is the stage fn main(/* no parameters */) -> @location(0) vec4<f32> { return/*block_comments_delimit_tokens*/vec4<f32>(.4, .2, .3, 1); }/* block comments are OK at EOF...*/)"); ASSERT_TRUE(p->Parse()) << p->error(); ASSERT_EQ(1u, p->program().AST().Functions().size()); } TEST_F(ParserImplTest, Comments_UnterminatedBlockComment) { auto p = parser(R"( @stage(fragment) fn main() -> @location(0) vec4<f32> { return vec4<f32>(.4, .2, .3, 1); } /* unterminated block comments are invalid ...)"); ASSERT_FALSE(p->Parse()); ASSERT_TRUE(p->has_error()); EXPECT_EQ(p->error(), "5:3: unterminated block comment") << p->error(); } } // namespace } // namespace tint::reader::wgsl
24.120567
76
0.644516
encounter
33b375a446358c034004680c682287c4146f6ac2
48
hpp
C++
src/boost_serialization_split_member.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
11
2015-08-19T23:15:41.000Z
2018-05-15T21:53:28.000Z
src/boost_serialization_split_member.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_serialization_split_member.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
5
2016-10-31T08:02:15.000Z
2018-08-24T07:40:23.000Z
#include <boost/serialization/split_member.hpp>
24
47
0.833333
miathedev
33b381cb6f40a59474e57ca63d53f93ae2ec685e
1,886
cpp
C++
tests/unit/fem/test_intruletypes.cpp
stefanhenneking/mfem
dc4715e03d177233ea0d891f2875324cadb06dc4
[ "BSD-3-Clause" ]
1
2020-08-15T07:00:22.000Z
2020-08-15T07:00:22.000Z
tests/unit/fem/test_intruletypes.cpp
stefanhenneking/mfem
dc4715e03d177233ea0d891f2875324cadb06dc4
[ "BSD-3-Clause" ]
null
null
null
tests/unit/fem/test_intruletypes.cpp
stefanhenneking/mfem
dc4715e03d177233ea0d891f2875324cadb06dc4
[ "BSD-3-Clause" ]
1
2021-09-15T14:14:29.000Z
2021-09-15T14:14:29.000Z
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "mfem.hpp" using namespace mfem; #include "catch.hpp" //You typically want to start by testing things one object at a time. TEST_CASE("IntegrationRules of Different Types", "[IntegrationRules]") { //This code is automatically re-executed for all of the sections. IntegrationRules gauss_intrules(0, Quadrature1D::GaussLegendre); IntegrationRules lobatto_intrules(0, Quadrature1D::GaussLobatto); IntegrationRules oes_intrules(0, Quadrature1D::OpenUniform); IntegrationRules ces_intrules(0, Quadrature1D::ClosedUniform); //The tests will be reported in these sections. //Each REQUIRE counts as an assertion. //true = pass, false = fail SECTION("Expected Number of points for GaussLegendre exactness") { // polynomial degree we want to exactly integrate int exact = 4; // exact for 2*np - 1 int pts_needed = 3; const IntegrationRule *ir; ir = &gauss_intrules.Get(Geometry::SEGMENT, exact); REQUIRE(ir->Size() == pts_needed); } SECTION("Expected Number of points for GaussLobatto exactness") { // polynomial degree we want to exactly integrate int exact = 4; // exact for 2*np - 3 int pts_needed = 4; const IntegrationRule *ir; ir = &lobatto_intrules.Get(Geometry::SEGMENT, exact); REQUIRE(ir->Size() == pts_needed); } }
34.925926
80
0.711029
stefanhenneking
33b43d1dd819e5e3edf84e91d29f9508329532c0
5,377
hpp
C++
include/text_view_detail/codecs/utf32be_codec.hpp
tahonermann/text_view
65740356488d0dd98b65f221c71c7b7377c813de
[ "MIT" ]
144
2015-10-10T10:12:53.000Z
2021-12-31T16:07:27.000Z
include/text_view_detail/codecs/utf32be_codec.hpp
Quuxplusone/text_view
65740356488d0dd98b65f221c71c7b7377c813de
[ "MIT" ]
34
2016-01-22T03:52:53.000Z
2018-08-04T01:56:06.000Z
include/text_view_detail/codecs/utf32be_codec.hpp
Quuxplusone/text_view
65740356488d0dd98b65f221c71c7b7377c813de
[ "MIT" ]
19
2016-02-10T11:29:20.000Z
2021-06-28T11:11:36.000Z
// Copyright (c) 2017, Tom Honermann // // This file is distributed under the MIT License. See the accompanying file // LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms // and conditions. #if !defined(TEXT_VIEW_CODECS_UTF32BE_CODEC_HPP) // { #define TEXT_VIEW_CODECS_UTF32BE_CODEC_HPP #include <climits> #include <cstdint> #include <text_view_detail/codecs/codec_util.hpp> #include <text_view_detail/concepts.hpp> #include <text_view_detail/error_status.hpp> #include <text_view_detail/character.hpp> #include <text_view_detail/trivial_encoding_state.hpp> namespace std { namespace experimental { inline namespace text { namespace text_detail { template<Character CT, CodeUnit CUT> class utf32be_codec { public: using state_type = trivial_encoding_state; using state_transition_type = trivial_encoding_state_transition; using character_type = CT; using code_unit_type = CUT; static constexpr int min_code_units = 4; static constexpr int max_code_units = 4; static_assert(sizeof(code_unit_type) * CHAR_BIT >= 8); template<CodeUnitOutputIterator<code_unit_type> CUIT> static encode_status encode_state_transition( state_type &state, CUIT &out, const state_transition_type &stt, int &encoded_code_units) noexcept { encoded_code_units = 0; return encode_status::no_error; } template<CodeUnitOutputIterator<code_unit_type> CUIT> static encode_status encode( state_type &state, CUIT &out, character_type c, int &encoded_code_units) noexcept(text_detail::NoExceptOutputIterator<CUIT, code_unit_type>()) { encoded_code_units = 0; using code_point_type = code_point_type_t<character_set_type_t<character_type>>; code_point_type cp{c.get_code_point()}; code_unit_type octet1 = (cp >> 24) & 0xFF; code_unit_type octet2 = (cp >> 16) & 0xFF; code_unit_type octet3 = (cp >> 8) & 0xFF; code_unit_type octet4 = (cp >> 0) & 0xFF; *out++ = octet1; ++encoded_code_units; *out++ = octet2; ++encoded_code_units; *out++ = octet3; ++encoded_code_units; *out++ = octet4; ++encoded_code_units; return encode_status::no_error; } template<CodeUnitIterator CUIT, typename CUST> requires ranges::ForwardIterator<CUIT> && ranges::ConvertibleTo<ranges::value_type_t<CUIT>, code_unit_type> && ranges::Sentinel<CUST, CUIT> static decode_status decode( state_type &state, CUIT &in_next, CUST in_end, character_type &c, int &decoded_code_units) noexcept(text_detail::NoExceptInputIterator<CUIT, CUST>()) { decoded_code_units = 0; using code_point_type = code_point_type_t<character_set_type_t<character_type>>; code_point_type cp; if (in_next == in_end) return decode_status::underflow; code_unit_type octet1 = *in_next++; ++decoded_code_units; if (in_next == in_end) return decode_status::underflow; code_unit_type octet2 = *in_next++; ++decoded_code_units; if (in_next == in_end) return decode_status::underflow; code_unit_type octet3 = *in_next++; ++decoded_code_units; if (in_next == in_end) return decode_status::underflow; code_unit_type octet4 = *in_next++; ++decoded_code_units; cp = ((octet1 & 0xFF) << 24) | ((octet2 & 0xFF) << 16) | ((octet3 & 0xFF) << 8) | ((octet4 & 0xFF) << 0); c.set_code_point(cp); return decode_status::no_error; } template<CodeUnitIterator CUIT, typename CUST> requires ranges::ForwardIterator<CUIT> && ranges::ConvertibleTo<ranges::value_type_t<CUIT>, code_unit_type> && ranges::Sentinel<CUST, CUIT> static decode_status rdecode( state_type &state, CUIT &in_next, CUST in_end, character_type &c, int &decoded_code_units) noexcept(text_detail::NoExceptInputIterator<CUIT, CUST>()) { decoded_code_units = 0; using code_point_type = code_point_type_t<character_set_type_t<character_type>>; code_point_type cp; if (in_next == in_end) return decode_status::underflow; code_unit_type roctet1 = *in_next++; ++decoded_code_units; if (in_next == in_end) return decode_status::underflow; code_unit_type roctet2 = *in_next++; ++decoded_code_units; if (in_next == in_end) return decode_status::underflow; code_unit_type roctet3 = *in_next++; ++decoded_code_units; if (in_next == in_end) return decode_status::underflow; code_unit_type roctet4 = *in_next++; ++decoded_code_units; cp = ((roctet4 & 0xFF) << 24) | ((roctet3 & 0xFF) << 16) | ((roctet2 & 0xFF) << 8) | ((roctet1 & 0xFF) << 0); c.set_code_point(cp); return decode_status::no_error; } }; } // namespace text_detail } // inline namespace text } // namespace experimental } // namespace std #endif // } TEXT_VIEW_CODECS_UTF32BE_CODEC_HPP
30.039106
78
0.637344
tahonermann
33b56574e74bf0d863247ce49370b4677d73a9f6
3,423
cpp
C++
sdk_test/fido/flo_test.cpp
uriel1998/wwiv
623cca6862540a5dc4ce355d7966766bf5d0fd0d
[ "Apache-2.0" ]
null
null
null
sdk_test/fido/flo_test.cpp
uriel1998/wwiv
623cca6862540a5dc4ce355d7966766bf5d0fd0d
[ "Apache-2.0" ]
null
null
null
sdk_test/fido/flo_test.cpp
uriel1998/wwiv
623cca6862540a5dc4ce355d7966766bf5d0fd0d
[ "Apache-2.0" ]
null
null
null
/**************************************************************************/ /* */ /* WWIV Version 5.x */ /* Copyright (C)2016-2020, WWIV Software Services */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, */ /* software distributed under the License is distributed on an */ /* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, */ /* either express or implied. See the License for the specific */ /* language governing permissions and limitations under the License. */ /**************************************************************************/ #include "core/datetime.h" #include "core/file.h" #include "core/stl.h" #include "core/strings.h" #include "core/textfile.h" #include "core_test/file_helper.h" #include "sdk/fido/flo_file.h" #include "gtest/gtest.h" #include <ctime> #include <memory> #include <string> using std::endl; using std::string; using std::unique_ptr; using namespace wwiv::core; using namespace wwiv::strings; using namespace wwiv::sdk::fido; class FloTest : public testing::Test { public: FloTest() { net.dir = helper_.TempDir().string(); net.fido.fido_address = "11:1/211"; p = helper_.CreateTempFile("00010064.flo", "^C:\\db\\outbound\\0000006f.su0"); } protected: FileHelper helper_; net_networks_rec net{}; std::filesystem::path p{}; }; TEST_F(FloTest, FloFile_Exists) { { const FloFile flo(net, p); ASSERT_TRUE(flo.exists()); } { p.replace_filename("00010063.flo"); const FloFile flo(net, p); ASSERT_FALSE(flo.exists()); } } TEST_F(FloTest, FloFile_Smoke) { FloFile flo(net, p); EXPECT_FALSE(flo.poll()); ASSERT_EQ(1, wwiv::stl::ssize(flo.flo_entries())); { auto e = flo.flo_entries().front(); EXPECT_EQ("C:\\db\\outbound\\0000006f.su0", e.first); EXPECT_EQ(flo_directive::delete_file, e.second); EXPECT_TRUE(flo.clear()); EXPECT_TRUE(flo.empty()); EXPECT_TRUE(flo.Save()); EXPECT_FALSE(File::Exists(p)) << p; } EXPECT_TRUE(flo.insert("C:\\db\\outbound\\0000006f.mo0", flo_directive::truncate_file)); { auto e = flo.flo_entries().front(); EXPECT_EQ("C:\\db\\outbound\\0000006f.mo0", e.first); EXPECT_EQ(flo_directive::truncate_file, e.second); flo.Save(); EXPECT_TRUE(File::Exists(p)); EXPECT_TRUE(flo.clear()); File::Remove(p); } { flo.set_poll(true); flo.Save(); EXPECT_TRUE(File::Exists(p)); TextFile tf(p, "r"); const auto contents = tf.ReadFileIntoString(); EXPECT_EQ("", contents); } } TEST_F(FloTest, Poll) { FloFile flo(net, p); ASSERT_FALSE(flo.poll()); flo.set_poll(true); ASSERT_TRUE(flo.poll()); flo.set_poll(false); ASSERT_FALSE(flo.poll()); }
31.40367
90
0.543091
uriel1998
33b5666d92685a07477a8bcc80ae15af1cd3cc99
8,014
cpp
C++
src/Core/x/xCollide.cpp
stravant/bfbbdecomp
2126be355a6bb8171b850f829c1f2731c8b5de08
[ "OLDAP-2.7" ]
1
2021-01-05T11:28:55.000Z
2021-01-05T11:28:55.000Z
src/Core/x/xCollide.cpp
sonich2401/bfbbdecomp
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
[ "OLDAP-2.7" ]
null
null
null
src/Core/x/xCollide.cpp
sonich2401/bfbbdecomp
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
[ "OLDAP-2.7" ]
1
2022-03-30T15:15:08.000Z
2022-03-30T15:15:08.000Z
#include "xCollide.h" #include <types.h> // func_8000F058 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xCollideGetCollsIdx__FPC7xCollisPC5xVec3PC7xMat3x3") // func_8000F1C8 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xCollideInit__FP6xScene") // func_8000F1E8 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsSphere__FPC7xSpherePC7xSphereP7xCollis") // func_8000F350 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsBox__FPC7xSpherePC4xBoxP7xCollis") // func_8000F474 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsOBB_nu__FPC7xSpherePC4xBoxPC7xMat4x3P7xCollis") // func_8000F830 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "sphereHitsModelCB__FP14RpIntersectionP19RpCollisionTrianglefPv") // func_8000F864 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsModel__FPC7xSpherePC14xModelInstanceP7xCollis") // func_8000FA50 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xParabolaRecenter__FP9xParabolaf") // func_8000FAD4 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xParabolaEnvCB__FP21xClumpCollBSPTrianglePv") // func_8000FFE8 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xParabolaHitsEnv__FP9xParabolaPC4xEnvP7xCollis") // func_80010228 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "__as__5RwV3dFRC5RwV3d") // func_80010244 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "__as__6RwBBoxFRC6RwBBox") // func_80010278 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "__as__7xCollisFRC7xCollis") // func_8001031C #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xBoxHitsSphere__FPC4xBoxPC7xSphereP7xCollis") // func_80010434 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "Mgc_BoxBoxTest__FPC4xBoxPC7xMat4x3PC4xBoxPC7xMat4x3") // func_80010ED8 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xBoxHitsObb__FPC4xBoxPC4xBoxPC7xMat4x3P7xCollis") // func_80010F48 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xCollideCalcTri__FRQ27xCollis8tri_dataRC14xModelInstanceRC5xVec3RC5xVec3") // func_800114F4 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "render_tri__22_esc__2_unnamed_esc__2_xCollide_cpp_esc__2_FRQ27xCollis8tri_dataRC14xModelInstance") // func_800114F8 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xCollisTriHit__FRCQ27xCollis8tri_dataRC14xModelInstance") // func_80011774 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "_rpCollBSPTreeForAllCapsuleLeafNodeIntersections__FP13RpCollBSPTreeP6RwLinefP13RpV3dGradientPFiiPv_iPv") // func_80011F1C #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "__as__8nodeInfoFRC8nodeInfo") // func_80011F30 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "__as__6RwLineFRC6RwLine") // func_80011F64 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSweptSpherePrepare__FP12xSweptSphereP5xVec3P5xVec3f") // func_800121A0 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSweptSphereGetResults__FP12xSweptSphere") // func_8001232C #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSweptSphereToTriangle__FP12xSweptSphereP5xVec3P5xVec3P5xVec3") // func_80012B58 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xsqrtfast__FRff") // func_80012B88 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "sqrtf__3stdFf") // func_80012BEC #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSweptSphereToSphere__FP12xSweptSphereP7xSphere") // func_80012D28 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSweptSphereToBox__FP12xSweptSphereP4xBoxP7xMat4x3") // func_800136B8 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "SweptSphereHitsEnvCB__FP14RpIntersectionP13RpWorldSectorP19RpCollisionTrianglefPv") // func_80013740 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "SweptSphereLeafNodeCB__FP21xClumpCollBSPTrianglePv") // func_800137E8 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSweptSphereToEnv__FP12xSweptSphereP4xEnv") // func_80013960 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "SweptSphereModelCB__FiiPv") // func_80013A20 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSweptSphereToModel__FP12xSweptSphereP8RpAtomicP11RwMatrixTag") // func_80013CB4 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "SweptSphereHitsEntCB__FP6xSceneP5xRay3P7xQCDataP4xEntPv") // func_80014088 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSweptSphereToScene__FP12xSweptSphereP6xSceneP4xEntUc") // func_80014204 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSweptSphereToStatDyn__FP12xSweptSphereP6xSceneP4xEntUc") // func_8001432C #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSweptSphereToNPC__FP12xSweptSphereP6xSceneP4xEntUc") // func_80014430 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSweptSphereToNonMoving__FP12xSweptSphereP6xSceneP4xEntUc") // func_80014594 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsCapsule__FRC5xVec3fRC5xVec3RC5xVec3f") // func_80014710 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsBound__FRC7xSphereRC6xBound") // func_80014784 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xOBBHitsOBB__FRC4xBoxRC7xMat4x3RC4xBoxRC7xMat4x3") // func_80014E14 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsVCylinder__FRC5xVec3fRC5xVec3ff") // func_80014F50 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsVCircle__FRC5xVec3fRC5xVec3f") // func_80015058 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xVec3AddScaled__FP5xVec3PC5xVec3f") // func_8001508C #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xVec3Cross__FP5xVec3PC5xVec3PC5xVec3") // func_800150CC #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xVec3Length2__FPC5xVec3") // func_800150F0 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xVec3Dist__FPC5xVec3PC5xVec3") // func_80015140 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xMat3x3RMulVec__FP5xVec3PC7xMat3x3PC5xVec3") // func_800151A4 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xMat4x3OrthoInv__FP7xMat4x3PC7xMat4x3") // func_800151F8 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xMat3x3LookVec3__FR7xMat3x3RC5xVec3") // func_80015348 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xModelAnimCollRestore__FRC14xModelInstance") // func_80015368 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xModelAnimCollApply__FRC14xModelInstance") // func_800153C8 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xModelAnimCollDirty__FRC14xModelInstance") // func_800153E0 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "__pl__5xVec3CFRC5xVec3") // func_80015444 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "__apl__5xVec3FRC5xVec3") // func_80015478 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "get_abs__5xVec3CFv") // func_800154D8 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "set_abs__5xVec3Fv") // func_8001550C #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "dot__5xVec3CFRC5xVec3") // func_80015534 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "cross__5xVec3CFRC5xVec3") // func_800155B0 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "normalize__5xVec3Fv") // func_800155E8 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "__dv__5xVec3CFf") // func_80015648 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xParabolaEvalVel__FPC9xParabolaP5xVec3f") // func_800156AC #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xParabolaEvalPos__FPC9xParabolaP5xVec3f") // func_8001572C #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsOBB__FRC7xSphereRC4xBoxRC7xMat4x3") // func_80015750 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsOBB__FRC5xVec3fRC4xBoxRC7xMat4x3") // func_800157A4 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsBox__FRC5xVec3fRC4xBox") // func_80015838 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsBox__FRC7xSphereRC4xBox") // func_8001585C #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsSphere__FRC7xSphereRC7xSphere") // func_80015884 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xSphereHitsSphere__FRC5xVec3fRC5xVec3f") // func_800158F4 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xQuickCullForRay__FP7xQCDataPC5xRay3") // func_80015928 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "xQuickCullForBox__FP7xQCDataPC4xBox") // func_8001595C #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "length2__5xVec2CFv") // func_80015974 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "__mi__5xVec2CFRC5xVec2") // func_800159B0 #pragma GLOBAL_ASM("asm/Core/x/xCollide.s", "__ami__5xVec2FRC5xVec2")
34.995633
149
0.811205
stravant
33b6d09cf8896466edbc3f8c25c443502bb4abfc
10,270
cpp
C++
Public/Src/Sandbox/MacOs/Sandbox/Src/ConcurrentSharedDataQueue.cpp
miniksa/BuildXL
4dc257a82a6126fe7516f15fa6f505c14c122ffb
[ "MIT" ]
448
2018-11-07T21:00:58.000Z
2019-05-06T17:29:34.000Z
Public/Src/Sandbox/MacOs/Sandbox/Src/ConcurrentSharedDataQueue.cpp
miniksa/BuildXL
4dc257a82a6126fe7516f15fa6f505c14c122ffb
[ "MIT" ]
496
2019-05-06T21:38:22.000Z
2022-03-14T18:17:14.000Z
Public/Src/Sandbox/MacOs/Sandbox/Src/ConcurrentSharedDataQueue.cpp
miniksa/BuildXL
4dc257a82a6126fe7516f15fa6f505c14c122ffb
[ "MIT" ]
88
2019-05-08T08:28:45.000Z
2022-03-24T23:43:21.000Z
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <IOKit/IOMemoryDescriptor.h> #include <IOKit/IODataQueueShared.h> #include "Alloc.hpp" #include "BuildXLSandboxClient.hpp" #include "ConcurrentSharedDataQueue.hpp" #define super OSObject OSDefineMetaClassAndStructors(ConcurrentSharedDataQueue, OSObject) typedef ConcurrentSharedDataQueue::ElemPayload ElemPayload; static ElemPayload* getValue(QueueElem *e) { return (ElemPayload*)LFDS711_QUEUE_UMM_GET_VALUE_FROM_ELEMENT(*e); } static void setValue(QueueElem *e, ElemPayload *p) { LFDS711_QUEUE_UMM_SET_VALUE_IN_ELEMENT(*e, p); } static ElemPayload* getValue(FreeListElem *e) { return (ElemPayload*)LFDS711_FREELIST_GET_VALUE_FROM_ELEMENT(*e); } static void setValue(FreeListElem *e, ElemPayload *p) { LFDS711_FREELIST_SET_VALUE_IN_ELEMENT(*e, p); } static void deallocateFreeListElem(FreeListElem *elem) { ElemPayload *payload = getValue(elem); Alloc::Delete<QueueElem>(payload->queueElem, 1); Alloc::Delete<ElemPayload>(payload, 1); } QueueElem* ConcurrentSharedDataQueue::allocateElem(const EnqueueArgs &args) { // try and get an element from the free list ElemPayload *payload = nullptr; FreeListElem *elem = nullptr; bool found = lfds711_freelist_pop(freeList_, &elem, nullptr); if (found) { payload = getValue(elem); } else { reportCounters_->freeListNodeCount++; payload = Alloc::New<ElemPayload>(1); if (payload == nullptr) { return nullptr; } payload->queueElem = Alloc::New<QueueElem>(1); if (payload->queueElem == nullptr) { Alloc::Delete<ElemPayload>(payload, 1); return nullptr; } setValue(&payload->freeListElem, payload); } // make sure the queue element is pointing to this payload setValue(payload->queueElem, payload); // set the actual payload bytes payload->report = args.report; payload->cacheRecord = args.cacheRecord; if (payload->cacheRecord) { payload->cacheRecord->retain(); } return payload->queueElem; } void ConcurrentSharedDataQueue::releaseElem(QueueElem *elem) { ElemPayload *payload = getValue(elem); payload->queueElem = elem; OSSafeReleaseNULL(payload->cacheRecord); lfds711_freelist_push(freeList_, &payload->freeListElem, nullptr); } ConcurrentSharedDataQueue* ConcurrentSharedDataQueue::create(const InitArgs& args) { auto *instance = new ConcurrentSharedDataQueue; if (instance) { bool initialized = instance->init(args); if (!initialized) { instance->release(); instance = nullptr; } } if (!instance) { log_error("Failed to initialize shared data queue with %d entries of size %d", args.entryCount, args.entrySize); } return instance; } bool ConcurrentSharedDataQueue::init(const InitArgs& args) { if (!super::init()) { return false; } drainingDone_ = false; unrecoverableFailureOccurred_ = false; reportCounters_ = args.counters; enableBatching_ = args.enableBatching; lock_ = BXLRecursiveLockAlloc(); if (lock_ == nullptr) { return false; } queue_ = IOSharedDataQueue::withCapacity((args.entrySize + DATA_QUEUE_ENTRY_HEADER_SIZE) * args.entryCount); if (queue_ == nullptr) { return false; } freeList_ = Alloc::New<FreeList>(1); if (freeList_ == nullptr) { return false; } pendingReports_ = Alloc::New<Queue>(1); if (pendingReports_ == nullptr) { return false; } QueueElem *dummy = Alloc::New<QueueElem>(1); // this is dealocated in lfds711_queue_umm_cleanup() if (dummy == nullptr) { return false; } // init lock-free queue and free list lfds711_queue_umm_init_valid_on_current_logical_core(pendingReports_, dummy, nullptr); lfds711_freelist_init_valid_on_current_logical_core(freeList_, nullptr, 0, nullptr); // init consumer thread consumerThread_ = Thread::create(this, [](void *me, wait_result_t result) { static_cast<ConcurrentSharedDataQueue*>(me)->drainQueue(); }); if (consumerThread_ == nullptr) { return false; } // start the consumer thread consumerThread_->start(); // These resources are released on the client side asyncFailureHandle_ = nullptr; return true; } void ConcurrentSharedDataQueue::free() { drainingDone_ = true; // wait for consumer thread to finish if (consumerThread_ != nullptr) { consumerThread_->join(); } LFDS711_MISC_MAKE_VALID_ON_CURRENT_LOGICAL_CORE_INITS_COMPLETED_BEFORE_NOW_ON_ANY_OTHER_LOGICAL_CORE; // purge any left over elements in the queue (can happen if the client exits abnormally) if (pendingReports_ != nullptr) { QueueElem *e; while (lfds711_queue_umm_dequeue(pendingReports_, &e)) releaseElem(e); lfds711_queue_umm_cleanup(pendingReports_, [](Queue *q, QueueElem *e, lfds711_misc_flag flag) { Alloc::Delete<QueueElem>(e, 1); }); Alloc::Delete<Queue>(pendingReports_, 1); pendingReports_ = nullptr; } // cleanup free list if (freeList_ != nullptr) { lfds711_freelist_cleanup(freeList_, [](FreeList *l, FreeListElem *e) { deallocateFreeListElem(e); }); Alloc::Delete<FreeList>(freeList_, 1); freeList_ = nullptr; } if (asyncFailureHandle_ != nullptr) { asyncFailureHandle_->userClient = nullptr; Alloc::Delete<ClientAsyncHandle>(asyncFailureHandle_, 1); asyncFailureHandle_ = nullptr; } if (lock_ != nullptr) { BXLRecursiveLockFree(lock_); lock_ = nullptr; } OSSafeReleaseNULL(consumerThread_); OSSafeReleaseNULL(queue_); super::free(); } long long ConcurrentSharedDataQueue::getCount() const { LFDS711_MISC_MAKE_VALID_ON_CURRENT_LOGICAL_CORE_INITS_COMPLETED_BEFORE_NOW_ON_ANY_OTHER_LOGICAL_CORE; long long count; lfds711_queue_umm_query(pendingReports_, LFDS711_QUEUE_UMM_QUERY_SINGLETHREADED_GET_COUNT, NULL, &count); return count; } void ConcurrentSharedDataQueue::setNotificationPort(mach_port_t port) { EnterMonitor queue_->setNotificationPort(port); } IOMemoryDescriptor* ConcurrentSharedDataQueue::getMemoryDescriptor() { EnterMonitor return queue_->getMemoryDescriptor(); } void ConcurrentSharedDataQueue::setClientAsyncFailureHandle(OSAsyncReference64 ref, OSObject* client) { EnterMonitor asyncFailureHandle_ = Alloc::New<ClientAsyncHandle>(1); if (asyncFailureHandle_ != nullptr) { bcopy(ref, asyncFailureHandle_->ref, sizeof(OSAsyncReference64)); asyncFailureHandle_->userClient = client; } } IOReturn ConcurrentSharedDataQueue::InvokeAsyncFailureHandle(IOReturn status) { EnterMonitor if (asyncFailureHandle_ != nullptr) { BuildXLSandboxClient *client = OSDynamicCast(BuildXLSandboxClient, asyncFailureHandle_->userClient); return client->SendAsyncResult(asyncFailureHandle_->ref, status); } return kIOReturnError; } bool ConcurrentSharedDataQueue::enqueueReport(const EnqueueArgs &args) { if (unrecoverableFailureOccurred_) { return false; } return enableBatching_ ? enqueueWithBatching(args) : enqueueWithLocking(args); } bool ConcurrentSharedDataQueue::enqueueWithLocking(const EnqueueArgs &args) { EnterMonitor return sendReport(args.report); } bool ConcurrentSharedDataQueue::sendReport(const AccessReport &report) { bool sent = queue_->enqueue((void*)&report, sizeof(AccessReport)); if (!sent) { log_error("Could not send data to shared queue from TID(%lld)", thread_tid(current_thread())); drainingDone_ = true; unrecoverableFailureOccurred_ = true; InvokeAsyncFailureHandle(kIOReturnNoMemory); } else { reportCounters_->totalNumSent++; } return sent; } bool ConcurrentSharedDataQueue::enqueueWithBatching(const EnqueueArgs &args) { LFDS711_MISC_MAKE_VALID_ON_CURRENT_LOGICAL_CORE_INITS_COMPLETED_BEFORE_NOW_ON_ANY_OTHER_LOGICAL_CORE; QueueElem *elem = allocateElem(args); if (elem == nullptr) { return false; } lfds711_queue_umm_enqueue(pendingReports_, elem); reportCounters_->numQueued++; return true; } static uint s_backoffIntervalsMs[] = {1, 2, 4, 8, 16, 32, 64}; static uint s_backoffIntervalsLen = sizeof(s_backoffIntervalsMs) / sizeof(s_backoffIntervalsMs[0]); void ConcurrentSharedDataQueue::drainQueue() { if (!enableBatching_) { return; } LFDS711_MISC_MAKE_VALID_ON_CURRENT_LOGICAL_CORE_INITS_COMPLETED_BEFORE_NOW_ON_ANY_OTHER_LOGICAL_CORE; uint backoffCounter = 0; while (!drainingDone_) { QueueElem *elem; if (!lfds711_queue_umm_dequeue(pendingReports_, &elem) || elem == nullptr) { uint backoffIndex = backoffCounter < s_backoffIntervalsLen ? backoffCounter : s_backoffIntervalsLen - 1; IOSleep(/*milliseconds*/ s_backoffIntervalsMs[backoffIndex]); ++backoffCounter; continue; } backoffCounter = 0; reportCounters_->numQueued--; ElemPayload *payload = getValue(elem); if (payload->cacheRecord == nullptr) { sendReport(payload->report); } else if (payload->cacheRecord->HasStrongerRequestedAccess((RequestedAccess)payload->report.requestedAccess)) { reportCounters_->numCoalescedReports++; } else { sendReport(payload->report); } releaseElem(elem); } }
27.831978
124
0.660662
miniksa
33b73db389d1ffd56d79febcb223f7f59de32bf6
27,566
cc
C++
protri.cc
bjbuckman/galprop_bb_
076b168f7475b3ba9fb198b6ec2df7be66b1763c
[ "MIT" ]
null
null
null
protri.cc
bjbuckman/galprop_bb_
076b168f7475b3ba9fb198b6ec2df7be66b1763c
[ "MIT" ]
null
null
null
protri.cc
bjbuckman/galprop_bb_
076b168f7475b3ba9fb198b6ec2df7be66b1763c
[ "MIT" ]
null
null
null
//**.****|****.****|****.****|****.****|****.****|****.****|****.****|****.****| // * protri.cc * galprop package * 3/25/2002 //**"****!****"****!****"****!****"****!****"****!****"****!****"****!****"****| using namespace std;//AWS20050624 #include"galprop_classes.h" #include"galprop_internal.h" /* extern "C" int tridag_ext ( double*, double*, double*, double*, double*,int,int); extern "C" int tridag_sym_ext( double*, double*, double*, double*, double*,int,int); */ //Gulli20070810 Changed from float to double int tridag_ext ( double*, double*, double*, double*, double*,int,int); int tridag_sym_ext( double*, double*, double*, double*, double*,int,int); #define NMAX 4000000 /* double Nx1[NMAX],Nx2[NMAX],Nx3[NMAX],Nx0[NMAX],Rx[NMAX]; double Ny1[NMAX],Ny2[NMAX],Ny3[NMAX],Ny0[NMAX],Ry[NMAX]; double Nz1[NMAX],Nz2[NMAX],Nz3[NMAX],Nz0[NMAX],Rz[NMAX]; double Np1[NMAX],Np2[NMAX],Np3[NMAX],Np0[NMAX],Rp[NMAX]; double alpha1_xx[NMAX],alpha1_yy[NMAX],alpha1_zz[NMAX],alpha1_pp[NMAX]; double alpha2_xx[NMAX],alpha2_yy[NMAX],alpha2_zz[NMAX],alpha2_pp[NMAX]; double alpha3_xx[NMAX],alpha3_yy[NMAX],alpha3_zz[NMAX],alpha3_pp[NMAX]; double alpha1_x0[NMAX],alpha1_y0[NMAX],alpha1_z0[NMAX]; double total_source_function_x[NMAX]; double total_source_function_y[NMAX]; double total_source_function_z[NMAX]; double total_source_function_p[NMAX]; */ double *Nx1 ,*Nx2 ,*Nx3 ,*Nx0 ,*Rx ; double *Ny1 ,*Ny2 ,*Ny3 ,*Ny0 ,*Ry ; double *Nz1 ,*Nz2 ,*Nz3 ,*Nz0 ,*Rz ; double *Np1 ,*Np2 ,*Np3 ,*Np0 ,*Rp ; double *alpha1_xx ,*alpha1_yy ,*alpha1_zz ,*alpha1_pp ; double *alpha2_xx ,*alpha2_yy ,*alpha2_zz ,*alpha2_pp ; double *alpha3_xx ,*alpha3_yy ,*alpha3_zz ,*alpha3_pp ; double *alpha1_x0 ,*alpha1_y0 ,*alpha1_z0 ; float *total_source_function_x ; float *total_source_function_y ; float *total_source_function_z ; float *total_source_function_p ; int protri_init=0; ///////////////////////////////////////////////////////////////// void Galprop::protri(Particle &particle, Distribution &alpha1_x,Distribution &alpha1_y,Distribution &alpha1_z,Distribution &alpha1_p, Distribution &alpha2_x,Distribution &alpha2_y,Distribution &alpha2_z,Distribution &alpha2_p, Distribution &alpha3_x,Distribution &alpha3_y,Distribution &alpha3_z,Distribution &alpha3_p, Distribution &Nx1_, Distribution &Ny1_, Distribution &Nz1_, Distribution &Np1_, Distribution &Nx2_, Distribution &Ny2_, Distribution &Nz2_, Distribution &Np2_, Distribution &Nx3_, Distribution &Ny3_, Distribution &Nz3_, Distribution &Np3_, Distribution &total_source_function, double dt, int nrept_outer ,double f_use ) { double t; int ix,iy,iz,ip; int nk; // number of vectors to solve in tridag_ext int kk; // basic array index as in tridag_ext int kk1;// kk+1 int nkt; //total number of elements in array int i,k,ns;//counters, stride int irept_outer ; // for outer loop int irept,nrept; // for inner loops within protri nrept=1; cout<<">>protri"<<endl; nkt=particle.n_xgrid*particle.n_ygrid*particle.n_zgrid*particle.n_pgrid; cout<<" nkt="<<nkt<<endl; // if (protri_init==0){ //Gulli20070810 cout<<" Assigning arrays with dimension="<<nkt<<endl; protri_init=1; Nx1=new double[nkt]; Nx2=new double[nkt]; Nx3=new double[nkt]; Nx0=new double[nkt]; Rx=new double[nkt]; Ny1=new double[nkt]; Ny2=new double[nkt]; Ny3=new double[nkt]; Ny0=new double[nkt]; Ry=new double[nkt]; Nz1=new double[nkt]; Nz2=new double[nkt]; Nz3=new double[nkt]; Nz0=new double[nkt]; Rz=new double[nkt]; Np1=new double[nkt]; Np2=new double[nkt]; Np3=new double[nkt]; Np0=new double[nkt]; Rp=new double[nkt]; alpha1_xx=new double[nkt]; alpha1_yy=new double[nkt]; alpha1_zz=new double[nkt]; alpha1_pp=new double[nkt]; alpha2_xx=new double[nkt]; alpha2_yy=new double[nkt]; alpha2_zz=new double[nkt]; alpha2_pp=new double[nkt]; alpha3_xx=new double[nkt]; alpha3_yy=new double[nkt]; alpha3_zz=new double[nkt]; alpha3_pp=new double[nkt]; alpha1_x0=new double[nkt]; alpha1_y0=new double[nkt]; alpha1_z0=new double[nkt]; total_source_function_x=new float[nkt]; total_source_function_y=new float[nkt]; total_source_function_z=new float[nkt]; total_source_function_p=new float[nkt]; // }//protri_init==0 // X propagation if(galdef.prop_x==1) { kk=0; for(ip=0; ip<particle.n_pgrid; ip++) { for(iz=0; iz<particle.n_zgrid; iz++) { for(iy=0; iy<particle.n_ygrid; iy++) { // if(galdef.use_symmetry<=1||(iy<=n_ygrid_sym && iz<=n_zgrid_sym)) // { for(ix=0; ix<particle.n_xgrid; ix++,kk++) { Nx1[kk] = Nx1_.d3[ix][iy][iz].s[ip]; Nx2[kk] = Nx2_.d3[ix][iy][iz].s[ip]; Nx3[kk] = Nx3_.d3[ix][iy][iz].s[ip]; alpha1_xx[kk]=alpha1_x.d3[ix][iy][iz].s[ip]; alpha2_xx[kk]=alpha2_x.d3[ix][iy][iz].s[ip]; alpha3_xx[kk]=alpha3_x.d3[ix][iy][iz].s[ip]; total_source_function_x[kk]= total_source_function.d3[ix][iy][iz].s[ip]; Rx[kk]=particle.cr_density.d3[ix][iy][iz].s[ip]; } // } //symmetry } //iy } //iz } //ip nk=particle.n_pgrid*particle.n_zgrid*particle.n_ygrid; // if symmetry, alpha1_xx at ix=0 is needed so copy it first if (galdef.use_symmetry==1) for(kk=0 ; kk<nkt; kk+=particle.n_xgrid)alpha1_x0[kk]=alpha1_xx[kk]; // zero coefficients to enable loops to be vectorized for(kk=0 ; kk<nkt; kk+=particle.n_xgrid)alpha1_xx[kk]=0.; for(kk=particle.n_xgrid-1; kk<nkt; kk+=particle.n_xgrid)alpha3_xx[kk]=0.; }//galdef.prop_x==1 // Y propagation if(galdef.prop_y==1) { kk=0; for(ix=0; ix<particle.n_xgrid; ix++) { for(ip=0; ip<particle.n_pgrid; ip++) { for(iz=0; iz<particle.n_zgrid; iz++) { // if(galdef.use_symmetry<=1 || (iz<=n_zgrid_sym && ix<=n_xgrid_sym)) // { for(iy=0; iy<particle.n_ygrid; iy++,kk++) { Ny1[kk] = Ny1_.d3[ix][iy][iz].s[ip]; Ny2[kk] = Ny2_.d3[ix][iy][iz].s[ip]; Ny3[kk] = Ny3_.d3[ix][iy][iz].s[ip]; alpha1_yy[kk]=alpha1_y.d3[ix][iy][iz].s[ip]; alpha2_yy[kk]=alpha2_y.d3[ix][iy][iz].s[ip]; alpha3_yy[kk]=alpha3_y.d3[ix][iy][iz].s[ip]; total_source_function_y[kk]= total_source_function.d3[ix][iy][iz].s[ip]; Ry[kk]=particle.cr_density.d3[ix][iy][iz].s[ip]; } // } // symmetry } // iz } // ip } // ix nk=particle.n_pgrid*particle.n_zgrid*particle.n_xgrid; // if symmetry, alpha1_yy at iy=0 is needed so copy it first if (galdef.use_symmetry==1) for(kk=0 ; kk<nkt; kk+=particle.n_ygrid)alpha1_y0[kk]=alpha1_yy[kk]; // zero coefficients to enable loops to be vectorized for(kk=0 ; kk<nkt; kk+=particle.n_ygrid)alpha1_yy[kk]=0.; for(kk=particle.n_ygrid-1; kk<nkt; kk+=particle.n_ygrid)alpha3_yy[kk]=0.; }//galdef.prop_y==1 // Z propagation if(galdef.prop_z==1) { kk=0; for(iy=0; iy<particle.n_ygrid; iy++) { for(ix=0; ix<particle.n_xgrid; ix++) { for(ip=0; ip<particle.n_pgrid; ip++) { // if(galdef.use_symmetry<=1 || (ix<=n_xgrid_sym && iy<=n_ygrid_sym)) // { for(iz=0; iz<particle.n_zgrid; iz++,kk++) { Nz1[kk]=Nz1_.d3[ix][iy][iz].s[ip]; Nz2[kk]=Nz2_.d3[ix][iy][iz].s[ip]; Nz3[kk]=Nz3_.d3[ix][iy][iz].s[ip]; alpha1_zz[kk]=alpha1_z.d3[ix][iy][iz].s[ip]; alpha2_zz[kk]=alpha2_z.d3[ix][iy][iz].s[ip]; alpha3_zz[kk]=alpha3_z.d3[ix][iy][iz].s[ip]; total_source_function_z[kk]= total_source_function.d3[ix][iy][iz].s[ip]; Rz[kk]=particle.cr_density.d3[ix][iy][iz].s[ip]; } // } // symmetry } // ip } // ix } // iy nk=particle.n_pgrid*particle.n_xgrid*particle.n_ygrid; // if symmetry, alpha1_zz at iz=0 is needed so copy it first if (galdef.use_symmetry==1) for(kk=0 ; kk<nkt; kk+=particle.n_zgrid)alpha1_z0[kk]=alpha1_zz[kk]; // zero coefficients to enable loops to be vectorized for(kk=0 ; kk<nkt; kk+=particle.n_zgrid)alpha1_zz[kk]=0.; for(kk=particle.n_zgrid-1; kk<nkt; kk+=particle.n_zgrid)alpha3_zz[kk]=0.; }//galdef.prop_z==1 // P propagation if(galdef.prop_p==1) { kk=0; for(iz=0; iz<particle.n_zgrid; iz++) { for(iy=0; iy<particle.n_ygrid; iy++) { for(ix=0; ix<particle.n_xgrid; ix++) { // if(galdef.use_symmetry<=1 || (ix<=n_xgrid_sym && iy<=n_ygrid_sym && iz<=n_zgrid_sym)) // { for(ip=0; ip<particle.n_pgrid; ip++,kk++) { Np1[kk]=Np1_.d3[ix][iy][iz].s[ip]; Np2[kk]=Np2_.d3[ix][iy][iz].s[ip]; Np3[kk]=Np3_.d3[ix][iy][iz].s[ip]; alpha1_pp[kk]=alpha1_p.d3[ix][iy][iz].s[ip]; alpha2_pp[kk]=alpha2_p.d3[ix][iy][iz].s[ip]; alpha3_pp[kk]=alpha3_p.d3[ix][iy][iz].s[ip]; total_source_function_p[kk]= total_source_function.d3[ix][iy][iz].s[ip]; Rp[kk]=particle.cr_density.d3[ix][iy][iz].s[ip]; } // } // symmetry } // ix } // iy } // iz nk=particle.n_xgrid*particle.n_ygrid*particle.n_zgrid; // zero coefficients to enable loops to be vectorized for(kk=0 ; kk<nkt; kk+=particle.n_pgrid)alpha1_pp[kk]=0.; for(kk=particle.n_pgrid-1; kk<nkt; kk+=particle.n_pgrid)alpha3_pp[kk]=0.; }// galdef.prop_p==1 //--------------------------------------------------------------------------------------------------- // end of setup phase // ------------------------------------------------------------------------------------------- t = 0.0; for (irept_outer=0; irept_outer<nrept_outer; irept_outer++) { t+=dt; cout<<" irept_outer="<<irept_outer<<" t="<<t<<endl; //#pragma vdir nodep for(kk=0; kk<nkt; kk++)total_source_function_x[kk]=0.0; // zero here to vectorize source_SNR_event_vec(particle, t/year2sec, total_source_function_x); // X propagation if(galdef.prop_x==1) { /* kk=0; for(ip=0; ip<particle.n_pgrid; ip++) { for(iz=0; iz<particle.n_zgrid; iz++) { for(iy=0; iy<particle.n_ygrid; iy++) { // if(galdef.use_symmetry<=1||(iy<=n_ygrid_sym && iz<=n_zgrid_sym)) // { for(ix=0; ix<particle.n_xgrid; ix++, kk++){ total_source_function_[kk]= total_source_function.d3[ix][iy][iz].s[ip]; } // } //symmetry } //iy } //iz } //ip */ nk=particle.n_pgrid*particle.n_zgrid*particle.n_ygrid; for(irept=0; irept<nrept; irept++) { //cout<<irept<<endl; //#pragma vdir nodep for(kk=1; kk<nkt-1; kk++) Nx0[kk] = total_source_function_x[kk]*dt/f_use; //#pragma vdir nodep for(kk=1; kk<nkt-1; kk++) Nx0[kk]+= (1.0-0.5*alpha2_xx[kk])*Rx[kk]; //#pragma vdir nodep for(kk=1; kk<nkt-1; kk++) Nx0[kk]+= 0.5*alpha1_xx[kk] *Rx[kk-1]; //#pragma vdir nodep for(kk=1,kk1=2; kk<nkt-1; kk++,kk1++) Nx0[kk]+= 0.5*alpha3_xx[kk] *Rx[kk1]; kk=0; Nx0[kk] = total_source_function_x[kk]*dt/f_use; Nx0[kk]+= (1.0-0.5*alpha2_xx[kk])*Rx[kk]; Nx0[kk]+= 0.5*alpha3_xx[kk] *Rx[kk+1]; kk=nkt-1; Nx0[kk] = total_source_function_x[kk]*dt/f_use; Nx0[kk]+= (1.0-0.5*alpha2_xx[kk])*Rx[kk]; Nx0[kk]+= 0.5*alpha1_xx[kk] *Rx[kk-1]; if(galdef.use_symmetry==0) tridag_ext (Nx1,Nx2,Nx3,Nx0,Rx, particle.n_xgrid,nk ); if(galdef.use_symmetry==1) { //#pragma vdir nodep for(kk=0,kk1=1; kk<nkt-1; kk+=particle.n_xgrid,kk1+=particle.n_xgrid)Nx0[kk]+=0.5*alpha1_x0[kk] *Rx[kk1]; tridag_sym_ext (Nx1,Nx2,Nx3,Nx0,Rx, particle.n_xgrid,nk ); } } // irept } // galdef.prop_x==1 //cout<<" x complete"<<endl; // permute to y-first ns=particle.n_xgrid; kk=0; //#pragma vdir nodep for(i=0; i<ns; i++) //#pragma vdir nodep for(k=i; k<nkt; k+=ns,kk++)Ry[kk]=Rx[k]; kk=0; //#pragma vdir nodep for(i=0; i<ns; i++) //#pragma vdir nodep for(k=i; k<nkt; k+=ns,kk++)total_source_function_y[kk]=total_source_function_x[k]; // Y propagation if(galdef.prop_y==1) { /* kk=0; for(ix=0; ix<particle.n_xgrid; ix++) { for(ip=0; ip<particle.n_pgrid; ip++) { for(iz=0; iz<particle.n_zgrid; iz++) { for(iy=0; iy<particle.n_ygrid; iy++, kk++) { total_source_function_[kk]= total_source_function.d3[ix][iy][iz].s[ip]; } } // iz } // ip } // ix */ nk=particle.n_pgrid*particle.n_zgrid*particle.n_xgrid; for(irept=0; irept<nrept; irept++) { //cout<<irept<<endl; //#pragma vdir nodep for(kk=1; kk<nkt-1; kk++)Ny0[kk] = total_source_function_y[kk]*dt/f_use; //#pragma vdir nodep for(kk=1; kk<nkt-1; kk++)Ny0[kk]+= (1.0-0.5*alpha2_yy[kk])*Ry[kk]; //#pragma vdir nodep for(kk=1; kk<nkt-1; kk++)Ny0[kk]+= 0.5*alpha1_yy[kk] *Ry[kk-1]; //#pragma vdir nodep for(kk=1,kk1=2; kk<nkt-1; kk++,kk1++)Ny0[kk]+= 0.5*alpha3_yy[kk] *Ry[kk1]; kk=0; Ny0[kk] = total_source_function_y[kk]*dt/f_use; Ny0[kk]+= (1.0-0.5*alpha2_yy[kk])*Ry[kk]; Ny0[kk]+= 0.5*alpha3_yy[kk] *Ry[kk+1]; kk=nkt-1; Ny0[kk] = total_source_function_y[kk]*dt/f_use; Ny0[kk]+= (1.0-0.5*alpha2_yy[kk])*Ry[kk]; Ny0[kk]+= 0.5*alpha1_yy[kk] *Ry[kk-1]; if(galdef.use_symmetry==0) tridag_ext (Ny1,Ny2,Ny3,Ny0,Ry, particle.n_ygrid,nk ); if(galdef.use_symmetry==1) { //#pragma vdir nodep for(kk=0,kk1=1; kk<nkt-1; kk+=particle.n_ygrid,kk1+=particle.n_ygrid)Ny0[kk]+=0.5*alpha1_y0[kk] *Ry[kk1]; tridag_sym_ext (Ny1,Ny2,Ny3,Ny0,Ry, particle.n_ygrid,nk ); } }//irept /* if(galdef.use_symmetry==2) { for(ip=0; ip<particle.n_pgrid; ip++) { for(iz=0; iz<=n_zgrid_sym; iz++) { for(ix=0; ix<=n_xgrid_sym; ix++) { for(iy=0; iy<particle.n_ygrid; iy++) { double value= particle.cr_density.d3[ ix][iy][ iz].s[ip]; particle.cr_density.d3[particle.n_xgrid-1-ix][iy][ iz].s[ip]=value; particle.cr_density.d3[ ix][iy][particle.n_zgrid-1-iz].s[ip]=value; particle.cr_density.d3[particle.n_xgrid-1-ix][iy][particle.n_zgrid-1-iz].s[ip]=value; } // iy } // ix } // iz } // ip } // symmetry */ } // prop_y //cout<<" y complete"<<endl; // permute to z-first ns=particle.n_ygrid; kk=0; //#pragma vdir nodep for(i=0; i<ns; i++) //#pragma vdir nodep for(k=i; k<nkt; k+=ns,kk++)Rz[kk]=Ry[k]; kk=0; //#pragma vdir nodep for(i=0; i<ns; i++) //#pragma vdir nodep for(k=i; k<nkt; k+=ns,kk++) //#pragma vdir nodep total_source_function_z[kk]=total_source_function_y[k]; // Z propagation if(galdef.prop_z==1) { /* kk=0; for(iy=0; iy<particle.n_ygrid; iy++) { for(ix=0; ix<particle.n_xgrid; ix++) { for(ip=0; ip<particle.n_pgrid; ip++) { for(iz=0;iz<particle.n_zgrid;iz++, kk++){ total_source_function_[kk]= total_source_function.d3[ix][iy][iz].s[ip]; } } // ip } // ix } // iy */ nk=particle.n_pgrid*particle.n_xgrid*particle.n_ygrid; for(irept=0; irept<nrept; irept++) { //cout<<irept<<endl; //#pragma vdir nodep for(kk=1; kk<nkt-1; kk++)Nz0[kk] = total_source_function_z[kk]*dt/f_use; //#pragma vdir nodep for(kk=1; kk<nkt-1; kk++)Nz0[kk]+= (1.0-0.5*alpha2_zz[kk])*Rz[kk]; //#pragma vdir nodep for(kk=1; kk<nkt-1; kk++)Nz0[kk]+= 0.5*alpha1_zz[kk] *Rz[kk-1]; //#pragma vdir nodep for(kk=1,kk1=2; kk<nkt-1; kk++,kk1++)Nz0[kk]+= 0.5*alpha3_zz[kk] *Rz[kk1]; kk=0; Nz0[kk] = total_source_function_z[kk]*dt/f_use; Nz0[kk]+= (1.0-0.5*alpha2_zz[kk])*Rz[kk]; Nz0[kk]+= 0.5*alpha3_zz[kk] *Rz[kk+1]; kk=nkt-1; Nz0[kk] = total_source_function_z[kk]*dt/f_use; Nz0[kk]+= (1.0-0.5*alpha2_zz[kk])*Rz[kk]; Nz0[kk]+= 0.5*alpha1_zz[kk] *Rz[kk-1]; if(galdef.use_symmetry==0) tridag_ext (Nz1,Nz2,Nz3,Nz0,Rz, particle.n_zgrid,nk ); if(galdef.use_symmetry==1) { //#pragma vdir nodep for(kk=0,kk1=1; kk<nkt-1; kk+=particle.n_zgrid,kk1+=particle.n_zgrid)Nz0[kk]+=0.5*alpha1_z0[kk] *Rz[kk1]; tridag_sym_ext (Nz1,Nz2,Nz3,Nz0,Rz, particle.n_zgrid,nk ); } }//irept /* if(galdef.use_symmetry==2) { for(ip=0; ip<particle.n_pgrid; ip++) { for(ix=0; ix<=n_xgrid_sym; ix++) { for(iy=0; iy<=n_ygrid_sym; iy++) { for(iz=0; iz<particle.n_zgrid; iz++) { double value= particle.cr_density.d3[ ix][ iy][iz].s[ip]; particle.cr_density.d3[particle.n_xgrid-1-ix][ iy][iz].s[ip]=value; particle.cr_density.d3[ ix][particle.n_ygrid-1-iy][iz].s[ip]=value; particle.cr_density.d3[particle.n_xgrid-1-ix][particle.n_ygrid-1-iy][iz].s[ip]=value; } // iz } // iy } // ix } // ip } // symmetry */ } // prop_z //cout<<" z complete"<<endl; // permute to p-first ns=particle.n_zgrid; kk=0; //#pragma vdir nodep for(i=0; i<ns; i++) //#pragma vdir nodep for(k=i; k<nkt; k+=ns,kk++)Rp[kk]=Rz[k]; kk=0; //#pragma vdir nodep for(i=0; i<ns; i++) //#pragma vdir nodep for(k=i; k<nkt; k+=ns,kk++)total_source_function_p[kk]=total_source_function_z[k]; // P propagation if(galdef.prop_p==1) { /* kk=0; for(iz=0; iz<particle.n_zgrid; iz++) { for(iy=0; iy<particle.n_ygrid; iy++) { for(ix=0; ix<particle.n_xgrid; ix++) { for(ip=0; ip<particle.n_pgrid; ip++, kk++){ total_source_function_[kk]= total_source_function.d3[ix][iy][iz].s[ip]; } } // ix } // iy } // iz */ nk=particle.n_xgrid*particle.n_ygrid*particle.n_zgrid; for(irept=0; irept<nrept; irept++) { //cout<<irept<<endl; //#pragma vdir nodep for(kk=1; kk<nkt-1; kk++)Np0[kk] = total_source_function_p[kk]*dt/f_use; //#pragma vdir nodep for(kk=1; kk<nkt-1; kk++)Np0[kk]+= (1.0-0.5*alpha2_pp[kk])*Rp[kk]; //#pragma vdir nodep for(kk=1; kk<nkt-1; kk++)Np0[kk]+= 0.5*alpha1_pp[kk] *Rp[kk-1]; //#pragma vdir nodep for(kk=1,kk1=2; kk<nkt-1; kk++,kk1++)Np0[kk]+= 0.5*alpha3_pp[kk] *Rp[kk1]; kk=0; Np0[kk] = total_source_function_p[kk]*dt/f_use; Np0[kk]+= (1.0-0.5*alpha2_pp[kk])*Rp[kk]; Np0[kk]+= 0.5*alpha3_pp[kk] *Rp[kk+1]; kk=nkt-1; Np0[kk] = total_source_function_p[kk]*dt/f_use; Np0[kk]+= (1.0-0.5*alpha2_pp[kk])*Rp[kk]; Np0[kk]+= 0.5*alpha1_pp[kk] *Rp[kk-1]; tridag_ext (Np1,Np2,Np3,Np0,Rp, particle.n_pgrid,nk ); }// irept /* if(galdef.use_symmetry==2) { for(ip=0; ip<particle.n_pgrid; ip++) { for(ix=0; ix<=n_xgrid_sym; ix++) { for(iy=0; iy<=n_ygrid_sym; iy++) { for(iz=0; iz<=n_zgrid_sym; iz++) { double value= particle.cr_density.d3[ ix][ iy][ iz].s[ip]; particle.cr_density.d3[ ix][particle.n_ygrid-1-iy][ iz].s[ip]=value; particle.cr_density.d3[ ix][ iy][particle.n_zgrid-1-iz].s[ip]=value; particle.cr_density.d3[ ix][particle.n_ygrid-1-iy][particle.n_zgrid-1-iz].s[ip]=value; particle.cr_density.d3[particle.n_xgrid-1-ix][ iy][ iz].s[ip]=value; particle.cr_density.d3[particle.n_xgrid-1-ix][ iy][particle.n_zgrid-1-iz].s[ip]=value; particle.cr_density.d3[particle.n_xgrid-1-ix][particle.n_ygrid-1-iy][ iz].s[ip]=value; particle.cr_density.d3[particle.n_xgrid-1-ix][particle.n_ygrid-1-iy][particle.n_zgrid-1-iz].s[ip]=value; } // iz } // iy } // ix } // ip } // symmetry */ } // prop_p // permute to x-first ns=particle.n_pgrid; kk=0; //#pragma vdir nodep for(i=0; i<ns; i++) //#pragma vdir nodep for(k=i; k<nkt; k+=ns,kk++)Rx[kk]=Rp[k]; }//irept_outer kk=0; for(iz=0; iz<particle.n_zgrid; iz++) { for(iy=0; iy<particle.n_ygrid; iy++) { for(ix=0; ix<particle.n_xgrid; ix++) { for(ip=0; ip<particle.n_pgrid; ip++, kk++) particle.cr_density.d3[ix][iy][iz].s[ip]=Rp[kk]; } // ix } // iy } // iz //Gulli20070810 delete[] Nx1; delete[] Nx2; delete[] Nx3; delete[] Nx0; delete[] Rx; delete[] Ny1; delete[] Ny2; delete[] Ny3; delete[] Ny0; delete[] Ry; delete[] Nz1; delete[] Nz2; delete[] Nz3; delete[] Nz0; delete[] Rz; delete[] Np1; delete[] Np2; delete[] Np3; delete[] Np0; delete[] Rp; delete[] alpha1_xx; delete[] alpha1_yy; delete[] alpha1_zz; delete[] alpha1_pp; delete[] alpha2_xx; delete[] alpha2_yy; delete[] alpha2_zz; delete[] alpha2_pp; delete[] alpha3_xx; delete[] alpha3_yy; delete[] alpha3_zz; delete[] alpha3_pp; delete[] alpha1_x0; delete[] alpha1_y0; delete[] alpha1_z0; delete[] total_source_function_x; delete[] total_source_function_y; delete[] total_source_function_z; delete[] total_source_function_p; cout<<"<<protri"<<endl; }
33.781863
142
0.446927
bjbuckman
33b9c68619e97cfedb66e33df977efdd210d87c9
2,299
cpp
C++
test/unit-test/single/test-continuable-promisify.cpp
sTabishAzam/continuable
809f82673ad3458fe12b11fa6dee46d3cbcaf749
[ "MIT" ]
745
2017-02-27T22:17:27.000Z
2022-03-21T20:15:14.000Z
test/unit-test/single/test-continuable-promisify.cpp
sTabishAzam/continuable
809f82673ad3458fe12b11fa6dee46d3cbcaf749
[ "MIT" ]
45
2018-02-14T22:32:13.000Z
2022-02-09T14:56:09.000Z
test/unit-test/single/test-continuable-promisify.cpp
sTabishAzam/continuable
809f82673ad3458fe12b11fa6dee46d3cbcaf749
[ "MIT" ]
47
2017-03-07T17:24:13.000Z
2022-02-03T07:06:21.000Z
/* Copyright(c) 2015 - 2020 Denis Blank <denis.blank at outlook dot 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. 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 <test-continuable.hpp> template <typename T, typename Callback> void async_supply(T&& value, Callback&& callback) { std::forward<Callback>(callback)(cti::exception_t{}, std::forward<T>(value)); } TEST(promisify_tests, promisify_from) { auto c = cti::promisify<int>::from( [&](auto&&... args) { async_supply(std::forward<decltype(args)>(args)...); }, 36354); EXPECT_ASYNC_RESULT(std::move(c), 36354); } TEST(promisify_tests, promisify_from_lvalue) { int value = 0; auto c = cti::promisify<int>::from( [&](auto&&... args) { async_supply(std::forward<decltype(args)>(args)...); }, value); value = 36354; EXPECT_ASYNC_RESULT(std::move(c), 36354); } TEST(promisify_tests, promisify_with) { int value = 0; auto c = cti::promisify<int>::with( [](auto&& promise, auto&& /*e*/, int const& value) { EXPECT_EQ(value, 36354); promise.set_exception(supply_test_exception()); }, [&](auto&&... args) { async_supply(std::forward<decltype(args)>(args)...); }, value); value = 36354; ASSERT_ASYNC_EXCEPTION_COMPLETION(std::move(c)); }
33.318841
79
0.693345
sTabishAzam
33bd58b1e92626a4773f714879077e22fbab40b6
3,467
cpp
C++
src/imu.cpp
josefadamcik/ESP32SelfBalancingRobot
88030dc85177b309998adb628ca739f35636a997
[ "MIT" ]
3
2020-08-04T17:15:18.000Z
2021-03-07T19:40:43.000Z
src/imu.cpp
josefadamcik/ESP32SelfBalancingRobot
88030dc85177b309998adb628ca739f35636a997
[ "MIT" ]
null
null
null
src/imu.cpp
josefadamcik/ESP32SelfBalancingRobot
88030dc85177b309998adb628ca739f35636a997
[ "MIT" ]
2
2020-11-07T13:01:06.000Z
2022-03-08T19:59:59.000Z
#include "imu.h" #include "Arduino.h" #include "I2Cdev.h" #include "MPU6050_6Axis_MotionApps_V6_12.h" #include "Preferences.h" // MPU control/status vars uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU uint8_t devStatus; // return status after each device operation (0 = success, // !0 = error) uint16_t packetSize; // expected DMP packet size (default is 42 bytes) uint16_t fifoCount; // count of all bytes currently in FIFO MPU6050 mpu; bool dmpReady = false; // set true if DMP init was successful uint8_t fifoBuffer[64]; // FIFO storage buffer Quaternion q; // [w, x, y, z] quaternion container VectorFloat gravity; // [x, y, z] gravity vector bool isMPUReady() { return dmpReady; } bool getYPR(float *data) { if (mpu.dmpGetCurrentFIFOPacket(fifoBuffer)) { // Get the Latest packet mpu.dmpGetQuaternion(&q, fifoBuffer); mpu.dmpGetGravity(&gravity, &q); mpu.dmpGetYawPitchRoll(data, &q, &gravity); return true; } return false; } void setupMPU6050(const uint8_t interruptPin, const char *preferencesNamespace, void (*dmpReadyIsr)(void)) { Serial.println(F("Initializing MPU6050")); mpu.initialize(); pinMode(interruptPin, INPUT); Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed")); // load and configure the DMP Serial.println(F("Initializing DMP...")); devStatus = mpu.dmpInitialize(); // load offsets from preferences Preferences preferences; preferences.begin(preferencesNamespace, true); mpu.setXGyroOffset(preferences.getShort("gyro_x", 0)); mpu.setYGyroOffset(preferences.getShort("gyro_y", 0)); mpu.setZGyroOffset(preferences.getShort("gyro_z", 0)); mpu.setXAccelOffset(preferences.getShort("accel_x", 0)); mpu.setYAccelOffset(preferences.getShort("accel_y", 0)); mpu.setZAccelOffset(preferences.getShort("accel_z", 0)); preferences.end(); // make sure it worked (returns 0 if so) if (devStatus == 0) { Serial.println(F("Enabling DMP...")); mpu.setDMPEnabled(true); attachInterrupt(digitalPinToInterrupt(interruptPin), dmpReadyIsr, RISING); mpuIntStatus = mpu.getIntStatus(); Serial.println(F("DMP ready! Waiting for first interrupt...")); dmpReady = true; packetSize = mpu.dmpGetFIFOPacketSize(); } else { // ERROR! // 1 = initial memory load failed // 2 = DMP configuration updates failed // (if it's going to break, usually the code will be 1) Serial.print(F("DMP Initialization failed (code ")); Serial.print(devStatus); Serial.println(F(")")); } } void calibrateMPU(const char *preferencesNamespace) { Serial.println("Calibrate MPU"); mpu.CalibrateAccel(6); mpu.CalibrateGyro(6); mpu.PrintActiveOffsets(); Preferences preferences; preferences.begin(preferencesNamespace, false); preferences.putShort("gyro_x", mpu.getXGyroOffset()); preferences.putShort("gyro_y", mpu.getYGyroOffset()); preferences.putShort("gyro_z", mpu.getZGyroOffset()); preferences.putShort("accel_x", mpu.getXAccelOffset()); preferences.putShort("accel_y", mpu.getYAccelOffset()); preferences.putShort("accel_z", mpu.getZAccelOffset()); preferences.end(); }
39.850575
80
0.662532
josefadamcik
33be6fef5e30284157dfc1412eb1f4f3f4ac2c13
9,766
cxx
C++
sdk/scintilla/src/LexPOV.cxx
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
241
2015-01-04T00:36:58.000Z
2022-01-06T19:19:23.000Z
sdk/scintilla/src/LexPOV.cxx
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
10
2015-07-10T18:27:17.000Z
2019-06-26T20:59:59.000Z
sdk/scintilla/src/LexPOV.cxx
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
82
2015-01-25T18:02:35.000Z
2022-03-05T12:28:17.000Z
// Scintilla source code edit control /** @file LexPOV.cxx ** Lexer for POV-Ray SDL (Persistance of Vision Raytracer, Scene Description Language). ** Written by Philippe Lhoste but this is mostly a derivative of LexCPP... **/ // Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. // Some points that distinguish from a simple C lexer: // Identifiers start only by a character. // No line continuation character. // Strings are limited to 256 characters. // Directives are similar to preprocessor commands, // but we match directive keywords and colorize incorrect ones. // Block comments can be nested (code stolen from my code in LexLua). #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif static inline bool IsAWordChar(int ch) { return ch < 0x80 && (isalnum(ch) || ch == '_'); } static inline bool IsAWordStart(int ch) { return ch < 0x80 && isalpha(ch); } static inline bool IsANumberChar(int ch) { // Not exactly following number definition (several dots are seen as OK, etc.) // but probably enough in most cases. return (ch < 0x80) && (isdigit(ch) || toupper(ch) == 'E' || ch == '.' || ch == '-' || ch == '+'); } static void ColourisePovDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords1 = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; WordList &keywords6 = *keywordlists[5]; WordList &keywords7 = *keywordlists[6]; WordList &keywords8 = *keywordlists[7]; int currentLine = styler.GetLine(startPos); // Initialize the block comment /* */ nesting level, if we are inside such a comment. int blockCommentLevel = 0; if (initStyle == SCE_POV_COMMENT) { blockCommentLevel = styler.GetLineState(currentLine - 1); } // Do not leak onto next line if (initStyle == SCE_POV_STRINGEOL || initStyle == SCE_POV_COMMENTLINE) { initStyle = SCE_POV_DEFAULT; } short stringLen = 0; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.atLineEnd) { // Update the line state, so it can be seen by next line currentLine = styler.GetLine(sc.currentPos); if (sc.state == SCE_POV_COMMENT) { // Inside a block comment, we set the line state styler.SetLineState(currentLine, blockCommentLevel); } else { // Reset the line state styler.SetLineState(currentLine, 0); } } if (sc.atLineStart && (sc.state == SCE_POV_STRING)) { // Prevent SCE_POV_STRINGEOL from leaking back to previous line sc.SetState(SCE_POV_STRING); } // Determine if the current state should terminate. if (sc.state == SCE_POV_OPERATOR) { sc.SetState(SCE_POV_DEFAULT); } else if (sc.state == SCE_POV_NUMBER) { // We stop the number definition on non-numerical non-dot non-eE non-sign char if (!IsANumberChar(sc.ch)) { sc.SetState(SCE_POV_DEFAULT); } } else if (sc.state == SCE_POV_IDENTIFIER) { if (!IsAWordChar(sc.ch)) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords2.InList(s)) { sc.ChangeState(SCE_POV_WORD2); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_POV_WORD3); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_POV_WORD4); } else if (keywords5.InList(s)) { sc.ChangeState(SCE_POV_WORD5); } else if (keywords6.InList(s)) { sc.ChangeState(SCE_POV_WORD6); } else if (keywords7.InList(s)) { sc.ChangeState(SCE_POV_WORD7); } else if (keywords8.InList(s)) { sc.ChangeState(SCE_POV_WORD8); } sc.SetState(SCE_POV_DEFAULT); } } else if (sc.state == SCE_POV_DIRECTIVE) { if (!IsAWordChar(sc.ch)) { char s[100]; char *p; sc.GetCurrent(s, sizeof(s)); p = s; // Skip # and whitespace between # and directive word do { p++; } while ((*p == ' ' || *p == '\t') && *p != '\0'); if (!keywords1.InList(p)) { sc.ChangeState(SCE_POV_BADDIRECTIVE); } sc.SetState(SCE_POV_DEFAULT); } } else if (sc.state == SCE_POV_COMMENT) { if (sc.Match('/', '*')) { blockCommentLevel++; sc.Forward(); } else if (sc.Match('*', '/') && blockCommentLevel > 0) { blockCommentLevel--; sc.Forward(); if (blockCommentLevel == 0) { sc.ForwardSetState(SCE_POV_DEFAULT); } } } else if (sc.state == SCE_POV_COMMENTLINE) { if (sc.atLineEnd) { sc.ForwardSetState(SCE_POV_DEFAULT); } } else if (sc.state == SCE_POV_STRING) { if (sc.ch == '\\') { stringLen++; if (strchr("abfnrtuv0'\"", sc.chNext)) { // Compound characters are counted as one. // Note: for Unicode chars \u, we shouldn't count the next 4 digits... sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_POV_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_POV_STRINGEOL); sc.ForwardSetState(SCE_POV_DEFAULT); } else { stringLen++; } if (stringLen > 256) { // Strings are limited to 256 chars sc.SetState(SCE_POV_STRINGEOL); } } else if (sc.state == SCE_POV_STRINGEOL) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_C_DEFAULT); } else if (sc.atLineEnd) { sc.ForwardSetState(SCE_POV_DEFAULT); } } // Determine if a new state should be entered. if (sc.state == SCE_POV_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_POV_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_POV_IDENTIFIER); } else if (sc.Match('/', '*')) { blockCommentLevel = 1; sc.SetState(SCE_POV_COMMENT); sc.Forward(); // Eat the * so it isn't used for the end of the comment } else if (sc.Match('/', '/')) { sc.SetState(SCE_POV_COMMENTLINE); } else if (sc.ch == '\"') { sc.SetState(SCE_POV_STRING); stringLen = 0; } else if (sc.ch == '#') { sc.SetState(SCE_POV_DIRECTIVE); // Skip whitespace between # and directive word do { sc.Forward(); } while ((sc.ch == ' ' || sc.ch == '\t') && sc.More()); if (sc.atLineEnd) { sc.SetState(SCE_POV_DEFAULT); } } else if (isoperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_POV_OPERATOR); } } } sc.Complete(); } static void FoldPovDoc( unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { bool foldComment = styler.GetPropertyInt("fold.comment") != 0; bool foldDirective = styler.GetPropertyInt("fold.directive") != 0; bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style = initStyle; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int stylePrev = style; style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (foldComment && (style == SCE_POV_COMMENT)) { if (stylePrev != SCE_POV_COMMENT) { levelCurrent++; } else if ((styleNext != SCE_POV_COMMENT) && !atEOL) { // Comments don't end at end of line and the next character may be unstyled. levelCurrent--; } } if (foldComment && (style == SCE_POV_COMMENTLINE)) { if ((ch == '/') && (chNext == '/')) { char chNext2 = styler.SafeGetCharAt(i + 2); if (chNext2 == '{') { levelCurrent++; } else if (chNext2 == '}') { levelCurrent--; } } } if (foldDirective && (style == SCE_POV_DIRECTIVE)) { if (ch == '#') { unsigned int j=i+1; while ((j<endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) { j++; } } } if (style == SCE_POV_OPERATOR) { if (ch == '{') { levelCurrent++; } else if (ch == '}') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } static const char * const povWordLists[] = { "Language directives", "Objects & CSG & Appearance", "Types & Modifiers & Items", "Predefined Identifiers", "Predefined Functions", "User defined 1", "User defined 2", "User defined 3", 0, }; LexerModule lmPOV(SCLEX_POV, ColourisePovDoc, "pov", FoldPovDoc, povWordLists);
30.807571
103
0.622773
ixray-team
33bea0d080603eaced79872714ac598c0e7ae9a0
1,240
cpp
C++
test/std/localization/locale.categories/category.collate/locale.collate/locale.collate.members/hash.pass.cpp
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
test/std/localization/locale.categories/category.collate/locale.collate/locale.collate.members/hash.pass.cpp
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
test/std/localization/locale.categories/category.collate/locale.collate/locale.collate.members/hash.pass.cpp
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // <locale> // template <class charT> class collate; // long hash(const charT* low, const charT* high) const; // This test is not portable #include <locale.hxx> #include <string.hxx> #include <cassert.hxx> #include "test_macros.h" int main(int, char**) { std::locale l = std::locale::classic(); { std::string x1("1234"); std::string x2("12345"); const std::collate<char>& f = std::use_facet<std::collate<char> >(l); assert(f.hash(x1.data(), x1.data() + x1.size()) != f.hash(x2.data(), x2.data() + x2.size())); } { std::wstring x1(L"1234"); std::wstring x2(L"12345"); const std::collate<wchar_t>& f = std::use_facet<std::collate<wchar_t> >(l); assert(f.hash(x1.data(), x1.data() + x1.size()) != f.hash(x2.data(), x2.data() + x2.size())); } return 0; }
28.837209
83
0.512903
K-Wu
33c474e167900819a4233cae854cf178ed20ef67
30,955
cpp
C++
src/canvas/canvas.cpp
sixtyfive/lcdgfx
ef1a62fd4c86a7f5421c37065b6528634573f677
[ "MIT" ]
null
null
null
src/canvas/canvas.cpp
sixtyfive/lcdgfx
ef1a62fd4c86a7f5421c37065b6528634573f677
[ "MIT" ]
null
null
null
src/canvas/canvas.cpp
sixtyfive/lcdgfx
ef1a62fd4c86a7f5421c37065b6528634573f677
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2018-2020, Alexey Dynda 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 "canvas.h" #include "canvas/internal/canvas_types.h" #include <string.h> ///////////////////////////////////////////////////////////////////////////////// // // COMMON GRAPHICS // ///////////////////////////////////////////////////////////////////////////////// template <uint8_t BPP> void NanoCanvasOps<BPP>::putPixel(const NanoPoint &p) { putPixel(p.x, p.y); } template <uint8_t BPP> void NanoCanvasOps<BPP>::drawRect(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2) { drawHLine(x1, y1, x2); drawHLine(x1, y2, x2); drawVLine(x1, y1, y2); drawVLine(x2, y1, y2); } template <uint8_t BPP> void NanoCanvasOps<BPP>::drawRect(const NanoRect &rect) { drawRect(rect.p1.x, rect.p1.y, rect.p2.x, rect.p2.y); } template <uint8_t BPP> void NanoCanvasOps<BPP>::drawLine(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2) { lcduint_t dx = x1 > x2 ? (x1 - x2): (x2 - x1); lcduint_t dy = y1 > y2 ? (y1 - y2): (y2 - y1); lcduint_t err = 0; if (dy > dx) { if (y1 > y2) { canvas_swap_data(x1, x2, lcdint_t); canvas_swap_data(y1, y2, lcdint_t); } for(; y1<=y2; y1++) { err += dx; if (err >= dy) { err -= dy; x1 < x2 ? x1++: x1--; } putPixel( x1, y1 ); } } else { if (x1 > x2) { canvas_swap_data(x1, x2, lcdint_t); canvas_swap_data(y1, y2, lcdint_t); } for(; x1<=x2; x1++) { err += dy; if (err >= dx) { err -= dx; if (y1 < y2) y1++; else y1--; } putPixel( x1, y1 ); } } } template <uint8_t BPP> void NanoCanvasOps<BPP>::drawLine(const NanoRect &rect) { drawLine(rect.p1.x, rect.p1.y, rect.p2.x, rect.p2.y); } template <uint8_t BPP> void NanoCanvasOps<BPP>::fillRect(const NanoRect &rect) { fillRect(rect.p1.x, rect.p1.y, rect.p2.x, rect.p2.y); } template <uint8_t BPP> void NanoCanvasOps<BPP>::drawCircle(lcdint_t xc, lcdint_t yc, lcdint_t r) { if ((xc + r < offset.x) || (yc + r < offset.y) || (xc - r >= (lcdint_t)m_w + offset.x) || (yc - r >= (lcdint_t)m_h - offset.y)) { return; } lcdint_t d = 3 - 2 * r; lcdint_t x = 0; lcdint_t y = r; putPixel(xc, yc + r); putPixel(xc, yc - r); putPixel(xc + r, yc); putPixel(xc - r, yc); while (y >= x) { x++; if (d > 0) { y--; d += - 4 * y + 4; } d += 4 * x + 6; putPixel(xc+x, yc+y); putPixel(xc-x, yc+y); putPixel(xc+x, yc-y); putPixel(xc-x, yc-y); putPixel(xc+y, yc+x); putPixel(xc-y, yc+x); putPixel(xc+y, yc-x); putPixel(xc-y, yc-x); } } template <uint8_t BPP> uint8_t NanoCanvasOps<BPP>::printChar(uint8_t c) { uint16_t unicode = m_font->unicode16FromUtf8(c); if (unicode == SSD1306_MORE_CHARS_REQUIRED) return 0; SCharInfo char_info; m_font->getCharBitmap(unicode, &char_info); uint8_t mode = m_textMode; for (uint8_t i = 0; i<(m_fontStyle == STYLE_BOLD ? 2: 1); i++) { drawBitmap1(m_cursorX + i, m_cursorY, char_info.width, char_info.height, char_info.glyph ); m_textMode |= CANVAS_MODE_TRANSPARENT; } m_textMode = mode; m_cursorX += (lcdint_t)(char_info.width + char_info.spacing); if ( (m_textMode & CANVAS_TEXT_WRAP_LOCAL) && (m_cursorX > (lcdint_t)m_w - (lcdint_t)m_font->getHeader().width) ) { m_cursorY += (lcdint_t)m_font->getHeader().height; m_cursorX = 0; if ( (m_textMode & CANVAS_TEXT_WRAP_LOCAL) && (m_cursorY > ((lcdint_t)m_h - (lcdint_t)m_font->getHeader().height)) ) { m_cursorY = 0; } } return 1; } template <uint8_t BPP> size_t NanoCanvasOps<BPP>::write(uint8_t c) { if (c == '\n') { m_cursorY += (lcdint_t)m_font->getHeader().height; m_cursorX = 0; } else if (c == '\r') { // skip non-printed char } else { return printChar( c ); } return 1; } template <uint8_t BPP> void NanoCanvasOps<BPP>::printFixed(lcdint_t xpos, lcdint_t y, const char *ch, EFontStyle style) { m_fontStyle = style; m_cursorX = xpos; m_cursorY = y; while (*ch) { write(*ch); ch++; } } template <uint8_t BPP> void NanoCanvasOps<BPP>::printFixedPgm(lcdint_t xpos, lcdint_t y, const char *ch, EFontStyle style) { m_fontStyle = style; m_cursorX = xpos; m_cursorY = y; for (;;) { char c = pgm_read_byte(ch); if (!c) break; write(c); ch++; } } ///////////////////////////////////////////////////////////////////////////////// // // 1-BIT GRAPHICS // ///////////////////////////////////////////////////////////////////////////////// #ifdef CONFIG_MULTIPLICATION_NOT_SUPPORTED // compiler optimizes multiplication correctly itself #define YADDR1(y) (static_cast<uint16_t>((y) >> 3) * m_w) #define BANK_ADDR1(b) ((b) * m_w) #else #define YADDR1(y) (static_cast<uint16_t>((y) >> 3) * m_w) #define BANK_ADDR1(b) ((b) * m_w) #endif template <> void NanoCanvasOps<1>::putPixel(lcdint_t x, lcdint_t y) { x -= offset.x; y -= offset.y; if ((x<0) || (y<0)) return; if (( x >= (lcdint_t)m_w ) || ( y >= (lcdint_t)m_h)) return; if (m_color) { m_buf[YADDR1(y) + x] |= (1 << (y & 0x7)); } else { m_buf[YADDR1(y) + x] &= ~(1 << (y & 0x7)); } } template <> void NanoCanvasOps<1>::drawHLine(lcdint_t x1, lcdint_t y1, lcdint_t x2) { if (x2 < x1) canvas_swap_data(x2, x1, lcdint_t); x1 -= offset.x; x2 -= offset.x; y1 -= offset.y; if ((y1 >= (lcdint_t)m_h) || (y1 < 0)) return; if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; x1 = max(0, x1); x2 = min(x2, (lcdint_t)(m_w -1)); uint16_t addr = YADDR1(y1) + x1; uint8_t mask = (1 << (y1 & 0x7)); if (m_color) { do { m_buf[addr++] |= mask; } while (x2>x1++); } else { do { m_buf[addr++] &= ~mask; } while (x2>x1++); } } template <> void NanoCanvasOps<1>::drawVLine(lcdint_t x1, lcdint_t y1, lcdint_t y2) { if (y2 < y1) canvas_swap_data(y2, y1, lcdint_t); x1 -= offset.x; y1 -= offset.y; y2 -= offset.y; if ((x1 >= (lcdint_t)m_w) || (x1 < 0)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; y1 = max(0, y1); y2 = min(y2, (lcdint_t)(m_h -1)); uint16_t addr = YADDR1(y1) + x1; if ((y1 & 0xFFF8) == (y2 & 0xFFF8)) { uint8_t mask = ((0xFF >> (0x07 + y1 - y2)) << (y1 & 0x07)); if (m_color) m_buf[addr] |= mask; else m_buf[addr] &= ~mask; return; } if (m_color) { m_buf[addr] |= (0xFF << (y1 & 0x07)); addr += m_w; while (addr<YADDR1(y2) + x1) { m_buf[addr] |= 0xFF; addr += m_w; } m_buf[addr] |= (0xFF >> (0x07 - (y2 & 0x07))); } else { m_buf[addr] &= ~(0xFF << (y1 & 0x07)); addr += m_w; while (addr<YADDR1(y2) + x1) { m_buf[addr] &= 0; addr += m_w; } m_buf[addr] &= ~(0xFF >> (0x07 - (y2 & 0x07))); } } template <> void NanoCanvasOps<1>::fillRect(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2) { if (x2 < x1) canvas_swap_data(x2, x1, lcdint_t); if (y2 < y1) canvas_swap_data(y2, y1, lcdint_t); x1 -= offset.x; x2 -= offset.x; y1 -= offset.y; y2 -= offset.y; if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; x1 = max(0, x1); x2 = min(x2, (lcdint_t)(m_w - 1)); y1 = max(0, y1); y2 = min(y2, (lcdint_t)(m_h - 1)); uint8_t bank1 = (y1 >> 3); uint8_t bank2 = (y2 >> 3); for (uint8_t bank = bank1; bank<=bank2; bank++) { uint8_t mask = 0xFF; if (bank1 == bank2) { mask = (mask >> ((y1 & 7) + 7 - (y2 & 7))) << (y1 & 7); } else if (bank1 == bank) { mask = (mask << (y1 & 7)); } else if (bank2 == bank) { mask = (mask >> (7 - (y2 & 7))); } for (uint8_t x=x1; x<=x2; x++) { if (m_color) { m_buf[BANK_ADDR1(bank) + x] |= mask; } else { m_buf[BANK_ADDR1(bank) + x] &= ~mask; } } } }; template <> void NanoCanvasOps<1>::clear() { memset(m_buf, 0, YADDR1(m_h)); } // TODO: Not so fast implementation. needs to be optimized template <> void NanoCanvasOps<1>::drawBitmap1(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap) { x -= offset.x; y -= offset.y; lcduint_t origin_width = w; uint8_t offs = y & 0x07; uint8_t complexFlag = 0; uint8_t mainFlag = 1; if (y + (lcdint_t)h <= 0) return; if (y >= (lcdint_t)m_h) return; if (x + (lcdint_t)w <= 0) return; if (x >= (lcdint_t)m_w) return; if (y < 0) { bitmap += ((lcduint_t)((-y) + 7) >> 3) * w; h += y; y = 0; complexFlag = 1; } if (x < 0) { bitmap += -x; w += x; x = 0; } uint8_t max_pages = (lcduint_t)(h + 15 - offs) >> 3; if ((lcduint_t)(y + (lcdint_t)h) > (lcduint_t)m_h) { h = (lcduint_t)(m_h - (lcduint_t)y); } if ((lcduint_t)(x + (lcdint_t)w) > (lcduint_t)m_w) { w = (lcduint_t)(m_w - (lcduint_t)x); } uint8_t pages = ((y + h - 1) >> 3) - (y >> 3) + 1; uint8_t j; lcduint_t i; for(j=0; j < pages; j++) { uint16_t addr = YADDR1(y + ((uint16_t)j<<3)) + x; if ( j == max_pages - 1 ) mainFlag = !offs; for( i=w; i > 0; i--) { uint8_t data = 0; uint8_t mask = 0; if ( mainFlag ) { data |= (pgm_read_byte(bitmap) << offs); mask |= (0xFF << offs); } if ( complexFlag ) { data |= (pgm_read_byte(bitmap - origin_width) >> (8 - offs)); mask |= (0xFF >> (8 - offs)); } if (CANVAS_MODE_TRANSPARENT != (m_textMode & CANVAS_MODE_TRANSPARENT)) { m_buf[addr] &= ~mask; m_buf[addr] |= m_color == BLACK ? ~data: data; } else { if (m_color == BLACK) m_buf[addr] &= ~data; else m_buf[addr] |= data; } bitmap++; addr++; } bitmap += origin_width - w; complexFlag = offs; } } template <> void NanoCanvasOps<1>::begin(lcdint_t w, lcdint_t h, uint8_t *bytes) { m_w = w; m_h = h; offset.x = 0; offset.y = 0; m_cursorX = 0; m_cursorY = 0; m_color = WHITE; m_bgColor = 0; m_textMode = 0; m_buf = bytes; clear(); } ///////////////////////////////////////////////////////////////////////////////// // // 4-BIT GRAY GRAPHICS // ///////////////////////////////////////////////////////////////////////////////// /* We need to use multiply operation, because there are displays on the market * * with resolution different from 2^N (160x128, 96x64, etc.) */ #define YADDR4(y) (static_cast<uint32_t>(y) * m_w / 2) #define BITS_SHIFT4(x) ((x & 1) ? 4 : 0) template <> void NanoCanvasOps<4>::putPixel(lcdint_t x, lcdint_t y) { x -= offset.x; y -= offset.y; if ((x >= 0) && (y >= 0) && (x < (lcdint_t)m_w) && (y < (lcdint_t)m_h)) { m_buf[YADDR4(y) + x / 2] &= ~(0x0F << BITS_SHIFT4(x)); m_buf[YADDR4(y) + x / 2] |= (m_color & 0x0F) << BITS_SHIFT4(x); } } template <> void NanoCanvasOps<4>::drawVLine(lcdint_t x1, lcdint_t y1, lcdint_t y2) { x1 -= offset.x; y1 -= offset.y; y2 -= offset.y; if (y1 > y2) { canvas_swap_data(y1, y2, lcdint_t); } if ((x1 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; y1 = max(y1,0); y2 = min(y2,(lcdint_t)m_h-1) - y1; uint8_t *buf = m_buf + YADDR4(y1) + x1 / 2; do { *buf &= ~(0x0F << BITS_SHIFT4(x1)); *buf |= ((m_color & 0x0F) << BITS_SHIFT4(x1)); buf += m_w / 2; } while (y2--); } template <> void NanoCanvasOps<4>::drawHLine(lcdint_t x1, lcdint_t y1, lcdint_t x2) { x1 -= offset.x; y1 -= offset.y; x2 -= offset.x; if (x1 > x2) { canvas_swap_data(x1, x2, lcdint_t); } if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y1 < 0) || (y1 >= (lcdint_t)m_h)) return; x1 = max(x1,0); x2 = min(x2,(lcdint_t)m_w-1); uint8_t *buf = m_buf + YADDR4(y1) + x1 / 2; for (lcdint_t x = x1; x <= x2; x++) { *buf &= ~(0x0F << BITS_SHIFT4(x)); *buf |= ((m_color & 0x0F) << BITS_SHIFT4(x)); if ( x & 1 ) { buf++; } } } template <> void NanoCanvasOps<4>::fillRect(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2) { if (y1 > y2) { canvas_swap_data(y1, y2, lcdint_t); } if (x1 > x2) { canvas_swap_data(x1, x2, lcdint_t); } x1 -= offset.x; y1 -= offset.y; x2 -= offset.x; y2 -= offset.y; if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; x1 = max(x1,0); x2 = min(x2,(lcdint_t)m_w-1); y1 = max(y1,0); y2 = min(y2,(lcdint_t)m_h-1); uint8_t *buf = m_buf + YADDR4(y1) + x1 / 2; for (lcdint_t y = y1; y <= y2; y++) { for (lcdint_t x = x1; x <= x2; x++) { *buf &= ~(0x0F << BITS_SHIFT4(x)); *buf |= ((m_color & 0xF) << BITS_SHIFT4(x)); if ( x & 1 ) { buf++; } } buf += ((lcdint_t)(m_w) - (x2 - x1 + ((x2 - x1) & 0x1))) / 2; } } template <> void NanoCanvasOps<4>::drawBitmap1(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *bitmap) { lcdint_t xb1 = 0; lcdint_t yb1 = 0; lcdint_t xb2 = (lcdint_t)w - 1; lcdint_t yb2 = (lcdint_t)h - 1; /* calculate char rectangle */ lcdint_t x1 = xpos - offset.x; lcdint_t y1 = ypos - offset.y; lcdint_t x2 = x1 + xb2; lcdint_t y2 = y1 + yb2; /* clip bitmap */ if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; if (x1 < 0) { xb1 -= x1; x1 = 0; } if (y1 < 0) { yb1 -= y1; y1 = 0; } if (y2 >= (lcdint_t)m_h) { // yb2 -= (y2 - (lcdint_t)m_h + 1); y2 = (lcdint_t)m_h - 1; } if (x2 >= (lcdint_t)m_w) { // xb2 -= (x2 - (lcdint_t)m_w + 1); x2 = (lcdint_t)m_w - 1; } for ( lcdint_t y = y1; y <= y2; y++ ) { for ( lcdint_t x = x1; x <= x2; x++ ) { uint16_t src_addr1 = xb1 + x - x1 + ((yb1 + y - y1) / 8) * w; uint8_t src_bit1 = (yb1 + y - y1) & 0x07; uint8_t data = pgm_read_byte( &bitmap[ src_addr1 ] ); uint16_t addr = YADDR4(y) + x / 2; if (data & (1 << src_bit1)) { data = m_color & 0x0F; m_buf[ addr ] &= ~(0x0F << BITS_SHIFT4(x)); m_buf[ addr ] |= data << BITS_SHIFT4(x); } else if (!(m_textMode & CANVAS_MODE_TRANSPARENT)) { data = 0x00; m_buf[ addr ] &= ~(0x0F << BITS_SHIFT4(x)); } } } } template <> void NanoCanvasOps<4>::drawBitmap8(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *bitmap) { lcdint_t xb1 = 0; lcdint_t yb1 = 0; lcdint_t xb2 = (lcdint_t)w - 1; lcdint_t yb2 = (lcdint_t)h - 1; /* calculate char rectangle */ lcdint_t x1 = xpos - offset.x; lcdint_t y1 = ypos - offset.y; lcdint_t x2 = x1 + xb2; lcdint_t y2 = y1 + yb2; /* clip bitmap */ if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; if (x1 < 0) { xb1 -= x1; x1 = 0; } if (y1 < 0) { yb1 -= y1; y1 = 0; } if (y2 >= (lcdint_t)m_h) { // yb2 -= (y2 - (lcdint_t)m_h + 1); y2 = (lcdint_t)m_h - 1; } if (x2 >= (lcdint_t)m_w) { // xb2 -= (x2 - (lcdint_t)m_w + 1); x2 = (lcdint_t)m_w - 1; } for ( lcdint_t y = y1; y <= y2; y++ ) { for ( lcdint_t x = x1; x <= x2; x++ ) { uint16_t src_addr8 = xb1 + x - x1 + ((yb1 + y - y1)) * w; uint8_t data = pgm_read_byte( &bitmap[ src_addr8 ] ); uint16_t addr = YADDR4(y) + x / 2; if ( (data) || (!(m_textMode & CANVAS_MODE_TRANSPARENT)) ) { data = RGB8_TO_GRAY4(data); m_buf[ addr ] &= ~(0x0F << BITS_SHIFT4(x)); m_buf[ addr ] |= (data & 0x0F) << BITS_SHIFT4(x); } } } } template <> void NanoCanvasOps<4>::clear() { memset(m_buf, 0, YADDR4(m_h)); } /* This method must be implemented always after clear() */ template <> void NanoCanvasOps<4>::begin(lcdint_t w, lcdint_t h, uint8_t *bytes) { m_w = w; m_h = h; offset.x = 0; offset.y = 0; m_cursorX = 0; m_cursorY = 0; m_color = 0xFF; // white color by default m_bgColor = 0x00; m_textMode = 0; m_buf = bytes; clear(); } ///////////////////////////////////////////////////////////////////////////////// // // 8-BIT GRAPHICS // ///////////////////////////////////////////////////////////////////////////////// /* We need to use multiply operation, because there are displays on the market * * with resolution different from 2^N (160x128, 96x64, etc.) */ #define YADDR8(y) (static_cast<uint32_t>(y) * m_w) template <> void NanoCanvasOps<8>::putPixel(lcdint_t x, lcdint_t y) { x -= offset.x; y -= offset.y; if ((x >= 0) && (y >= 0) && (x < (lcdint_t)m_w) && (y < (lcdint_t)m_h)) { m_buf[YADDR8(y) + x] = m_color; } } template <> void NanoCanvasOps<8>::drawVLine(lcdint_t x1, lcdint_t y1, lcdint_t y2) { x1 -= offset.x; y1 -= offset.y; y2 -= offset.y; if (y1 > y2) { canvas_swap_data(y1, y2, lcdint_t); } if ((x1 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; y1 = max(y1,0); uint8_t *buf = m_buf + YADDR8(y1) + x1; y2 = min(y2,(lcdint_t)m_h-1) - y1; do { *buf = m_color; buf += m_w; } while (y2--); } template <> void NanoCanvasOps<8>::drawHLine(lcdint_t x1, lcdint_t y1, lcdint_t x2) { x1 -= offset.x; y1 -= offset.y; x2 -= offset.x; if (x1 > x2) { canvas_swap_data(x1, x2, lcdint_t); } if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y1 < 0) || (y1 >= (lcdint_t)m_h)) return; x1 = max(x1,0); x2 = min(x2,(lcdint_t)m_w-1); uint8_t *buf = m_buf + YADDR8(y1) + x1; for (lcdint_t x = 0; x <= x2 - x1; x++) { *buf = m_color; buf++; } } template <> void NanoCanvasOps<8>::fillRect(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2) { if (y1 > y2) { canvas_swap_data(y1, y2, lcdint_t); } if (x1 > x2) { canvas_swap_data(x1, x2, lcdint_t); } x1 -= offset.x; y1 -= offset.y; x2 -= offset.x; y2 -= offset.y; if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; x1 = max(x1,0); x2 = min(x2,(lcdint_t)m_w-1); y1 = max(y1,0); y2 = min(y2,(lcdint_t)m_h-1); uint8_t *buf = m_buf + YADDR8(y1) + x1; for (lcdint_t y = y1; y <= y2; y++) { for (lcdint_t x = x1; x <= x2; x++) { *buf = m_color; buf++; } buf += ((lcdint_t)(m_w) - (x2 - x1 + 1)); } } template <> void NanoCanvasOps<8>::drawBitmap1(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *bitmap) { uint8_t offs = 0; /* calculate char rectangle */ lcdint_t x1 = xpos - offset.x; lcdint_t y1 = ypos - offset.y; lcdint_t x2 = x1 + (lcdint_t)w - 1; lcdint_t y2 = y1 + (lcdint_t)h - 1; /* clip bitmap */ if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; if (x1 < 0) { bitmap -= x1; x1 = 0; } if (y1 < 0) { bitmap += ((lcduint_t)(-y1) >> 3) * w; offs = ((-y1) & 0x07); y1 = 0; } if (y2 >= (lcdint_t)m_h) { y2 = (lcdint_t)m_h - 1; } if (x2 >= (lcdint_t)m_w) { x2 = (lcdint_t)m_w - 1; } uint8_t offs2 = 8 - offs; lcdint_t y = y1; while ( y <= y2) { for ( lcdint_t x = x1; x <= x2; x++ ) { uint8_t data = pgm_read_byte( bitmap ); uint16_t addr = YADDR8(y) + x; for (uint8_t n = 0; n < min(y2 - y + 1, 8); n++) { if ( data & (1<<(n + offs)) ) m_buf[addr] = m_color; else if (!(m_textMode & CANVAS_MODE_TRANSPARENT)) m_buf[addr] = 0x00; addr += (lcduint_t)m_w; } bitmap++; } bitmap += (w - (x2 - x1 + 1)); y = y + offs2; offs = 0; offs2 = 8; } } template <> void NanoCanvasOps<8>::drawBitmap8(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *bitmap) { /* calculate char rectangle */ lcdint_t x1 = xpos - offset.x; lcdint_t y1 = ypos - offset.y; lcdint_t x2 = x1 + (lcdint_t)w - 1; lcdint_t y2 = y1 + (lcdint_t)h - 1; /* clip bitmap */ if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; if (x1 < 0) { bitmap -= x1; x1 = 0; } if (y1 < 0) { bitmap += (lcduint_t)(-y1) * w; y1 = 0; } if (y2 >= (lcdint_t)m_h) { y2 = (lcdint_t)m_h - 1; } if (x2 >= (lcdint_t)m_w) { x2 = (lcdint_t)m_w - 1; } lcdint_t y = y1; while ( y <= y2 ) { for ( lcdint_t x = x1; x <= x2; x++ ) { uint8_t data = pgm_read_byte( bitmap ); if ( (data) || (!(m_textMode & CANVAS_MODE_TRANSPARENT)) ) { m_buf[YADDR8(y) + x] = data; } bitmap++; } bitmap += (w - (x2 - x1 + 1)); y++; } } template <> void NanoCanvasOps<8u>::clear() { memset(m_buf, 0, YADDR8(m_h)); } /* This method must be implemented always after clear() */ template <> void NanoCanvasOps<8>::begin(lcdint_t w, lcdint_t h, uint8_t *bytes) { m_w = w; m_h = h; offset.x = 0; offset.y = 0; m_cursorX = 0; m_cursorY = 0; m_color = 0xFF; // white color by default m_bgColor = 0x00; m_textMode = 0; m_buf = bytes; clear(); } ///////////////////////////////////////////////////////////////////////////////// // // 16-BIT GRAPHICS // ///////////////////////////////////////////////////////////////////////////////// /* We need to use multiply operation, because there are displays on the market * * with resolution different from 2^N (160x128, 96x64, etc.) */ #define YADDR16(y) (static_cast<uint32_t>(y) * (m_w << 1)) template <> void NanoCanvasOps<16>::putPixel(lcdint_t x, lcdint_t y) { x -= offset.x; y -= offset.y; if ((x >= 0) && (y >= 0) && (x < (lcdint_t)m_w) && (y < (lcdint_t)m_h)) { m_buf[YADDR16(y) + (x<<1)] = m_color >> 8; m_buf[YADDR16(y) + (x<<1) + 1] = m_color & 0xFF; } } template <> void NanoCanvasOps<16>::drawVLine(lcdint_t x1, lcdint_t y1, lcdint_t y2) { x1 -= offset.x; y1 -= offset.y; y2 -= offset.y; if (y1 > y2) { canvas_swap_data(y1, y2, lcdint_t); } if ((x1 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; y1 = max(y1,0); uint8_t *buf = m_buf + YADDR16(y1) + (x1 << 1); y2 = min(y2,(lcdint_t)m_h-1) - y1; do { buf[0] = m_color >> 8; buf[1] = m_color & 0xFF; buf += (m_w<<1); } while (y2--); } template <> void NanoCanvasOps<16>::drawHLine(lcdint_t x1, lcdint_t y1, lcdint_t x2) { x1 -= offset.x; y1 -= offset.y; x2 -= offset.x; if (x1 > x2) { canvas_swap_data(x1, x2, lcdint_t); } if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y1 < 0) || (y1 >= (lcdint_t)m_h)) return; x1 = max(x1,0); x2 = min(x2,(lcdint_t)m_w-1); uint8_t *buf = m_buf + YADDR16(y1) + (x1<<1); for (lcdint_t x = 0; x <= x2 - x1; x++) { buf[0] = m_color >> 8; buf[1] = m_color & 0xFF; buf+=2; } } template <> void NanoCanvasOps<16>::fillRect(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2) { if (y1 > y2) { canvas_swap_data(y1, y2, lcdint_t); } if (x1 > x2) { canvas_swap_data(x1, x2, lcdint_t); } x1 -= offset.x; y1 -= offset.y; x2 -= offset.x; y2 -= offset.y; if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; x1 = max(x1,0); x2 = min(x2,(lcdint_t)m_w-1); y1 = max(y1,0); y2 = min(y2,(lcdint_t)m_h-1); uint8_t *buf = m_buf + YADDR16(y1) + (x1<<1); for (lcdint_t y = y1; y <= y2; y++) { for (lcdint_t x = x1; x <= x2; x++) { buf[0] = m_color >> 8; buf[1] = m_color & 0xFF; buf+=2; } buf += ( ((lcdint_t)(m_w) - (x2 - x1 + 1)) <<1 ); } } template <> void NanoCanvasOps<16>::drawBitmap1(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *bitmap) { uint8_t offs = 0; /* calculate char rectangle */ lcdint_t x1 = xpos - offset.x; lcdint_t y1 = ypos - offset.y; lcdint_t x2 = x1 + (lcdint_t)w - 1; lcdint_t y2 = y1 + (lcdint_t)h - 1; /* clip bitmap */ if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; if (x1 < 0) { bitmap -= x1; x1 = 0; } if (y1 < 0) { bitmap += ((lcduint_t)(-y1) >> 3) * w; offs = ((-y1) & 0x07); y1 = 0; } if (y2 >= (lcdint_t)m_h) { y2 = (lcdint_t)m_h - 1; } if (x2 >= (lcdint_t)m_w) { x2 = (lcdint_t)m_w - 1; } uint8_t offs2 = 8 - offs; lcdint_t y = y1; while ( y <= y2) { for ( lcdint_t x = x1; x <= x2; x++ ) { uint8_t data = pgm_read_byte( bitmap ); uint16_t addr = YADDR16(y) + (x<<1); for (uint8_t n = 0; n < min(y2 - y + 1, 8); n++) { if ( data & (1<<(n + offs)) ) { m_buf[addr] = m_color >> 8; m_buf[addr+1] = m_color & 0xFF; } else if (!(m_textMode & CANVAS_MODE_TRANSPARENT)) { m_buf[addr] = 0x00; m_buf[addr+1] = 0x00; } addr += ((lcduint_t)m_w << 1); } bitmap++; } bitmap += (w - (x2 - x1 + 1)); y = y + offs2; offs = 0; offs2 = 8; } } template <> void NanoCanvasOps<16>::drawBitmap8(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *bitmap) { /* calculate char rectangle */ lcdint_t x1 = xpos - offset.x; lcdint_t y1 = ypos - offset.y; lcdint_t x2 = x1 + (lcdint_t)w - 1; lcdint_t y2 = y1 + (lcdint_t)h - 1; /* clip bitmap */ if ((x2 < 0) || (x1 >= (lcdint_t)m_w)) return; if ((y2 < 0) || (y1 >= (lcdint_t)m_h)) return; if (x1 < 0) { bitmap -= x1; x1 = 0; } if (y1 < 0) { bitmap += (lcduint_t)(-y1) * w; y1 = 0; } if (y2 >= (lcdint_t)m_h) { y2 = (lcdint_t)m_h - 1; } if (x2 >= (lcdint_t)m_w) { x2 = (lcdint_t)m_w - 1; } lcdint_t y = y1; while ( y <= y2 ) { for ( lcdint_t x = x1; x <= x2; x++ ) { uint8_t data = pgm_read_byte( bitmap ); if ( (data) || (!(m_textMode & CANVAS_MODE_TRANSPARENT)) ) { uint16_t color = (((uint16_t)data & 0b11100000) << 8) | (((uint16_t)data & 0b00011100) << 6) | (((uint16_t)data & 0b00000011) << 3); m_buf[YADDR16(y) + (x<<1)] = color; } bitmap++; } bitmap += (w - (x2 - x1 + 1)); y++; } } template <> void NanoCanvasOps<16>::clear() { memset(m_buf, 0, YADDR16(m_h)); } template <> void NanoCanvasOps<16>::begin(lcdint_t w, lcdint_t h, uint8_t *bytes) { m_w = w; m_h = h; offset.x = 0; offset.y = 0; m_cursorX = 0; m_cursorY = 0; m_color = 0xFFFF; // white color by default m_textMode = 0; m_buf = bytes; clear(); } ///////////////////////////////////////////////////////////////////////////////// // // NanoCanvasOps class initiation // ///////////////////////////////////////////////////////////////////////////////// template class NanoCanvasOps<1>; template class NanoCanvasOps<4>; template class NanoCanvasOps<8>; template class NanoCanvasOps<16>;
26.100337
126
0.47456
sixtyfive
33c560313771c0e4d30b210cd8b122ae95dcaa0c
9,291
cpp
C++
gmsl_camera/src/SampleFramework.cpp
vehicularkech/gmsl-camera-ros-driver
1dfadb91c4b5829ca562e362911f1b3dcb7ab083
[ "MIT" ]
2
2018-04-20T02:26:18.000Z
2018-10-11T03:20:36.000Z
gmsl_camera/src/SampleFramework.cpp
vehicularkech/gmsl-camera-ros-driver
1dfadb91c4b5829ca562e362911f1b3dcb7ab083
[ "MIT" ]
1
2018-07-12T08:19:31.000Z
2018-07-12T08:19:31.000Z
gmsl_camera/src/SampleFramework.cpp
vehicularkech/gmsl-camera-ros-driver
1dfadb91c4b5829ca562e362911f1b3dcb7ab083
[ "MIT" ]
1
2019-01-24T03:02:45.000Z
2019-01-24T03:02:45.000Z
#pragma GCC diagnostic ignored "-Wold-style-cast" #include <signal.h> #include <cstring> // for memset #include <iostream> #include <SampleFramework.hpp> void (*gUserKeyPressCallback)(int) = 0; ProgramArguments gArguments; WindowBase *gWindow = nullptr; bool gRun = false; void sig_int_handler(int sig) { (void)sig; gRun = false; } void keyPressCallback(int key) { // stop application if (key == GLFW_KEY_ESCAPE) gRun = false; if (gUserKeyPressCallback) { gUserKeyPressCallback(key); } } void drawLineSegments(const std::vector<dwLineSegment2Df> &segments, dwRenderBufferHandle_t renderBuffer, dwRendererHandle_t renderer) { float32_t* coords = nullptr; uint32_t maxVertices = 0; uint32_t vertexStride = 0; dwRenderBuffer_map(&coords, &maxVertices, &vertexStride, renderBuffer); dwRect screenRectangle; dwRenderer_getRect(&screenRectangle, renderer); for (uint32_t i = 0U; i < segments.size(); ++i) { // transform pixel coords into rendered rectangle float32_t x_start = static_cast<float32_t>(segments[i].a.x) - 0.5f; float32_t y_start = static_cast<float32_t>(segments[i].a.y) - 0.5f; float32_t x_end = static_cast<float32_t>(segments[i].b.x) - 0.5f; float32_t y_end = static_cast<float32_t>(segments[i].b.y) - 0.5f; coords[0] = x_start; coords[1] = y_start; coords += vertexStride; coords[0] = x_end; coords[1] = y_end; coords += vertexStride; } dwRenderBuffer_unmap(static_cast<uint32_t>(segments.size() * 2), renderBuffer); dwRenderer_renderBuffer(renderBuffer, renderer); } void drawBoxes(const std::vector<dwBox2D> &boxes, const std::vector<uint32_t> *boxIds, float32_t normalizationWidth, float32_t normalizationHeight, dwRenderBufferHandle_t renderBuffer, dwRendererHandle_t renderer) { if (boxes.size() == 0) return; bool renderText = boxIds && boxIds->size() == boxes.size(); dwRenderer_setFont(DW_RENDER_FONT_VERDANA_20, renderer); char idString[64]; float32_t* coords = nullptr; uint32_t maxVertices = 0; uint32_t vertexStride = 0; dwRenderBuffer_map(&coords, &maxVertices, &vertexStride, renderBuffer); uint32_t n_boxes = static_cast<uint32_t>(boxes.size()); uint32_t n_verts = 8 * n_boxes; if (n_verts > maxVertices) { n_boxes = maxVertices / 8; n_verts = 8 * n_boxes; } dwRect screenRectangle; dwRenderer_getRect(&screenRectangle, renderer); float32_t screenWidth = static_cast<float32_t>(screenRectangle.width); float32_t screenHeight = static_cast<float32_t>(screenRectangle.height); for (uint32_t i = 0U; i < n_boxes; ++i) { // transform pixel coords into rendered rectangle float32_t x_start = static_cast<float32_t>(boxes[i].x) - 0.5f; float32_t y_start = static_cast<float32_t>(boxes[i].y) - 0.5f; float32_t x_end = static_cast<float32_t>(boxes[i].width) + x_start; float32_t y_end = static_cast<float32_t>(boxes[i].height) + y_start; coords[0] = x_start; coords[1] = y_start; coords += vertexStride; coords[0] = x_start; coords[1] = y_end; coords += vertexStride; coords[0] = x_start; coords[1] = y_end; coords += vertexStride; coords[0] = x_end; coords[1] = y_end; coords += vertexStride; coords[0] = x_end; coords[1] = y_end; coords += vertexStride; coords[0] = x_end; coords[1] = y_start; coords += vertexStride; coords[0] = x_end; coords[1] = y_start; coords += vertexStride; coords[0] = x_start; coords[1] = y_start; coords += vertexStride; if (renderText) { #ifndef _MSC_VER sprintf(idString, "%u", (*boxIds)[i]); #else sprintf_s(idString, "%u", (*boxIds)[i]); #endif dwRenderer_renderText(static_cast<int32_t>((x_start * screenWidth) / normalizationWidth), screenRectangle.height - static_cast<int32_t>((y_start * screenHeight) / normalizationHeight), idString, renderer); } } dwRenderBuffer_unmap(n_verts, renderBuffer); dwRenderer_renderBuffer(renderBuffer, renderer); } void drawBoxesWithLabels(const std::vector<std::pair<dwBox2D, std::string>> &boxesWithLabels, float32_t normalizationWidth, float32_t normalizationHeight, dwRenderBufferHandle_t renderBuffer, dwRendererHandle_t renderer) { if (boxesWithLabels.size() == 0) return; dwRenderer_setFont(DW_RENDER_FONT_VERDANA_20, renderer); float32_t* coords = nullptr; uint32_t maxVertices = 0; uint32_t vertexStride = 0; dwRenderBuffer_map(&coords, &maxVertices, &vertexStride, renderBuffer); uint32_t n_boxes = static_cast<uint32_t>(boxesWithLabels.size()); uint32_t n_verts = 8 * n_boxes; if (n_verts > maxVertices) { n_boxes = maxVertices / 8; n_verts = 8 * n_boxes; } dwRect screenRectangle; dwRenderer_getRect(&screenRectangle, renderer); float32_t screenWidth = static_cast<float32_t>(screenRectangle.width); float32_t screenHeight = static_cast<float32_t>(screenRectangle.height); for (uint32_t i = 0U; i < n_boxes; ++i) { std::pair<dwBox2D, std::string> boxClassIdPair = boxesWithLabels[i]; dwBox2D &box = boxClassIdPair.first; std::string classLabel = boxClassIdPair.second; // transform pixel coords into rendered rectangle float32_t x_start = static_cast<float32_t>(box.x) - 0.5f; float32_t y_start = static_cast<float32_t>(box.y) - 0.5f; float32_t x_end = static_cast<float32_t>(box.width) + x_start; float32_t y_end = static_cast<float32_t>(box.height) + y_start; coords[0] = x_start; coords[1] = y_start; coords += vertexStride; coords[0] = x_start; coords[1] = y_end; coords += vertexStride; coords[0] = x_start; coords[1] = y_end; coords += vertexStride; coords[0] = x_end; coords[1] = y_end; coords += vertexStride; coords[0] = x_end; coords[1] = y_end; coords += vertexStride; coords[0] = x_end; coords[1] = y_start; coords += vertexStride; coords[0] = x_end; coords[1] = y_start; coords += vertexStride; coords[0] = x_start; coords[1] = y_start; coords += vertexStride; dwRenderer_renderText(static_cast<int32_t>((x_start * screenWidth) / normalizationWidth), screenRectangle.height - static_cast<int32_t>((y_start * screenHeight) / normalizationHeight), classLabel.c_str(), renderer); } dwRenderBuffer_unmap(n_verts, renderBuffer); dwRenderer_renderBuffer(renderBuffer, renderer); } bool initSampleApp( int argc, const char **argv, const ProgramArguments* arguments, void (*userKeyPressCallback)(int), uint32_t width, uint32_t height) { gUserKeyPressCallback = userKeyPressCallback; #if (!WINDOWS) struct sigaction action = {}; action.sa_handler = sig_int_handler; sigaction(SIGHUP, &action, NULL); // controlling terminal closed, Ctrl-D sigaction(SIGINT, &action, NULL); // Ctrl-C sigaction(SIGQUIT, &action, NULL); // Ctrl-\, clean quit with core dump sigaction(SIGABRT, &action, NULL); // abort() called. sigaction(SIGTERM, &action, NULL); // kill command sigaction(SIGSTOP, &action, NULL); // kill command #endif if (arguments) { gArguments = *arguments; if (!gArguments.parse(argc, argv)) { exit(1); // Exit if not all require arguments are provided } std::string argumentString = gArguments.printList(); if (argumentString.size() > 0) { std::cout << "Program Arguments:\n" << argumentString << std::endl; } } gRun = true; // Setup Window for Output, initialize the GL and GLFW #ifdef VIBRANTE bool offscreen = false; if (gArguments.has("offscreen")) { const std::string offscreenString = gArguments.get("offscreen"); if (offscreenString.compare("")) { offscreen = std::stoi(offscreenString) ? true : false; } } if (offscreen) gWindow = new WindowOffscreenEGL(width, height); #endif try { gWindow = gWindow ? gWindow : new WindowGLFW(width, height); } catch (const std::exception &/*ex*/) { #ifdef VIBRANTE gWindow = new WindowOffscreenEGL(width, height); #else gWindow = nullptr; #endif } if (gWindow == nullptr) return false; gWindow->makeCurrent(); gWindow->setOnKeypressCallback(keyPressCallback); return true; } void releaseSampleApp() { // Shutdown delete gWindow; gWindow = nullptr; }
30.362745
103
0.618448
vehicularkech
33c70101bc3ea6a7e21263b245b9589dd07c9798
492
hpp
C++
include/cjdb/functional/invoke.hpp
cjdb/clang-concepts-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
4
2019-03-02T01:09:07.000Z
2019-10-16T15:46:21.000Z
include/cjdb/functional/invoke.hpp
cjdb/cjdb-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
5
2019-11-29T12:23:55.000Z
2019-12-14T13:03:00.000Z
include/cjdb/functional/invoke.hpp
cjdb/clang-concepts-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
3
2020-06-08T18:27:28.000Z
2021-03-27T17:49:46.000Z
// Copyright (c) Christopher Di Bella. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // #ifndef CJDB_FUNCTIONAL_INVOKE_HPP #define CJDB_FUNCTIONAL_INVOKE_HPP #include "cjdb/detail/functional/invoke.hpp" namespace cjdb { /// \brief An entity used to call function-like entities generically. /// \note cjdb::invoke is a niebloid. /// \see [func.invoke] /// constexpr inline auto invoke = detail_invoke::invoke_fn{}; } // namespace cjdb #endif // CJDB_FUNCTIONAL_INVOKE_HPP
27.333333
70
0.752033
cjdb
33c8bc2b46e8d54bb2de64d35be47e2e946c60c6
3,260
cpp
C++
engine/source/wide/ui/property/basic/ui_property_base.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
engine/source/wide/ui/property/basic/ui_property_base.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
engine/source/wide/ui/property/basic/ui_property_base.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------------------------// /// @file wide/ui/property/basic/ui_property_base.cpp //------------------------------------------------------------------------------------------------// //-INCLUDES---------------------------------------------------------------------------------------// #include "wide/ui/property/basic/ui_property_base.h" #include "wide/ui/property/ui_property_manager.h" #include "wide/ui/property/ui_property_list.h" #include "wide/ui/window/ui_window_manager.h" //------------------------------------------------------------------------------------------------// namespace coffee { //-META---------------------------------------------------------------------------------------// COFFEE_BeginType(ui::PropertyBase); COFFEE_Ancestor(ui::Property); COFFEE_EndType(); namespace ui { //-CONSTRUCTORS-------------------------------------------------------------------------------// PropertyBase::PropertyBase() : _ObjectInfo(NULL) { } //--------------------------------------------------------------------------------------------// PropertyBase::~PropertyBase() { if (_ObjectInfo!=NULL) _ObjectInfo->Destroy(); } //-OPERATIONS---------------------------------------------------------------------------------// void PropertyBase::CreateContent() { basic::PropertyBase* prop = (basic::PropertyBase *) GetData(); if(prop->IsScalar()) { _ObjectInfo = COFFEE_New(meta::ObjectInfo, ((basic::PropertyScalar *) prop->GetObject())->GetObject(), (meta::Type*)prop->GetType(), &_Attribute); _ObjectInfo->SetName(prop->GetName()); _Attribute._Param = COFFEE_New(meta::Param); PropertyManager::Get().CreatePropertyInterface( *this, *_ObjectInfo, prop->GetType(), NULL, 0); } else { _ObjectInfo = COFFEE_New(meta::ObjectInfo, (void *) prop->GetObject(), (meta::Type*)prop->GetType(), &_Attribute); _ObjectInfo->SetName(prop->GetName()); _Attribute._Param = COFFEE_New(meta::Param); if(PropertyManager::Get().CreatePropertyInterface( *this, *_ObjectInfo, prop->GetType(), NULL, PROPERTY_FLAG_Root)==NULL) { widget::Group* group; group = COFFEE_New(widget::Group); group->Create(this, basic::Vector2i(), basic::Vector2i(GetClientRect().Size.X, 20)); group->SetTitleBarText(prop->GetName()); PropertyList* list; list = COFFEE_New(PropertyList); list->Create(*prop->GetObject(), basic::Vector2i(), basic::Vector2i(), group, false); } } } //-EVENTS-------------------------------------------------------------------------------------// COFFEE_BeginEventHandler(PropertyBase, Property) COFFEE_EndEventHandler() } } //------------------------------------------------------------------------------------------------//
36.629213
101
0.401227
skarab
33ca9894af9b0e54f4ecb690499bec65c4a395f4
1,835
cpp
C++
v1.0/src/test/PGI_OpenACC/MatMul/MatMul.cpp
dikujepsen/OpenTran
af9654fcf55e394e7bece38e59bbdc3dd343f092
[ "MIT" ]
1
2015-02-09T12:56:07.000Z
2015-02-09T12:56:07.000Z
v1.0/src/test/PGI_OpenACC/MatMul/MatMul.cpp
dikujepsen/OpenTran
af9654fcf55e394e7bece38e59bbdc3dd343f092
[ "MIT" ]
null
null
null
v1.0/src/test/PGI_OpenACC/MatMul/MatMul.cpp
dikujepsen/OpenTran
af9654fcf55e394e7bece38e59bbdc3dd343f092
[ "MIT" ]
null
null
null
#include <cstdlib> #include <cstdio> #include <iostream> #include "../../../utils/Stopwatch.cpp" Stopwatch timer; #include <openacc.h> using namespace std; void matmul(float* A, float* B, float* C, unsigned hA, unsigned wA, unsigned wB) { #ifndef CPU #ifdef READBACK #pragma acc kernels loop copyin(A[0:hA*wA], B[0:wB*wA]) copyout(C[0:wB*hA] ) independent #else #pragma acc kernels loop copyin(A[0:hA*wA], B[0:wB*wA]) local(C[0:wB*hA] ) independent #endif #endif for (unsigned i = 0; i < hA; i++) { for (unsigned j = 0; j < wB; j++) { float sum = 0; for (unsigned k = 0; k < wA; k++) { sum += A[i * wA + k] * B[k * wB + j]; } C[i * wB + j] = sum; } } } void randMat(float* mat, unsigned mat_size) { for (unsigned i = 0; i < mat_size; ++i) { mat[i] = (float)((rand() % 10)/10.0); } } void printMat(float* mat, unsigned mat_size) { for (unsigned i = 0; i < mat_size; ++i) { cout << mat[i] << " "; if (i % 10 == 0) { cout << endl; } } cout << endl; } // #define matsize 3584 //#define matsize 9216 int main(int argc, char** argv) { unsigned matsize; ParseCommandLine(argc, argv, &matsize, NULL, NULL); unsigned hA = matsize; unsigned hB = matsize; unsigned hC = matsize; unsigned wA = matsize; unsigned wB = matsize; unsigned wC = matsize; unsigned A_size = hA*wA; unsigned B_size = hB*wB; unsigned C_size = hC*wC; float* A_mat = new float[A_size]; float* B_mat = new float[B_size]; float* C_mat = new float[C_size]; srand(2013); randMat(A_mat,A_size); randMat(B_mat,B_size); randMat(C_mat,C_size); acc_init( acc_device_nvidia ); timer.start(); matmul(A_mat, B_mat, C_mat, hA, wA, wB); cout << timer.stop() << endl; #if PRINT printMat(C_mat, 100); #endif free(A_mat); free(B_mat); free(C_mat); }
19.521277
89
0.60436
dikujepsen
33ce799228197553e802b5e2ad31dbb39a368b04
93,493
cpp
C++
kcfi/llvm-kcfi/tools/clang/lib/Lex/PPDirectives.cpp
IntelSTORM/Projects
b983417a5ca22c7679da5a1144b348863bea5698
[ "Intel" ]
1
2022-01-11T11:12:00.000Z
2022-01-11T11:12:00.000Z
kcfi/llvm-kcfi/tools/clang/lib/Lex/PPDirectives.cpp
IntelSTORMteam/Jurassic-Projects
b983417a5ca22c7679da5a1144b348863bea5698
[ "Intel" ]
null
null
null
kcfi/llvm-kcfi/tools/clang/lib/Lex/PPDirectives.cpp
IntelSTORMteam/Jurassic-Projects
b983417a5ca22c7679da5a1144b348863bea5698
[ "Intel" ]
null
null
null
//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Implements # directive processing for the Preprocessor. /// //===----------------------------------------------------------------------===// #include "clang/Lex/Preprocessor.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/LiteralSupport.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/ModuleLoader.h" #include "clang/Lex/Pragma.h" #include "llvm/ADT/APInt.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Path.h" #include "llvm/Support/SaveAndRestore.h" using namespace clang; //===----------------------------------------------------------------------===// // Utility Methods for Preprocessor Directive Handling. //===----------------------------------------------------------------------===// MacroInfo *Preprocessor::AllocateMacroInfo() { MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>(); MIChain->Next = MIChainHead; MIChainHead = MIChain; return &MIChain->MI; } MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) { MacroInfo *MI = AllocateMacroInfo(); new (MI) MacroInfo(L); return MI; } MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L, unsigned SubModuleID) { static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID), "alignment for MacroInfo is less than the ID"); DeserializedMacroInfoChain *MIChain = BP.Allocate<DeserializedMacroInfoChain>(); MIChain->Next = DeserialMIChainHead; DeserialMIChainHead = MIChain; MacroInfo *MI = &MIChain->MI; new (MI) MacroInfo(L); MI->FromASTFile = true; MI->setOwningModuleID(SubModuleID); return MI; } DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc) { return new (BP) DefMacroDirective(MI, Loc); } UndefMacroDirective * Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) { return new (BP) UndefMacroDirective(UndefLoc); } VisibilityMacroDirective * Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc, bool isPublic) { return new (BP) VisibilityMacroDirective(Loc, isPublic); } /// \brief Read and discard all tokens remaining on the current line until /// the tok::eod token is found. void Preprocessor::DiscardUntilEndOfDirective() { Token Tmp; do { LexUnexpandedToken(Tmp); assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens"); } while (Tmp.isNot(tok::eod)); } /// \brief Enumerates possible cases of #define/#undef a reserved identifier. enum MacroDiag { MD_NoWarn, //> Not a reserved identifier MD_KeywordDef, //> Macro hides keyword, enabled by default MD_ReservedMacro //> #define of #undef reserved id, disabled by default }; /// \brief Checks if the specified identifier is reserved in the specified /// language. /// This function does not check if the identifier is a keyword. static bool isReservedId(StringRef Text, const LangOptions &Lang) { // C++ [macro.names], C11 7.1.3: // All identifiers that begin with an underscore and either an uppercase // letter or another underscore are always reserved for any use. if (Text.size() >= 2 && Text[0] == '_' && (isUppercase(Text[1]) || Text[1] == '_')) return true; // C++ [global.names] // Each name that contains a double underscore ... is reserved to the // implementation for any use. if (Lang.CPlusPlus) { if (Text.find("__") != StringRef::npos) return true; } return false; } static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) { const LangOptions &Lang = PP.getLangOpts(); StringRef Text = II->getName(); if (isReservedId(Text, Lang)) return MD_ReservedMacro; if (II->isKeyword(Lang)) return MD_KeywordDef; if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final"))) return MD_KeywordDef; return MD_NoWarn; } static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) { const LangOptions &Lang = PP.getLangOpts(); StringRef Text = II->getName(); // Do not warn on keyword undef. It is generally harmless and widely used. if (isReservedId(Text, Lang)) return MD_ReservedMacro; return MD_NoWarn; } bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef, bool *ShadowFlag) { // Missing macro name? if (MacroNameTok.is(tok::eod)) return Diag(MacroNameTok, diag::err_pp_missing_macro_name); IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); if (!II) { bool Invalid = false; std::string Spelling = getSpelling(MacroNameTok, &Invalid); if (Invalid) return Diag(MacroNameTok, diag::err_pp_macro_not_identifier); II = getIdentifierInfo(Spelling); if (!II->isCPlusPlusOperatorKeyword()) return Diag(MacroNameTok, diag::err_pp_macro_not_identifier); // C++ 2.5p2: Alternative tokens behave the same as its primary token // except for their spellings. Diag(MacroNameTok, getLangOpts().MicrosoftExt ? diag::ext_pp_operator_used_as_macro_name : diag::err_pp_operator_used_as_macro_name) << II << MacroNameTok.getKind(); // Allow #defining |and| and friends for Microsoft compatibility or // recovery when legacy C headers are included in C++. MacroNameTok.setIdentifierInfo(II); } if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) { // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4. return Diag(MacroNameTok, diag::err_defined_macro_name); } if (isDefineUndef == MU_Undef) { auto *MI = getMacroInfo(II); if (MI && MI->isBuiltinMacro()) { // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4 // and C++ [cpp.predefined]p4], but allow it as an extension. Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro); } } // If defining/undefining reserved identifier or a keyword, we need to issue // a warning. SourceLocation MacroNameLoc = MacroNameTok.getLocation(); if (ShadowFlag) *ShadowFlag = false; if (!SourceMgr.isInSystemHeader(MacroNameLoc) && (strcmp(SourceMgr.getBufferName(MacroNameLoc), "<built-in>") != 0)) { MacroDiag D = MD_NoWarn; if (isDefineUndef == MU_Define) { D = shouldWarnOnMacroDef(*this, II); } else if (isDefineUndef == MU_Undef) D = shouldWarnOnMacroUndef(*this, II); if (D == MD_KeywordDef) { // We do not want to warn on some patterns widely used in configuration // scripts. This requires analyzing next tokens, so do not issue warnings // now, only inform caller. if (ShadowFlag) *ShadowFlag = true; } if (D == MD_ReservedMacro) Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id); } // Okay, we got a good identifier. return false; } /// \brief Lex and validate a macro name, which occurs after a /// \#define or \#undef. /// /// This sets the token kind to eod and discards the rest of the macro line if /// the macro name is invalid. /// /// \param MacroNameTok Token that is expected to be a macro name. /// \param isDefineUndef Context in which macro is used. /// \param ShadowFlag Points to a flag that is set if macro shadows a keyword. void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef, bool *ShadowFlag) { // Read the token, don't allow macro expansion on it. LexUnexpandedToken(MacroNameTok); if (MacroNameTok.is(tok::code_completion)) { if (CodeComplete) CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define); setCodeCompletionReached(); LexUnexpandedToken(MacroNameTok); } if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag)) return; // Invalid macro name, read and discard the rest of the line and set the // token kind to tok::eod if necessary. if (MacroNameTok.isNot(tok::eod)) { MacroNameTok.setKind(tok::eod); DiscardUntilEndOfDirective(); } } /// \brief Ensure that the next token is a tok::eod token. /// /// If not, emit a diagnostic and consume up until the eod. If EnableMacros is /// true, then we consider macros that expand to zero tokens as being ok. void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) { Token Tmp; // Lex unexpanded tokens for most directives: macros might expand to zero // tokens, causing us to miss diagnosing invalid lines. Some directives (like // #line) allow empty macros. if (EnableMacros) Lex(Tmp); else LexUnexpandedToken(Tmp); // There should be no tokens after the directive, but we allow them as an // extension. while (Tmp.is(tok::comment)) // Skip comments in -C mode. LexUnexpandedToken(Tmp); if (Tmp.isNot(tok::eod)) { // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89, // or if this is a macro-style preprocessing directive, because it is more // trouble than it is worth to insert /**/ and check that there is no /**/ // in the range also. FixItHint Hint; if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) && !CurTokenLexer) Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//"); Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint; DiscardUntilEndOfDirective(); } } /// SkipExcludedConditionalBlock - We just read a \#if or related directive and /// decided that the subsequent tokens are in the \#if'd out portion of the /// file. Lex the rest of the file, until we see an \#endif. If /// FoundNonSkipPortion is true, then we have already emitted code for part of /// this \#if directive, so \#else/\#elif blocks should never be entered. /// If ElseOk is true, then \#else directives are ok, if not, then we have /// already seen one so a \#else directive is a duplicate. When this returns, /// the caller can lex the first valid token. void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, bool FoundNonSkipPortion, bool FoundElse, SourceLocation ElseLoc) { ++NumSkipped; assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?"); CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false, FoundNonSkipPortion, FoundElse); if (CurPTHLexer) { PTHSkipExcludedConditionalBlock(); return; } // Enter raw mode to disable identifier lookup (and thus macro expansion), // disabling warnings, etc. CurPPLexer->LexingRawMode = true; Token Tok; while (1) { CurLexer->Lex(Tok); if (Tok.is(tok::code_completion)) { if (CodeComplete) CodeComplete->CodeCompleteInConditionalExclusion(); setCodeCompletionReached(); continue; } // If this is the end of the buffer, we have an error. if (Tok.is(tok::eof)) { // Emit errors for each unterminated conditional on the stack, including // the current one. while (!CurPPLexer->ConditionalStack.empty()) { if (CurLexer->getFileLoc() != CodeCompletionFileLoc) Diag(CurPPLexer->ConditionalStack.back().IfLoc, diag::err_pp_unterminated_conditional); CurPPLexer->ConditionalStack.pop_back(); } // Just return and let the caller lex after this #include. break; } // If this token is not a preprocessor directive, just skip it. if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) continue; // We just parsed a # character at the start of a line, so we're in // directive mode. Tell the lexer this so any newlines we see will be // converted into an EOD token (this terminates the macro). CurPPLexer->ParsingPreprocessorDirective = true; if (CurLexer) CurLexer->SetKeepWhitespaceMode(false); // Read the next token, the directive flavor. LexUnexpandedToken(Tok); // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or // something bogus), skip it. if (Tok.isNot(tok::raw_identifier)) { CurPPLexer->ParsingPreprocessorDirective = false; // Restore comment saving mode. if (CurLexer) CurLexer->resetExtendedTokenMode(); continue; } // If the first letter isn't i or e, it isn't intesting to us. We know that // this is safe in the face of spelling differences, because there is no way // to spell an i/e in a strange way that is another letter. Skipping this // allows us to avoid looking up the identifier info for #define/#undef and // other common directives. StringRef RI = Tok.getRawIdentifier(); char FirstChar = RI[0]; if (FirstChar >= 'a' && FirstChar <= 'z' && FirstChar != 'i' && FirstChar != 'e') { CurPPLexer->ParsingPreprocessorDirective = false; // Restore comment saving mode. if (CurLexer) CurLexer->resetExtendedTokenMode(); continue; } // Get the identifier name without trigraphs or embedded newlines. Note // that we can't use Tok.getIdentifierInfo() because its lookup is disabled // when skipping. char DirectiveBuf[20]; StringRef Directive; if (!Tok.needsCleaning() && RI.size() < 20) { Directive = RI; } else { std::string DirectiveStr = getSpelling(Tok); unsigned IdLen = DirectiveStr.size(); if (IdLen >= 20) { CurPPLexer->ParsingPreprocessorDirective = false; // Restore comment saving mode. if (CurLexer) CurLexer->resetExtendedTokenMode(); continue; } memcpy(DirectiveBuf, &DirectiveStr[0], IdLen); Directive = StringRef(DirectiveBuf, IdLen); } if (Directive.startswith("if")) { StringRef Sub = Directive.substr(2); if (Sub.empty() || // "if" Sub == "def" || // "ifdef" Sub == "ndef") { // "ifndef" // We know the entire #if/#ifdef/#ifndef block will be skipped, don't // bother parsing the condition. DiscardUntilEndOfDirective(); CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true, /*foundnonskip*/false, /*foundelse*/false); } } else if (Directive[0] == 'e') { StringRef Sub = Directive.substr(1); if (Sub == "ndif") { // "endif" PPConditionalInfo CondInfo; CondInfo.WasSkipping = true; // Silence bogus warning. bool InCond = CurPPLexer->popConditionalLevel(CondInfo); (void)InCond; // Silence warning in no-asserts mode. assert(!InCond && "Can't be skipping if not in a conditional!"); // If we popped the outermost skipping block, we're done skipping! if (!CondInfo.WasSkipping) { // Restore the value of LexingRawMode so that trailing comments // are handled correctly, if we've reached the outermost block. CurPPLexer->LexingRawMode = false; CheckEndOfDirective("endif"); CurPPLexer->LexingRawMode = true; if (Callbacks) Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc); break; } else { DiscardUntilEndOfDirective(); } } else if (Sub == "lse") { // "else". // #else directive in a skipping conditional. If not in some other // skipping conditional, and if #else hasn't already been seen, enter it // as a non-skipping conditional. PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); // If this is a #else with a #else before it, report the error. if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else); // Note that we've seen a #else in this conditional. CondInfo.FoundElse = true; // If the conditional is at the top level, and the #if block wasn't // entered, enter the #else block now. if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) { CondInfo.FoundNonSkip = true; // Restore the value of LexingRawMode so that trailing comments // are handled correctly. CurPPLexer->LexingRawMode = false; CheckEndOfDirective("else"); CurPPLexer->LexingRawMode = true; if (Callbacks) Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc); break; } else { DiscardUntilEndOfDirective(); // C99 6.10p4. } } else if (Sub == "lif") { // "elif". PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); // If this is a #elif with a #else before it, report the error. if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else); // If this is in a skipping block or if we're already handled this #if // block, don't bother parsing the condition. if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) { DiscardUntilEndOfDirective(); } else { const SourceLocation CondBegin = CurPPLexer->getSourceLocation(); // Restore the value of LexingRawMode so that identifiers are // looked up, etc, inside the #elif expression. assert(CurPPLexer->LexingRawMode && "We have to be skipping here!"); CurPPLexer->LexingRawMode = false; IdentifierInfo *IfNDefMacro = nullptr; const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro); CurPPLexer->LexingRawMode = true; if (Callbacks) { const SourceLocation CondEnd = CurPPLexer->getSourceLocation(); Callbacks->Elif(Tok.getLocation(), SourceRange(CondBegin, CondEnd), (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc); } // If this condition is true, enter it! if (CondValue) { CondInfo.FoundNonSkip = true; break; } } } } CurPPLexer->ParsingPreprocessorDirective = false; // Restore comment saving mode. if (CurLexer) CurLexer->resetExtendedTokenMode(); } // Finally, if we are out of the conditional (saw an #endif or ran off the end // of the file, just stop skipping and return to lexing whatever came after // the #if block. CurPPLexer->LexingRawMode = false; if (Callbacks) { SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc; Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation())); } } void Preprocessor::PTHSkipExcludedConditionalBlock() { while (1) { assert(CurPTHLexer); assert(CurPTHLexer->LexingRawMode == false); // Skip to the next '#else', '#elif', or #endif. if (CurPTHLexer->SkipBlock()) { // We have reached an #endif. Both the '#' and 'endif' tokens // have been consumed by the PTHLexer. Just pop off the condition level. PPConditionalInfo CondInfo; bool InCond = CurPTHLexer->popConditionalLevel(CondInfo); (void)InCond; // Silence warning in no-asserts mode. assert(!InCond && "Can't be skipping if not in a conditional!"); break; } // We have reached a '#else' or '#elif'. Lex the next token to get // the directive flavor. Token Tok; LexUnexpandedToken(Tok); // We can actually look up the IdentifierInfo here since we aren't in // raw mode. tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID(); if (K == tok::pp_else) { // #else: Enter the else condition. We aren't in a nested condition // since we skip those. We're always in the one matching the last // blocked we skipped. PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); // Note that we've seen a #else in this conditional. CondInfo.FoundElse = true; // If the #if block wasn't entered then enter the #else block now. if (!CondInfo.FoundNonSkip) { CondInfo.FoundNonSkip = true; // Scan until the eod token. CurPTHLexer->ParsingPreprocessorDirective = true; DiscardUntilEndOfDirective(); CurPTHLexer->ParsingPreprocessorDirective = false; break; } // Otherwise skip this block. continue; } assert(K == tok::pp_elif); PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); // If this is a #elif with a #else before it, report the error. if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else); // If this is in a skipping block or if we're already handled this #if // block, don't bother parsing the condition. We just skip this block. if (CondInfo.FoundNonSkip) continue; // Evaluate the condition of the #elif. IdentifierInfo *IfNDefMacro = nullptr; CurPTHLexer->ParsingPreprocessorDirective = true; bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro); CurPTHLexer->ParsingPreprocessorDirective = false; // If this condition is true, enter it! if (ShouldEnter) { CondInfo.FoundNonSkip = true; break; } // Otherwise, skip this block and go to the next one. continue; } } Module *Preprocessor::getModuleForLocation(SourceLocation Loc) { ModuleMap &ModMap = HeaderInfo.getModuleMap(); if (SourceMgr.isInMainFile(Loc)) { if (Module *CurMod = getCurrentModule()) return CurMod; // Compiling a module. return HeaderInfo.getModuleMap().SourceModule; // Compiling a source. } // Try to determine the module of the include directive. // FIXME: Look into directly passing the FileEntry from LookupFile instead. FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc)); if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) { // The include comes from a file. return ModMap.findModuleForHeader(EntryOfIncl).getModule(); } else { // The include does not come from a file, // so it is probably a module compilation. return getCurrentModule(); } } Module *Preprocessor::getModuleContainingLocation(SourceLocation Loc) { return HeaderInfo.getModuleMap().inferModuleFromLocation( FullSourceLoc(Loc, SourceMgr)); } const FileEntry *Preprocessor::LookupFile( SourceLocation FilenameLoc, StringRef Filename, bool isAngled, const DirectoryLookup *FromDir, const FileEntry *FromFile, const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) { // If the header lookup mechanism may be relative to the current inclusion // stack, record the parent #includes. SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16> Includers; if (!FromDir && !FromFile) { FileID FID = getCurrentFileLexer()->getFileID(); const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID); // If there is no file entry associated with this file, it must be the // predefines buffer or the module includes buffer. Any other file is not // lexed with a normal lexer, so it won't be scanned for preprocessor // directives. // // If we have the predefines buffer, resolve #include references (which come // from the -include command line argument) from the current working // directory instead of relative to the main file. // // If we have the module includes buffer, resolve #include references (which // come from header declarations in the module map) relative to the module // map file. if (!FileEnt) { if (FID == SourceMgr.getMainFileID() && MainFileDir) Includers.push_back(std::make_pair(nullptr, MainFileDir)); else if ((FileEnt = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))) Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory("."))); } else { Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir())); } // MSVC searches the current include stack from top to bottom for // headers included by quoted include directives. // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx if (LangOpts.MSVCCompat && !isAngled) { for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1]; if (IsFileLexer(ISEntry)) if ((FileEnt = SourceMgr.getFileEntryForID( ISEntry.ThePPLexer->getFileID()))) Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir())); } } } CurDir = CurDirLookup; if (FromFile) { // We're supposed to start looking from after a particular file. Search // the include path until we find that file or run out of files. const DirectoryLookup *TmpCurDir = CurDir; const DirectoryLookup *TmpFromDir = nullptr; while (const FileEntry *FE = HeaderInfo.LookupFile( Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir, Includers, SearchPath, RelativePath, SuggestedModule, SkipCache)) { // Keep looking as if this file did a #include_next. TmpFromDir = TmpCurDir; ++TmpFromDir; if (FE == FromFile) { // Found it. FromDir = TmpFromDir; CurDir = TmpCurDir; break; } } } // Do a standard file entry lookup. const FileEntry *FE = HeaderInfo.LookupFile( Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath, RelativePath, SuggestedModule, SkipCache); if (FE) { if (SuggestedModule && !LangOpts.AsmPreprocessor) HeaderInfo.getModuleMap().diagnoseHeaderInclusion( getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE); return FE; } const FileEntry *CurFileEnt; // Otherwise, see if this is a subframework header. If so, this is relative // to one of the headers on the #include stack. Walk the list of the current // headers on the #include stack and pass them to HeaderInfo. if (IsFileLexer()) { if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))) { if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt, SearchPath, RelativePath, SuggestedModule))) { if (SuggestedModule && !LangOpts.AsmPreprocessor) HeaderInfo.getModuleMap().diagnoseHeaderInclusion( getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE); return FE; } } } for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1]; if (IsFileLexer(ISEntry)) { if ((CurFileEnt = SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) { if ((FE = HeaderInfo.LookupSubframeworkHeader( Filename, CurFileEnt, SearchPath, RelativePath, SuggestedModule))) { if (SuggestedModule && !LangOpts.AsmPreprocessor) HeaderInfo.getModuleMap().diagnoseHeaderInclusion( getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE); return FE; } } } } // Otherwise, we really couldn't find the file. return nullptr; } //===----------------------------------------------------------------------===// // Preprocessor Directive Handling. //===----------------------------------------------------------------------===// class Preprocessor::ResetMacroExpansionHelper { public: ResetMacroExpansionHelper(Preprocessor *pp) : PP(pp), save(pp->DisableMacroExpansion) { if (pp->MacroExpansionInDirectivesOverride) pp->DisableMacroExpansion = false; } ~ResetMacroExpansionHelper() { PP->DisableMacroExpansion = save; } private: Preprocessor *PP; bool save; }; /// HandleDirective - This callback is invoked when the lexer sees a # token /// at the start of a line. This consumes the directive, modifies the /// lexer/preprocessor state, and advances the lexer(s) so that the next token /// read is the correct one. void Preprocessor::HandleDirective(Token &Result) { // FIXME: Traditional: # with whitespace before it not recognized by K&R? // We just parsed a # character at the start of a line, so we're in directive // mode. Tell the lexer this so any newlines we see will be converted into an // EOD token (which terminates the directive). CurPPLexer->ParsingPreprocessorDirective = true; if (CurLexer) CurLexer->SetKeepWhitespaceMode(false); bool ImmediatelyAfterTopLevelIfndef = CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef(); CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef(); ++NumDirectives; // We are about to read a token. For the multiple-include optimization FA to // work, we have to remember if we had read any tokens *before* this // pp-directive. bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal(); // Save the '#' token in case we need to return it later. Token SavedHash = Result; // Read the next token, the directive flavor. This isn't expanded due to // C99 6.10.3p8. LexUnexpandedToken(Result); // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.: // #define A(x) #x // A(abc // #warning blah // def) // If so, the user is relying on undefined behavior, emit a diagnostic. Do // not support this for #include-like directives, since that can result in // terrible diagnostics, and does not work in GCC. if (InMacroArgs) { if (IdentifierInfo *II = Result.getIdentifierInfo()) { switch (II->getPPKeywordID()) { case tok::pp_include: case tok::pp_import: case tok::pp_include_next: case tok::pp___include_macros: case tok::pp_pragma: Diag(Result, diag::err_embedded_directive) << II->getName(); DiscardUntilEndOfDirective(); return; default: break; } } Diag(Result, diag::ext_embedded_directive); } // Temporarily enable macro expansion if set so // and reset to previous state when returning from this function. ResetMacroExpansionHelper helper(this); switch (Result.getKind()) { case tok::eod: return; // null directive. case tok::code_completion: if (CodeComplete) CodeComplete->CodeCompleteDirective( CurPPLexer->getConditionalStackDepth() > 0); setCodeCompletionReached(); return; case tok::numeric_constant: // # 7 GNU line marker directive. if (getLangOpts().AsmPreprocessor) break; // # 4 is not a preprocessor directive in .S files. return HandleDigitDirective(Result); default: IdentifierInfo *II = Result.getIdentifierInfo(); if (!II) break; // Not an identifier. // Ask what the preprocessor keyword ID is. switch (II->getPPKeywordID()) { default: break; // C99 6.10.1 - Conditional Inclusion. case tok::pp_if: return HandleIfDirective(Result, ReadAnyTokensBeforeDirective); case tok::pp_ifdef: return HandleIfdefDirective(Result, false, true/*not valid for miopt*/); case tok::pp_ifndef: return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective); case tok::pp_elif: return HandleElifDirective(Result); case tok::pp_else: return HandleElseDirective(Result); case tok::pp_endif: return HandleEndifDirective(Result); // C99 6.10.2 - Source File Inclusion. case tok::pp_include: // Handle #include. return HandleIncludeDirective(SavedHash.getLocation(), Result); case tok::pp___include_macros: // Handle -imacros. return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result); // C99 6.10.3 - Macro Replacement. case tok::pp_define: return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef); case tok::pp_undef: return HandleUndefDirective(Result); // C99 6.10.4 - Line Control. case tok::pp_line: return HandleLineDirective(Result); // C99 6.10.5 - Error Directive. case tok::pp_error: return HandleUserDiagnosticDirective(Result, false); // C99 6.10.6 - Pragma Directive. case tok::pp_pragma: return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma); // GNU Extensions. case tok::pp_import: return HandleImportDirective(SavedHash.getLocation(), Result); case tok::pp_include_next: return HandleIncludeNextDirective(SavedHash.getLocation(), Result); case tok::pp_warning: Diag(Result, diag::ext_pp_warning_directive); return HandleUserDiagnosticDirective(Result, true); case tok::pp_ident: return HandleIdentSCCSDirective(Result); case tok::pp_sccs: return HandleIdentSCCSDirective(Result); case tok::pp_assert: //isExtension = true; // FIXME: implement #assert break; case tok::pp_unassert: //isExtension = true; // FIXME: implement #unassert break; case tok::pp___public_macro: if (getLangOpts().Modules) return HandleMacroPublicDirective(Result); break; case tok::pp___private_macro: if (getLangOpts().Modules) return HandleMacroPrivateDirective(Result); break; } break; } // If this is a .S file, treat unknown # directives as non-preprocessor // directives. This is important because # may be a comment or introduce // various pseudo-ops. Just return the # token and push back the following // token to be lexed next time. if (getLangOpts().AsmPreprocessor) { Token *Toks = new Token[2]; // Return the # and the token after it. Toks[0] = SavedHash; Toks[1] = Result; // If the second token is a hashhash token, then we need to translate it to // unknown so the token lexer doesn't try to perform token pasting. if (Result.is(tok::hashhash)) Toks[1].setKind(tok::unknown); // Enter this token stream so that we re-lex the tokens. Make sure to // enable macro expansion, in case the token after the # is an identifier // that is expanded. EnterTokenStream(Toks, 2, false, true); return; } // If we reached here, the preprocessing token is not valid! Diag(Result, diag::err_pp_invalid_directive); // Read the rest of the PP line. DiscardUntilEndOfDirective(); // Okay, we're done parsing the directive. } /// GetLineValue - Convert a numeric token into an unsigned value, emitting /// Diagnostic DiagID if it is invalid, and returning the value in Val. static bool GetLineValue(Token &DigitTok, unsigned &Val, unsigned DiagID, Preprocessor &PP, bool IsGNULineDirective=false) { if (DigitTok.isNot(tok::numeric_constant)) { PP.Diag(DigitTok, DiagID); if (DigitTok.isNot(tok::eod)) PP.DiscardUntilEndOfDirective(); return true; } SmallString<64> IntegerBuffer; IntegerBuffer.resize(DigitTok.getLength()); const char *DigitTokBegin = &IntegerBuffer[0]; bool Invalid = false; unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid); if (Invalid) return true; // Verify that we have a simple digit-sequence, and compute the value. This // is always a simple digit string computed in decimal, so we do this manually // here. Val = 0; for (unsigned i = 0; i != ActualLength; ++i) { // C++1y [lex.fcon]p1: // Optional separating single quotes in a digit-sequence are ignored if (DigitTokBegin[i] == '\'') continue; if (!isDigit(DigitTokBegin[i])) { PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i), diag::err_pp_line_digit_sequence) << IsGNULineDirective; PP.DiscardUntilEndOfDirective(); return true; } unsigned NextVal = Val*10+(DigitTokBegin[i]-'0'); if (NextVal < Val) { // overflow. PP.Diag(DigitTok, DiagID); PP.DiscardUntilEndOfDirective(); return true; } Val = NextVal; } if (DigitTokBegin[0] == '0' && Val) PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal) << IsGNULineDirective; return false; } /// \brief Handle a \#line directive: C99 6.10.4. /// /// The two acceptable forms are: /// \verbatim /// # line digit-sequence /// # line digit-sequence "s-char-sequence" /// \endverbatim void Preprocessor::HandleLineDirective(Token &Tok) { // Read the line # and string argument. Per C99 6.10.4p5, these tokens are // expanded. Token DigitTok; Lex(DigitTok); // Validate the number and convert it to an unsigned. unsigned LineNo; if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this)) return; if (LineNo == 0) Diag(DigitTok, diag::ext_pp_line_zero); // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a // number greater than 2147483647". C90 requires that the line # be <= 32767. unsigned LineLimit = 32768U; if (LangOpts.C99 || LangOpts.CPlusPlus11) LineLimit = 2147483648U; if (LineNo >= LineLimit) Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit; else if (LangOpts.CPlusPlus11 && LineNo >= 32768U) Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big); int FilenameID = -1; Token StrTok; Lex(StrTok); // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a // string followed by eod. if (StrTok.is(tok::eod)) ; // ok else if (StrTok.isNot(tok::string_literal)) { Diag(StrTok, diag::err_pp_line_invalid_filename); return DiscardUntilEndOfDirective(); } else if (StrTok.hasUDSuffix()) { Diag(StrTok, diag::err_invalid_string_udl); return DiscardUntilEndOfDirective(); } else { // Parse and validate the string, converting it into a unique ID. StringLiteralParser Literal(StrTok, *this); assert(Literal.isAscii() && "Didn't allow wide strings in"); if (Literal.hadError) return DiscardUntilEndOfDirective(); if (Literal.Pascal) { Diag(StrTok, diag::err_pp_linemarker_invalid_filename); return DiscardUntilEndOfDirective(); } FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString()); // Verify that there is nothing after the string, other than EOD. Because // of C99 6.10.4p5, macros that expand to empty tokens are ok. CheckEndOfDirective("line", true); } SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID); if (Callbacks) Callbacks->FileChanged(CurPPLexer->getSourceLocation(), PPCallbacks::RenameFile, SrcMgr::C_User); } /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line /// marker directive. static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit, bool &IsSystemHeader, bool &IsExternCHeader, Preprocessor &PP) { unsigned FlagVal; Token FlagTok; PP.Lex(FlagTok); if (FlagTok.is(tok::eod)) return false; if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP)) return true; if (FlagVal == 1) { IsFileEntry = true; PP.Lex(FlagTok); if (FlagTok.is(tok::eod)) return false; if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) return true; } else if (FlagVal == 2) { IsFileExit = true; SourceManager &SM = PP.getSourceManager(); // If we are leaving the current presumed file, check to make sure the // presumed include stack isn't empty! FileID CurFileID = SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first; PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation()); if (PLoc.isInvalid()) return true; // If there is no include loc (main file) or if the include loc is in a // different physical file, then we aren't in a "1" line marker flag region. SourceLocation IncLoc = PLoc.getIncludeLoc(); if (IncLoc.isInvalid() || SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) { PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop); PP.DiscardUntilEndOfDirective(); return true; } PP.Lex(FlagTok); if (FlagTok.is(tok::eod)) return false; if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) return true; } // We must have 3 if there are still flags. if (FlagVal != 3) { PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); PP.DiscardUntilEndOfDirective(); return true; } IsSystemHeader = true; PP.Lex(FlagTok); if (FlagTok.is(tok::eod)) return false; if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP)) return true; // We must have 4 if there is yet another flag. if (FlagVal != 4) { PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); PP.DiscardUntilEndOfDirective(); return true; } IsExternCHeader = true; PP.Lex(FlagTok); if (FlagTok.is(tok::eod)) return false; // There are no more valid flags here. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); PP.DiscardUntilEndOfDirective(); return true; } /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is /// one of the following forms: /// /// # 42 /// # 42 "file" ('1' | '2')? /// # 42 "file" ('1' | '2')? '3' '4'? /// void Preprocessor::HandleDigitDirective(Token &DigitTok) { // Validate the number and convert it to an unsigned. GNU does not have a // line # limit other than it fit in 32-bits. unsigned LineNo; if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer, *this, true)) return; Token StrTok; Lex(StrTok); bool IsFileEntry = false, IsFileExit = false; bool IsSystemHeader = false, IsExternCHeader = false; int FilenameID = -1; // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a // string followed by eod. if (StrTok.is(tok::eod)) ; // ok else if (StrTok.isNot(tok::string_literal)) { Diag(StrTok, diag::err_pp_linemarker_invalid_filename); return DiscardUntilEndOfDirective(); } else if (StrTok.hasUDSuffix()) { Diag(StrTok, diag::err_invalid_string_udl); return DiscardUntilEndOfDirective(); } else { // Parse and validate the string, converting it into a unique ID. StringLiteralParser Literal(StrTok, *this); assert(Literal.isAscii() && "Didn't allow wide strings in"); if (Literal.hadError) return DiscardUntilEndOfDirective(); if (Literal.Pascal) { Diag(StrTok, diag::err_pp_linemarker_invalid_filename); return DiscardUntilEndOfDirective(); } FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString()); // If a filename was present, read any flags that are present. if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, IsSystemHeader, IsExternCHeader, *this)) return; } // Create a line note with this information. SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry, IsFileExit, IsSystemHeader, IsExternCHeader); // If the preprocessor has callbacks installed, notify them of the #line // change. This is used so that the line marker comes out in -E mode for // example. if (Callbacks) { PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile; if (IsFileEntry) Reason = PPCallbacks::EnterFile; else if (IsFileExit) Reason = PPCallbacks::ExitFile; SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User; if (IsExternCHeader) FileKind = SrcMgr::C_ExternCSystem; else if (IsSystemHeader) FileKind = SrcMgr::C_System; Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind); } } /// HandleUserDiagnosticDirective - Handle a #warning or #error directive. /// void Preprocessor::HandleUserDiagnosticDirective(Token &Tok, bool isWarning) { // PTH doesn't emit #warning or #error directives. if (CurPTHLexer) return CurPTHLexer->DiscardToEndOfLine(); // Read the rest of the line raw. We do this because we don't want macros // to be expanded and we don't require that the tokens be valid preprocessing // tokens. For example, this is allowed: "#warning ` 'foo". GCC does // collapse multiple consequtive white space between tokens, but this isn't // specified by the standard. SmallString<128> Message; CurLexer->ReadToEndOfLine(&Message); // Find the first non-whitespace character, so that we can make the // diagnostic more succinct. StringRef Msg = StringRef(Message).ltrim(" "); if (isWarning) Diag(Tok, diag::pp_hash_warning) << Msg; else Diag(Tok, diag::err_pp_hash_error) << Msg; } /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive. /// void Preprocessor::HandleIdentSCCSDirective(Token &Tok) { // Yes, this directive is an extension. Diag(Tok, diag::ext_pp_ident_directive); // Read the string argument. Token StrTok; Lex(StrTok); // If the token kind isn't a string, it's a malformed directive. if (StrTok.isNot(tok::string_literal) && StrTok.isNot(tok::wide_string_literal)) { Diag(StrTok, diag::err_pp_malformed_ident); if (StrTok.isNot(tok::eod)) DiscardUntilEndOfDirective(); return; } if (StrTok.hasUDSuffix()) { Diag(StrTok, diag::err_invalid_string_udl); return DiscardUntilEndOfDirective(); } // Verify that there is nothing after the string, other than EOD. CheckEndOfDirective("ident"); if (Callbacks) { bool Invalid = false; std::string Str = getSpelling(StrTok, &Invalid); if (!Invalid) Callbacks->Ident(Tok.getLocation(), Str); } } /// \brief Handle a #public directive. void Preprocessor::HandleMacroPublicDirective(Token &Tok) { Token MacroNameTok; ReadMacroName(MacroNameTok, MU_Undef); // Error reading macro name? If so, diagnostic already issued. if (MacroNameTok.is(tok::eod)) return; // Check to see if this is the last token on the #__public_macro line. CheckEndOfDirective("__public_macro"); IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); // Okay, we finally have a valid identifier to undef. MacroDirective *MD = getLocalMacroDirective(II); // If the macro is not defined, this is an error. if (!MD) { Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II; return; } // Note that this macro has now been exported. appendMacroDirective(II, AllocateVisibilityMacroDirective( MacroNameTok.getLocation(), /*IsPublic=*/true)); } /// \brief Handle a #private directive. void Preprocessor::HandleMacroPrivateDirective(Token &Tok) { Token MacroNameTok; ReadMacroName(MacroNameTok, MU_Undef); // Error reading macro name? If so, diagnostic already issued. if (MacroNameTok.is(tok::eod)) return; // Check to see if this is the last token on the #__private_macro line. CheckEndOfDirective("__private_macro"); IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); // Okay, we finally have a valid identifier to undef. MacroDirective *MD = getLocalMacroDirective(II); // If the macro is not defined, this is an error. if (!MD) { Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II; return; } // Note that this macro has now been marked private. appendMacroDirective(II, AllocateVisibilityMacroDirective( MacroNameTok.getLocation(), /*IsPublic=*/false)); } //===----------------------------------------------------------------------===// // Preprocessor Include Directive Handling. //===----------------------------------------------------------------------===// /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully /// checked and spelled filename, e.g. as an operand of \#include. This returns /// true if the input filename was in <>'s or false if it were in ""'s. The /// caller is expected to provide a buffer that is large enough to hold the /// spelling of the filename, but is also expected to handle the case when /// this method decides to use a different buffer. bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc, StringRef &Buffer) { // Get the text form of the filename. assert(!Buffer.empty() && "Can't have tokens with empty spellings!"); // Make sure the filename is <x> or "x". bool isAngled; if (Buffer[0] == '<') { if (Buffer.back() != '>') { Diag(Loc, diag::err_pp_expects_filename); Buffer = StringRef(); return true; } isAngled = true; } else if (Buffer[0] == '"') { if (Buffer.back() != '"') { Diag(Loc, diag::err_pp_expects_filename); Buffer = StringRef(); return true; } isAngled = false; } else { Diag(Loc, diag::err_pp_expects_filename); Buffer = StringRef(); return true; } // Diagnose #include "" as invalid. if (Buffer.size() <= 2) { Diag(Loc, diag::err_pp_empty_filename); Buffer = StringRef(); return true; } // Skip the brackets. Buffer = Buffer.substr(1, Buffer.size()-2); return isAngled; } // \brief Handle cases where the \#include name is expanded from a macro // as multiple tokens, which need to be glued together. // // This occurs for code like: // \code // \#define FOO <a/b.h> // \#include FOO // \endcode // because in this case, "<a/b.h>" is returned as 7 tokens, not one. // // This code concatenates and consumes tokens up to the '>' token. It returns // false if the > was found, otherwise it returns true if it finds and consumes // the EOD marker. bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer, SourceLocation &End) { Token CurTok; Lex(CurTok); while (CurTok.isNot(tok::eod)) { End = CurTok.getLocation(); // FIXME: Provide code completion for #includes. if (CurTok.is(tok::code_completion)) { setCodeCompletionReached(); Lex(CurTok); continue; } // Append the spelling of this token to the buffer. If there was a space // before it, add it now. if (CurTok.hasLeadingSpace()) FilenameBuffer.push_back(' '); // Get the spelling of the token, directly into FilenameBuffer if possible. unsigned PreAppendSize = FilenameBuffer.size(); FilenameBuffer.resize(PreAppendSize+CurTok.getLength()); const char *BufPtr = &FilenameBuffer[PreAppendSize]; unsigned ActualLen = getSpelling(CurTok, BufPtr); // If the token was spelled somewhere else, copy it into FilenameBuffer. if (BufPtr != &FilenameBuffer[PreAppendSize]) memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen); // Resize FilenameBuffer to the correct size. if (CurTok.getLength() != ActualLen) FilenameBuffer.resize(PreAppendSize+ActualLen); // If we found the '>' marker, return success. if (CurTok.is(tok::greater)) return false; Lex(CurTok); } // If we hit the eod marker, emit an error and return true so that the caller // knows the EOD has been read. Diag(CurTok.getLocation(), diag::err_pp_expects_filename); return true; } /// \brief Push a token onto the token stream containing an annotation. static void EnterAnnotationToken(Preprocessor &PP, SourceLocation Begin, SourceLocation End, tok::TokenKind Kind, void *AnnotationVal) { // FIXME: Produce this as the current token directly, rather than // allocating a new token for it. Token *Tok = new Token[1]; Tok[0].startToken(); Tok[0].setKind(Kind); Tok[0].setLocation(Begin); Tok[0].setAnnotationEndLoc(End); Tok[0].setAnnotationValue(AnnotationVal); PP.EnterTokenStream(Tok, 1, true, true); } /// \brief Produce a diagnostic informing the user that a #include or similar /// was implicitly treated as a module import. static void diagnoseAutoModuleImport( Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok, ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path, SourceLocation PathEnd) { assert(PP.getLangOpts().ObjC2 && "no import syntax available"); SmallString<128> PathString; for (unsigned I = 0, N = Path.size(); I != N; ++I) { if (I) PathString += '.'; PathString += Path[I].first->getName(); } int IncludeKind = 0; switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) { case tok::pp_include: IncludeKind = 0; break; case tok::pp_import: IncludeKind = 1; break; case tok::pp_include_next: IncludeKind = 2; break; case tok::pp___include_macros: IncludeKind = 3; break; default: llvm_unreachable("unknown include directive kind"); } CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd), /*IsTokenRange=*/false); PP.Diag(HashLoc, diag::warn_auto_module_import) << IncludeKind << PathString << FixItHint::CreateReplacement(ReplaceRange, ("@import " + PathString + ";").str()); } /// HandleIncludeDirective - The "\#include" tokens have just been read, read /// the file to be included from the lexer, then include it! This is a common /// routine with functionality shared between \#include, \#include_next and /// \#import. LookupFrom is set when this is a \#include_next directive, it /// specifies the file to start searching from. void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc, Token &IncludeTok, const DirectoryLookup *LookupFrom, const FileEntry *LookupFromFile, bool isImport) { Token FilenameTok; CurPPLexer->LexIncludeFilename(FilenameTok); // Reserve a buffer to get the spelling. SmallString<128> FilenameBuffer; StringRef Filename; SourceLocation End; SourceLocation CharEnd; // the end of this directive, in characters switch (FilenameTok.getKind()) { case tok::eod: // If the token kind is EOD, the error has already been diagnosed. return; case tok::angle_string_literal: case tok::string_literal: Filename = getSpelling(FilenameTok, FilenameBuffer); End = FilenameTok.getLocation(); CharEnd = End.getLocWithOffset(FilenameTok.getLength()); break; case tok::less: // This could be a <foo/bar.h> file coming from a macro expansion. In this // case, glue the tokens together into FilenameBuffer and interpret those. FilenameBuffer.push_back('<'); if (ConcatenateIncludeName(FilenameBuffer, End)) return; // Found <eod> but no ">"? Diagnostic already emitted. Filename = FilenameBuffer; CharEnd = End.getLocWithOffset(1); break; default: Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename); DiscardUntilEndOfDirective(); return; } CharSourceRange FilenameRange = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd); StringRef OriginalFilename = Filename; bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename); // If GetIncludeFilenameSpelling set the start ptr to null, there was an // error. if (Filename.empty()) { DiscardUntilEndOfDirective(); return; } // Verify that there is nothing after the filename, other than EOD. Note that // we allow macros that expand to nothing after the filename, because this // falls into the category of "#include pp-tokens new-line" specified in // C99 6.10.2p4. CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true); // Check that we don't have infinite #include recursion. if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) { Diag(FilenameTok, diag::err_pp_include_too_deep); return; } // Complain about attempts to #include files in an audit pragma. if (PragmaARCCFCodeAuditedLoc.isValid()) { Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited); Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here); // Immediately leave the pragma. PragmaARCCFCodeAuditedLoc = SourceLocation(); } // Complain about attempts to #include files in an assume-nonnull pragma. if (PragmaAssumeNonNullLoc.isValid()) { Diag(HashLoc, diag::err_pp_include_in_assume_nonnull); Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here); // Immediately leave the pragma. PragmaAssumeNonNullLoc = SourceLocation(); } if (HeaderInfo.HasIncludeAliasMap()) { // Map the filename with the brackets still attached. If the name doesn't // map to anything, fall back on the filename we've already gotten the // spelling for. StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename); if (!NewName.empty()) Filename = NewName; } // Search include directories. const DirectoryLookup *CurDir; SmallString<1024> SearchPath; SmallString<1024> RelativePath; // We get the raw path only if we have 'Callbacks' to which we later pass // the path. ModuleMap::KnownHeader SuggestedModule; SourceLocation FilenameLoc = FilenameTok.getLocation(); SmallString<128> NormalizedPath; if (LangOpts.MSVCCompat) { NormalizedPath = Filename.str(); #ifndef LLVM_ON_WIN32 llvm::sys::path::native(NormalizedPath); #endif } const FileEntry *File = LookupFile( FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled, LookupFrom, LookupFromFile, CurDir, Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr, &SuggestedModule); if (!File) { if (Callbacks) { // Give the clients a chance to recover. SmallString<128> RecoveryPath; if (Callbacks->FileNotFound(Filename, RecoveryPath)) { if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) { // Add the recovery path to the list of search paths. DirectoryLookup DL(DE, SrcMgr::C_User, false); HeaderInfo.AddSearchPath(DL, isAngled); // Try the lookup again, skipping the cache. File = LookupFile( FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled, LookupFrom, LookupFromFile, CurDir, nullptr, nullptr, &SuggestedModule, /*SkipCache*/ true); } } } if (!SuppressIncludeNotFoundError) { // If the file could not be located and it was included via angle // brackets, we can attempt a lookup as though it were a quoted path to // provide the user with a possible fixit. if (isAngled) { File = LookupFile( FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false, LookupFrom, LookupFromFile, CurDir, Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr, &SuggestedModule); if (File) { SourceRange Range(FilenameTok.getLocation(), CharEnd); Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) << Filename << FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\""); } } // If the file is still not found, just go with the vanilla diagnostic if (!File) Diag(FilenameTok, diag::err_pp_file_not_found) << Filename; } } // Should we enter the source file? Set to false if either the source file is // known to have no effect beyond its effect on module visibility -- that is, // if it's got an include guard that is already defined or is a modular header // we've imported or already built. bool ShouldEnter = true; // Determine whether we should try to import the module for this #include, if // there is one. Don't do so if precompiled module support is disabled or we // are processing this module textually (because we're building the module). if (File && SuggestedModule && getLangOpts().Modules && SuggestedModule.getModule()->getTopLevelModuleName() != getLangOpts().CurrentModule && SuggestedModule.getModule()->getTopLevelModuleName() != getLangOpts().ImplementationOfModule) { // Compute the module access path corresponding to this module. // FIXME: Should we have a second loadModule() overload to avoid this // extra lookup step? SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent) Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name), FilenameTok.getLocation())); std::reverse(Path.begin(), Path.end()); // Warn that we're replacing the include/import with a module import. // We only do this in Objective-C, where we have a module-import syntax. if (getLangOpts().ObjC2) diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd); // Load the module to import its macros. We'll make the declarations // visible when the parser gets here. // FIXME: Pass SuggestedModule in here rather than converting it to a path // and making the module loader convert it back again. ModuleLoadResult Imported = TheModuleLoader.loadModule( IncludeTok.getLocation(), Path, Module::Hidden, /*IsIncludeDirective=*/true); assert((Imported == nullptr || Imported == SuggestedModule.getModule()) && "the imported module is different than the suggested one"); if (Imported) ShouldEnter = false; else if (Imported.isMissingExpected()) { // We failed to find a submodule that we assumed would exist (because it // was in the directory of an umbrella header, for instance), but no // actual module exists for it (because the umbrella header is // incomplete). Treat this as a textual inclusion. SuggestedModule = ModuleMap::KnownHeader(); } else { // We hit an error processing the import. Bail out. if (hadModuleLoaderFatalFailure()) { // With a fatal failure in the module loader, we abort parsing. Token &Result = IncludeTok; if (CurLexer) { Result.startToken(); CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof); CurLexer->cutOffLexing(); } else { assert(CurPTHLexer && "#include but no current lexer set!"); CurPTHLexer->getEOF(Result); } } return; } } if (Callbacks) { // Notify the callback object that we've seen an inclusion directive. Callbacks->InclusionDirective( HashLoc, IncludeTok, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled, FilenameRange, File, SearchPath, RelativePath, ShouldEnter ? nullptr : SuggestedModule.getModule()); } if (!File) return; // The #included file will be considered to be a system header if either it is // in a system include directory, or if the #includer is a system include // header. SrcMgr::CharacteristicKind FileCharacter = std::max(HeaderInfo.getFileDirFlavor(File), SourceMgr.getFileCharacteristic(FilenameTok.getLocation())); // FIXME: If we have a suggested module, and we've already visited this file, // don't bother entering it again. We know it has no further effect. // Ask HeaderInfo if we should enter this #include file. If not, #including // this file will have no effect. if (ShouldEnter && !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport)) { ShouldEnter = false; if (Callbacks) Callbacks->FileSkipped(*File, FilenameTok, FileCharacter); } // If we don't need to enter the file, stop now. if (!ShouldEnter) { // If this is a module import, make it visible if needed. if (auto *M = SuggestedModule.getModule()) { makeModuleVisible(M, HashLoc); if (IncludeTok.getIdentifierInfo()->getPPKeywordID() != tok::pp___include_macros) EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include, M); } return; } // Look up the file, create a File ID for it. SourceLocation IncludePos = End; // If the filename string was the result of macro expansions, set the include // position on the file where it will be included and after the expansions. if (IncludePos.isMacroID()) IncludePos = SourceMgr.getExpansionRange(IncludePos).second; FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter); assert(!FID.isInvalid() && "Expected valid file ID"); // If all is good, enter the new file! if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation())) return; // Determine if we're switching to building a new submodule, and which one. if (auto *M = SuggestedModule.getModule()) { assert(!CurSubmodule && "should not have marked this as a module yet"); CurSubmodule = M; // Let the macro handling code know that any future macros are within // the new submodule. EnterSubmodule(M, HashLoc); // Let the parser know that any future declarations are within the new // submodule. // FIXME: There's no point doing this if we're handling a #__include_macros // directive. EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin, M); } } /// HandleIncludeNextDirective - Implements \#include_next. /// void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc, Token &IncludeNextTok) { Diag(IncludeNextTok, diag::ext_pp_include_next_directive); // #include_next is like #include, except that we start searching after // the current found directory. If we can't do this, issue a // diagnostic. const DirectoryLookup *Lookup = CurDirLookup; const FileEntry *LookupFromFile = nullptr; if (isInPrimaryFile()) { Lookup = nullptr; Diag(IncludeNextTok, diag::pp_include_next_in_primary); } else if (CurSubmodule) { // Start looking up in the directory *after* the one in which the current // file would be found, if any. assert(CurPPLexer && "#include_next directive in macro?"); LookupFromFile = CurPPLexer->getFileEntry(); Lookup = nullptr; } else if (!Lookup) { Diag(IncludeNextTok, diag::pp_include_next_absolute_path); } else { // Start looking up in the next directory. ++Lookup; } return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup, LookupFromFile); } /// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) { // The Microsoft #import directive takes a type library and generates header // files from it, and includes those. This is beyond the scope of what clang // does, so we ignore it and error out. However, #import can optionally have // trailing attributes that span multiple lines. We're going to eat those // so we can continue processing from there. Diag(Tok, diag::err_pp_import_directive_ms ); // Read tokens until we get to the end of the directive. Note that the // directive can be split over multiple lines using the backslash character. DiscardUntilEndOfDirective(); } /// HandleImportDirective - Implements \#import. /// void Preprocessor::HandleImportDirective(SourceLocation HashLoc, Token &ImportTok) { if (!LangOpts.ObjC1) { // #import is standard for ObjC. if (LangOpts.MSVCCompat) return HandleMicrosoftImportDirective(ImportTok); Diag(ImportTok, diag::ext_pp_import_directive); } return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true); } /// HandleIncludeMacrosDirective - The -imacros command line option turns into a /// pseudo directive in the predefines buffer. This handles it by sucking all /// tokens through the preprocessor and discarding them (only keeping the side /// effects on the preprocessor). void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &IncludeMacrosTok) { // This directive should only occur in the predefines buffer. If not, emit an // error and reject it. SourceLocation Loc = IncludeMacrosTok.getLocation(); if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) { Diag(IncludeMacrosTok.getLocation(), diag::pp_include_macros_out_of_predefines); DiscardUntilEndOfDirective(); return; } // Treat this as a normal #include for checking purposes. If this is // successful, it will push a new lexer onto the include stack. HandleIncludeDirective(HashLoc, IncludeMacrosTok); Token TmpTok; do { Lex(TmpTok); assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!"); } while (TmpTok.isNot(tok::hashhash)); } //===----------------------------------------------------------------------===// // Preprocessor Macro Directive Handling. //===----------------------------------------------------------------------===// /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro /// definition has just been read. Lex the rest of the arguments and the /// closing ), updating MI with what we learn. Return true if an error occurs /// parsing the arg list. bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) { SmallVector<IdentifierInfo*, 32> Arguments; while (1) { LexUnexpandedToken(Tok); switch (Tok.getKind()) { case tok::r_paren: // Found the end of the argument list. if (Arguments.empty()) // #define FOO() return false; // Otherwise we have #define FOO(A,) Diag(Tok, diag::err_pp_expected_ident_in_arg_list); return true; case tok::ellipsis: // #define X(... -> C99 varargs if (!LangOpts.C99) Diag(Tok, LangOpts.CPlusPlus11 ? diag::warn_cxx98_compat_variadic_macro : diag::ext_variadic_macro); // OpenCL v1.2 s6.9.e: variadic macros are not supported. if (LangOpts.OpenCL) { Diag(Tok, diag::err_pp_opencl_variadic_macros); return true; } // Lex the token after the identifier. LexUnexpandedToken(Tok); if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); return true; } // Add the __VA_ARGS__ identifier as an argument. Arguments.push_back(Ident__VA_ARGS__); MI->setIsC99Varargs(); MI->setArgumentList(&Arguments[0], Arguments.size(), BP); return false; case tok::eod: // #define X( Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); return true; default: // Handle keywords and identifiers here to accept things like // #define Foo(for) for. IdentifierInfo *II = Tok.getIdentifierInfo(); if (!II) { // #define X(1 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list); return true; } // If this is already used as an argument, it is used multiple times (e.g. // #define X(A,A. if (std::find(Arguments.begin(), Arguments.end(), II) != Arguments.end()) { // C99 6.10.3p6 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II; return true; } // Add the argument to the macro info. Arguments.push_back(II); // Lex the token after the identifier. LexUnexpandedToken(Tok); switch (Tok.getKind()) { default: // #define X(A B Diag(Tok, diag::err_pp_expected_comma_in_arg_list); return true; case tok::r_paren: // #define X(A) MI->setArgumentList(&Arguments[0], Arguments.size(), BP); return false; case tok::comma: // #define X(A, break; case tok::ellipsis: // #define X(A... -> GCC extension // Diagnose extension. Diag(Tok, diag::ext_named_variadic_macro); // Lex the token after the identifier. LexUnexpandedToken(Tok); if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); return true; } MI->setIsGNUVarargs(); MI->setArgumentList(&Arguments[0], Arguments.size(), BP); return false; } } } } static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI, const LangOptions &LOptions) { if (MI->getNumTokens() == 1) { const Token &Value = MI->getReplacementToken(0); // Macro that is identity, like '#define inline inline' is a valid pattern. if (MacroName.getKind() == Value.getKind()) return true; // Macro that maps a keyword to the same keyword decorated with leading/ // trailing underscores is a valid pattern: // #define inline __inline // #define inline __inline__ // #define inline _inline (in MS compatibility mode) StringRef MacroText = MacroName.getIdentifierInfo()->getName(); if (IdentifierInfo *II = Value.getIdentifierInfo()) { if (!II->isKeyword(LOptions)) return false; StringRef ValueText = II->getName(); StringRef TrimmedValue = ValueText; if (!ValueText.startswith("__")) { if (ValueText.startswith("_")) TrimmedValue = TrimmedValue.drop_front(1); else return false; } else { TrimmedValue = TrimmedValue.drop_front(2); if (TrimmedValue.endswith("__")) TrimmedValue = TrimmedValue.drop_back(2); } return TrimmedValue.equals(MacroText); } else { return false; } } // #define inline if (MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static, tok::kw_const) && MI->getNumTokens() == 0) { return true; } return false; } /// HandleDefineDirective - Implements \#define. This consumes the entire macro /// line then lets the caller lex the next real token. void Preprocessor::HandleDefineDirective(Token &DefineTok, bool ImmediatelyAfterHeaderGuard) { ++NumDefined; Token MacroNameTok; bool MacroShadowsKeyword; ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword); // Error reading macro name? If so, diagnostic already issued. if (MacroNameTok.is(tok::eod)) return; Token LastTok = MacroNameTok; // If we are supposed to keep comments in #defines, reenable comment saving // mode. if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments); // Create the new macro. MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation()); Token Tok; LexUnexpandedToken(Tok); // If this is a function-like macro definition, parse the argument list, // marking each of the identifiers as being used as macro arguments. Also, // check other constraints on the first token of the macro body. if (Tok.is(tok::eod)) { if (ImmediatelyAfterHeaderGuard) { // Save this macro information since it may part of a header guard. CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(), MacroNameTok.getLocation()); } // If there is no body to this macro, we have no special handling here. } else if (Tok.hasLeadingSpace()) { // This is a normal token with leading space. Clear the leading space // marker on the first token to get proper expansion. Tok.clearFlag(Token::LeadingSpace); } else if (Tok.is(tok::l_paren)) { // This is a function-like macro definition. Read the argument list. MI->setIsFunctionLike(); if (ReadMacroDefinitionArgList(MI, LastTok)) { // Throw away the rest of the line. if (CurPPLexer->ParsingPreprocessorDirective) DiscardUntilEndOfDirective(); return; } // If this is a definition of a variadic C99 function-like macro, not using // the GNU named varargs extension, enabled __VA_ARGS__. // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. // This gets unpoisoned where it is allowed. assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!"); if (MI->isC99Varargs()) Ident__VA_ARGS__->setIsPoisoned(false); // Read the first token after the arg list for down below. LexUnexpandedToken(Tok); } else if (LangOpts.C99 || LangOpts.CPlusPlus11) { // C99 requires whitespace between the macro definition and the body. Emit // a diagnostic for something like "#define X+". Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name); } else { // C90 6.8 TC1 says: "In the definition of an object-like macro, if the // first character of a replacement list is not a character required by // subclause 5.2.1, then there shall be white-space separation between the // identifier and the replacement list.". 5.2.1 lists this set: // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which // is irrelevant here. bool isInvalid = false; if (Tok.is(tok::at)) // @ is not in the list above. isInvalid = true; else if (Tok.is(tok::unknown)) { // If we have an unknown token, it is something strange like "`". Since // all of valid characters would have lexed into a single character // token of some sort, we know this is not a valid case. isInvalid = true; } if (isInvalid) Diag(Tok, diag::ext_missing_whitespace_after_macro_name); else Diag(Tok, diag::warn_missing_whitespace_after_macro_name); } if (!Tok.is(tok::eod)) LastTok = Tok; // Read the rest of the macro body. if (MI->isObjectLike()) { // Object-like macros are very simple, just read their body. while (Tok.isNot(tok::eod)) { LastTok = Tok; MI->AddTokenToBody(Tok); // Get the next token of the macro. LexUnexpandedToken(Tok); } } else { // Otherwise, read the body of a function-like macro. While we are at it, // check C99 6.10.3.2p1: ensure that # operators are followed by macro // parameters in function-like macro expansions. while (Tok.isNot(tok::eod)) { LastTok = Tok; if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) { MI->AddTokenToBody(Tok); // Get the next token of the macro. LexUnexpandedToken(Tok); continue; } // If we're in -traditional mode, then we should ignore stringification // and token pasting. Mark the tokens as unknown so as not to confuse // things. if (getLangOpts().TraditionalCPP) { Tok.setKind(tok::unknown); MI->AddTokenToBody(Tok); // Get the next token of the macro. LexUnexpandedToken(Tok); continue; } if (Tok.is(tok::hashhash)) { // If we see token pasting, check if it looks like the gcc comma // pasting extension. We'll use this information to suppress // diagnostics later on. // Get the next token of the macro. LexUnexpandedToken(Tok); if (Tok.is(tok::eod)) { MI->AddTokenToBody(LastTok); break; } unsigned NumTokens = MI->getNumTokens(); if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ && MI->getReplacementToken(NumTokens-1).is(tok::comma)) MI->setHasCommaPasting(); // Things look ok, add the '##' token to the macro. MI->AddTokenToBody(LastTok); continue; } // Get the next token of the macro. LexUnexpandedToken(Tok); // Check for a valid macro arg identifier. if (Tok.getIdentifierInfo() == nullptr || MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) { // If this is assembler-with-cpp mode, we accept random gibberish after // the '#' because '#' is often a comment character. However, change // the kind of the token to tok::unknown so that the preprocessor isn't // confused. if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) { LastTok.setKind(tok::unknown); MI->AddTokenToBody(LastTok); continue; } else { Diag(Tok, diag::err_pp_stringize_not_parameter); // Disable __VA_ARGS__ again. Ident__VA_ARGS__->setIsPoisoned(true); return; } } // Things look ok, add the '#' and param name tokens to the macro. MI->AddTokenToBody(LastTok); MI->AddTokenToBody(Tok); LastTok = Tok; // Get the next token of the macro. LexUnexpandedToken(Tok); } } if (MacroShadowsKeyword && !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) { Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword); } // Disable __VA_ARGS__ again. Ident__VA_ARGS__->setIsPoisoned(true); // Check that there is no paste (##) operator at the beginning or end of the // replacement list. unsigned NumTokens = MI->getNumTokens(); if (NumTokens != 0) { if (MI->getReplacementToken(0).is(tok::hashhash)) { Diag(MI->getReplacementToken(0), diag::err_paste_at_start); return; } if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) { Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end); return; } } MI->setDefinitionEndLoc(LastTok.getLocation()); // Finally, if this identifier already had a macro defined for it, verify that // the macro bodies are identical, and issue diagnostics if they are not. if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) { // It is very common for system headers to have tons of macro redefinitions // and for warnings to be disabled in system headers. If this is the case, // then don't bother calling MacroInfo::isIdenticalTo. if (!getDiagnostics().getSuppressSystemWarnings() || !SourceMgr.isInSystemHeader(DefineTok.getLocation())) { if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused()) Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used); // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and // C++ [cpp.predefined]p4, but allow it as an extension. if (OtherMI->isBuiltinMacro()) Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro); // Macros must be identical. This means all tokens and whitespace // separation must be the same. C99 6.10.3p2. else if (!OtherMI->isAllowRedefinitionsWithoutWarning() && !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) { Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef) << MacroNameTok.getIdentifierInfo(); Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition); } } if (OtherMI->isWarnIfUnused()) WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc()); } DefMacroDirective *MD = appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI); assert(!MI->isUsed()); // If we need warning for not using the macro, add its location in the // warn-because-unused-macro set. If it gets used it will be removed from set. if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) && !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) { MI->setIsWarnIfUnused(true); WarnUnusedMacroLocs.insert(MI->getDefinitionLoc()); } // If the callbacks want to know, tell them about the macro definition. if (Callbacks) Callbacks->MacroDefined(MacroNameTok, MD); } /// HandleUndefDirective - Implements \#undef. /// void Preprocessor::HandleUndefDirective(Token &UndefTok) { ++NumUndefined; Token MacroNameTok; ReadMacroName(MacroNameTok, MU_Undef); // Error reading macro name? If so, diagnostic already issued. if (MacroNameTok.is(tok::eod)) return; // Check to see if this is the last token on the #undef line. CheckEndOfDirective("undef"); // Okay, we have a valid identifier to undef. auto *II = MacroNameTok.getIdentifierInfo(); auto MD = getMacroDefinition(II); // If the callbacks want to know, tell them about the macro #undef. // Note: no matter if the macro was defined or not. if (Callbacks) Callbacks->MacroUndefined(MacroNameTok, MD); // If the macro is not defined, this is a noop undef, just return. const MacroInfo *MI = MD.getMacroInfo(); if (!MI) return; if (!MI->isUsed() && MI->isWarnIfUnused()) Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used); if (MI->isWarnIfUnused()) WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); appendMacroDirective(MacroNameTok.getIdentifierInfo(), AllocateUndefMacroDirective(MacroNameTok.getLocation())); } //===----------------------------------------------------------------------===// // Preprocessor Conditional Directive Handling. //===----------------------------------------------------------------------===// /// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef /// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is /// true if any tokens have been returned or pp-directives activated before this /// \#ifndef has been lexed. /// void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef, bool ReadAnyTokensBeforeDirective) { ++NumIf; Token DirectiveTok = Result; Token MacroNameTok; ReadMacroName(MacroNameTok); // Error reading macro name? If so, diagnostic already issued. if (MacroNameTok.is(tok::eod)) { // Skip code until we get to #endif. This helps with recovery by not // emitting an error when the #endif is reached. SkipExcludedConditionalBlock(DirectiveTok.getLocation(), /*Foundnonskip*/false, /*FoundElse*/false); return; } // Check to see if this is the last token on the #if[n]def line. CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef"); IdentifierInfo *MII = MacroNameTok.getIdentifierInfo(); auto MD = getMacroDefinition(MII); MacroInfo *MI = MD.getMacroInfo(); if (CurPPLexer->getConditionalStackDepth() == 0) { // If the start of a top-level #ifdef and if the macro is not defined, // inform MIOpt that this might be the start of a proper include guard. // Otherwise it is some other form of unknown conditional which we can't // handle. if (!ReadAnyTokensBeforeDirective && !MI) { assert(isIfndef && "#ifdef shouldn't reach here"); CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation()); } else CurPPLexer->MIOpt.EnterTopLevelConditional(); } // If there is a macro, process it. if (MI) // Mark it used. markMacroAsUsed(MI); if (Callbacks) { if (isIfndef) Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD); else Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD); } // Should we include the stuff contained by this directive? if (!MI == isIfndef) { // Yes, remember that we are inside a conditional, then lex the next token. CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false, /*foundnonskip*/true, /*foundelse*/false); } else { // No, skip the contents of this block. SkipExcludedConditionalBlock(DirectiveTok.getLocation(), /*Foundnonskip*/false, /*FoundElse*/false); } } /// HandleIfDirective - Implements the \#if directive. /// void Preprocessor::HandleIfDirective(Token &IfToken, bool ReadAnyTokensBeforeDirective) { ++NumIf; // Parse and evaluate the conditional expression. IdentifierInfo *IfNDefMacro = nullptr; const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation(); const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro); const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation(); // If this condition is equivalent to #ifndef X, and if this is the first // directive seen, handle it for the multiple-include optimization. if (CurPPLexer->getConditionalStackDepth() == 0) { if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue) // FIXME: Pass in the location of the macro name, not the 'if' token. CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation()); else CurPPLexer->MIOpt.EnterTopLevelConditional(); } if (Callbacks) Callbacks->If(IfToken.getLocation(), SourceRange(ConditionalBegin, ConditionalEnd), (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False)); // Should we include the stuff contained by this directive? if (ConditionalTrue) { // Yes, remember that we are inside a conditional, then lex the next token. CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false, /*foundnonskip*/true, /*foundelse*/false); } else { // No, skip the contents of this block. SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false, /*FoundElse*/false); } } /// HandleEndifDirective - Implements the \#endif directive. /// void Preprocessor::HandleEndifDirective(Token &EndifToken) { ++NumEndif; // Check that this is the whole directive. CheckEndOfDirective("endif"); PPConditionalInfo CondInfo; if (CurPPLexer->popConditionalLevel(CondInfo)) { // No conditionals on the stack: this is an #endif without an #if. Diag(EndifToken, diag::err_pp_endif_without_if); return; } // If this the end of a top-level #endif, inform MIOpt. if (CurPPLexer->getConditionalStackDepth() == 0) CurPPLexer->MIOpt.ExitTopLevelConditional(); assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode && "This code should only be reachable in the non-skipping case!"); if (Callbacks) Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc); } /// HandleElseDirective - Implements the \#else directive. /// void Preprocessor::HandleElseDirective(Token &Result) { ++NumElse; // #else directive in a non-skipping conditional... start skipping. CheckEndOfDirective("else"); PPConditionalInfo CI; if (CurPPLexer->popConditionalLevel(CI)) { Diag(Result, diag::pp_err_else_without_if); return; } // If this is a top-level #else, inform the MIOpt. if (CurPPLexer->getConditionalStackDepth() == 0) CurPPLexer->MIOpt.EnterTopLevelConditional(); // If this is a #else with a #else before it, report the error. if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else); if (Callbacks) Callbacks->Else(Result.getLocation(), CI.IfLoc); // Finally, skip the rest of the contents of this block. SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true, /*FoundElse*/true, Result.getLocation()); } /// HandleElifDirective - Implements the \#elif directive. /// void Preprocessor::HandleElifDirective(Token &ElifToken) { ++NumElse; // #elif directive in a non-skipping conditional... start skipping. // We don't care what the condition is, because we will always skip it (since // the block immediately before it was included). const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation(); DiscardUntilEndOfDirective(); const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation(); PPConditionalInfo CI; if (CurPPLexer->popConditionalLevel(CI)) { Diag(ElifToken, diag::pp_err_elif_without_if); return; } // If this is a top-level #elif, inform the MIOpt. if (CurPPLexer->getConditionalStackDepth() == 0) CurPPLexer->MIOpt.EnterTopLevelConditional(); // If this is a #elif with a #else before it, report the error. if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else); if (Callbacks) Callbacks->Elif(ElifToken.getLocation(), SourceRange(ConditionalBegin, ConditionalEnd), PPCallbacks::CVK_NotEvaluated, CI.IfLoc); // Finally, skip the rest of the contents of this block. SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true, /*FoundElse*/CI.FoundElse, ElifToken.getLocation()); }
37.056282
106
0.660049
IntelSTORM
33ce8b62be16a0ec9a6069434b6eea96aae71ed0
4,179
hpp
C++
include/caffe/layers/cudnn_deconv_layer.hpp
Julian-He/caffe
f6a177c9d4230ed0ee9f26769e0f1c99b3ec2487
[ "BSD-2-Clause" ]
null
null
null
include/caffe/layers/cudnn_deconv_layer.hpp
Julian-He/caffe
f6a177c9d4230ed0ee9f26769e0f1c99b3ec2487
[ "BSD-2-Clause" ]
null
null
null
include/caffe/layers/cudnn_deconv_layer.hpp
Julian-He/caffe
f6a177c9d4230ed0ee9f26769e0f1c99b3ec2487
[ "BSD-2-Clause" ]
null
null
null
/* All modification made by Cambricon Corporation: © 2018 Cambricon Corporation All rights reserved. All other contributions: Copyright (c) 2014--2018, the respective contributors All rights reserved. For the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef INCLUDE_CAFFE_LAYERS_CUDNN_DECONV_LAYER_HPP_ #define INCLUDE_CAFFE_LAYERS_CUDNN_DECONV_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/layers/deconv_layer.hpp" namespace caffe { #ifdef USE_CUDNN /* * @brief cuDNN implementation of DeConvolutionLayer. * Fallback to DeConvolutionLayer for CPU mode. * * cuDNN accelerates deconvolution through forward kernels for filtering and * bias plus backward kernels for the gradient w.r.t. the filters, biases, and * inputs. Caffe + cuDNN further speeds up the computation through forward * parallelism across groups and backward parallelism across gradients. */ template <typename Dtype> class CuDNNDeconvolutionLayer : public DeconvolutionLayer<Dtype> { public: explicit CuDNNDeconvolutionLayer(const LayerParameter& param) : DeconvolutionLayer<Dtype>(param), handles_setup_(false) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual ~CuDNNDeconvolutionLayer(); protected: virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); bool handles_setup_; cudnnHandle_t* handle_; cudaStream_t* stream_; // algorithms for forward and backwards convolutions cudnnConvolutionFwdAlgo_t *fwd_algo_; cudnnConvolutionBwdFilterAlgo_t *bwd_filter_algo_; cudnnConvolutionBwdDataAlgo_t *bwd_data_algo_; vector<cudnnTensorDescriptor_t> bottom_descs_, top_descs_; cudnnTensorDescriptor_t bias_desc_; cudnnFilterDescriptor_t filter_desc_; vector<cudnnConvolutionDescriptor_t> conv_descs_; int bottom_offset_, top_offset_, bias_offset_; size_t *workspace_fwd_sizes_; size_t *workspace_bwd_data_sizes_; size_t *workspace_bwd_filter_sizes_; size_t workspaceSizeInBytes; // size of underlying storage void *workspaceData; // underlying storage void **workspace; // aliases into workspaceData }; #endif } // namespace caffe #endif // INCLUDE_CAFFE_LAYERS_CUDNN_DECONV_LAYER_HPP_
42.642857
92
0.767408
Julian-He
33cfe4854ab1f3a8d72476c09806db43f5b721f4
2,281
hpp
C++
Versionen/2021_06_15/RMF/rmf_ws/install/rmf_building_map_msgs/include/rmf_building_map_msgs/msg/detail/affine_image__rosidl_typesupport_fastrtps_cpp.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/RMF/rmf_ws/install/rmf_building_map_msgs/include/rmf_building_map_msgs/msg/detail/affine_image__rosidl_typesupport_fastrtps_cpp.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/RMF/rmf_ws/install/rmf_building_map_msgs/include/rmf_building_map_msgs/msg/detail/affine_image__rosidl_typesupport_fastrtps_cpp.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
2
2021-06-21T07:32:09.000Z
2021-08-17T03:05:38.000Z
// generated from rosidl_typesupport_fastrtps_cpp/resource/idl__rosidl_typesupport_fastrtps_cpp.hpp.em // with input from rmf_building_map_msgs:msg/AffineImage.idl // generated code does not contain a copyright notice #ifndef RMF_BUILDING_MAP_MSGS__MSG__DETAIL__AFFINE_IMAGE__ROSIDL_TYPESUPPORT_FASTRTPS_CPP_HPP_ #define RMF_BUILDING_MAP_MSGS__MSG__DETAIL__AFFINE_IMAGE__ROSIDL_TYPESUPPORT_FASTRTPS_CPP_HPP_ #include "rosidl_runtime_c/message_type_support_struct.h" #include "rosidl_typesupport_interface/macros.h" #include "rmf_building_map_msgs/msg/rosidl_typesupport_fastrtps_cpp__visibility_control.h" #include "rmf_building_map_msgs/msg/detail/affine_image__struct.hpp" #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-parameter" # ifdef __clang__ # pragma clang diagnostic ignored "-Wdeprecated-register" # pragma clang diagnostic ignored "-Wreturn-type-c-linkage" # endif #endif #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "fastcdr/Cdr.h" namespace rmf_building_map_msgs { namespace msg { namespace typesupport_fastrtps_cpp { bool ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_rmf_building_map_msgs cdr_serialize( const rmf_building_map_msgs::msg::AffineImage & ros_message, eprosima::fastcdr::Cdr & cdr); bool ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_rmf_building_map_msgs cdr_deserialize( eprosima::fastcdr::Cdr & cdr, rmf_building_map_msgs::msg::AffineImage & ros_message); size_t ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_rmf_building_map_msgs get_serialized_size( const rmf_building_map_msgs::msg::AffineImage & ros_message, size_t current_alignment); size_t ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_rmf_building_map_msgs max_serialized_size_AffineImage( bool & full_bounded, size_t current_alignment); } // namespace typesupport_fastrtps_cpp } // namespace msg } // namespace rmf_building_map_msgs #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_rmf_building_map_msgs const rosidl_message_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_cpp, rmf_building_map_msgs, msg, AffineImage)(); #ifdef __cplusplus } #endif #endif // RMF_BUILDING_MAP_MSGS__MSG__DETAIL__AFFINE_IMAGE__ROSIDL_TYPESUPPORT_FASTRTPS_CPP_HPP_
28.5125
128
0.854011
flitzmo-hso
33d1c41fcaff576af5a008841e5c03cd665f9ee9
6,651
cpp
C++
src/Exclusion.cpp
hiliev/timewarrior
025b36c051c70fef2beeb456df5ef9ad9221f2e9
[ "MIT" ]
null
null
null
src/Exclusion.cpp
hiliev/timewarrior
025b36c051c70fef2beeb456df5ef9ad9221f2e9
[ "MIT" ]
null
null
null
src/Exclusion.cpp
hiliev/timewarrior
025b36c051c70fef2beeb456df5ef9ad9221f2e9
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // Copyright 2015 - 2018, Thomas Lauf, Paul Beckingham, Federico Hernandez. // // 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. // // https://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <Exclusion.h> #include <Datetime.h> #include <Pig.h> #include <shared.h> #include <format.h> #include <algorithm> //////////////////////////////////////////////////////////////////////////////// // An exclusion represents untrackable time such as holidays, weekends, evenings // and lunch. By default there are none, but they may be configured. Once there // are exclusions defined, the :fill functionality is enabled. // // Exclusions are instantiated from configuration, and are passed here as name/ // value strings. // // Name Value // -------------------------- ------------------------ // exclusions.days.2016_01_01 on // exclusions.days.2016_01_02 off // exclusions.friday <8:00 12:00-12:45 >17:30 // exclusions.monday <8:00 12:00-12:45 >17:30 // exclusions.thursday <8:00 12:00-12:45 >17:30 // exclusions.tuesday <8:00 12:00-12:45 >18:30 // exclusions.wednesday <8:00 12:00-13:30 >17:30 // Exclusion::Exclusion (const std::string& name, const std::string& value) //void Exclusion::initialize (const std::string& line) { _tokens = split (name, '.'); for (auto& token : split (value)) _tokens.push_back (token); // Validate syntax only. Do nothing with the data. if (_tokens.size () >= 2 && _tokens[0] == "exclusions") { if (_tokens.size () == 4 && _tokens[1] == "days" && _tokens[3] == "on") { _additive = true; return; } if (_tokens.size () == 4 && _tokens[1] == "days" && _tokens[3] == "off") { _additive = false; return; } else if (Datetime::dayOfWeek (_tokens[1]) != -1) { _additive = false; return; } } throw format ("Unrecognized exclusion syntax: '{1}' '{2}'.", name, value); } //////////////////////////////////////////////////////////////////////////////// std::vector <std::string> Exclusion::tokens () const { return _tokens; } //////////////////////////////////////////////////////////////////////////////// // Within range, yield a collection of recurring ranges as defined by _tokens. // // exc monday <block> [<block> ...] --> yields a day range for every monday, // and every block within // exc day on <date> --> yields single day range // exc day off <date> --> yields single day range // std::vector <Range> Exclusion::ranges (const Range& range) const { std::vector <Range> results; int dayOfWeek; if (_tokens[1] == "days" && (_tokens[3] == "on" || _tokens[3] == "off")) { auto day = _tokens[2]; std::replace (day.begin (), day.end (), '_', '-'); Datetime start (day); Datetime end (start); ++end; Range all_day (start, end); if (range.overlaps (all_day)) results.push_back (all_day); } else if ((dayOfWeek = Datetime::dayOfWeek (_tokens[1])) != -1) { Datetime start (range.start.year (), range.start.month (), range.start.day (), 0, 0, 0); Range myRange = {range}; if (myRange.is_open()) { myRange.end = Datetime("tomorrow"); } while (start <= myRange.end) { if (start.dayOfWeek () == dayOfWeek) { Datetime end = start; ++end; // Now that 'start' and 'end' represent the correct day, compose a set // of Range objects for each time block. for (unsigned int block = 2; block < _tokens.size (); ++block) { auto r = rangeFromTimeBlock (_tokens[block], start, end); if (myRange.overlaps (r)) results.push_back (r); } } ++start; } } return results; } //////////////////////////////////////////////////////////////////////////////// bool Exclusion::additive () const { return _additive; } //////////////////////////////////////////////////////////////////////////////// std::string Exclusion::dump () const { return join (" ", _tokens); } //////////////////////////////////////////////////////////////////////////////// Range Exclusion::rangeFromTimeBlock ( const std::string& block, const Datetime& start, const Datetime& end) const { Pig pig (block); if (pig.skip ('<')) { int hh, mm, ss; if (pig.getHMS (hh, mm, ss)) return Range (Datetime (start.year (), start.month (), start.day (), 0, 0, 0), Datetime (start.year (), start.month (), start.day (), hh, mm, ss)); } else if (pig.skip ('>')) { int hh, mm, ss; if (pig.getHMS (hh, mm, ss)) return Range (Datetime (start.year (), start.month (), start.day (), hh, mm, ss), Datetime (end.year (), end.month (), end.day (), 0, 0, 0)); } else { int hh1, mm1, ss1; int hh2, mm2, ss2; if (pig.getHMS (hh1, mm1, ss1) && pig.skip ('-') && pig.getHMS (hh2, mm2, ss2)) return Range ( Datetime (start.year (), start.month (), start.day (), hh1, mm1, ss1), Datetime (start.year (), start.month (), start.day (), hh2, mm2, ss2)); } throw format ("Malformed time block '{1}'.", block); } ////////////////////////////////////////////////////////////////////////////////
32.443902
92
0.529544
hiliev
33d2cb50dee217a21996e318c5ef1a2eebefedeb
22,533
cpp
C++
IGC/Compiler/Optimizer/OpenCLPasses/LocalBuffers/InlineLocalsResolution.cpp
ConiKost/intel-graphics-compiler
f5227c9658da35d08d7f711552ebcb12638ebc18
[ "Intel", "MIT" ]
1
2020-09-03T17:11:47.000Z
2020-09-03T17:11:47.000Z
IGC/Compiler/Optimizer/OpenCLPasses/LocalBuffers/InlineLocalsResolution.cpp
ConiKost/intel-graphics-compiler
f5227c9658da35d08d7f711552ebcb12638ebc18
[ "Intel", "MIT" ]
null
null
null
IGC/Compiler/Optimizer/OpenCLPasses/LocalBuffers/InlineLocalsResolution.cpp
ConiKost/intel-graphics-compiler
f5227c9658da35d08d7f711552ebcb12638ebc18
[ "Intel", "MIT" ]
null
null
null
/*========================== begin_copyright_notice ============================ Copyright (C) 2017-2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ #include "AdaptorCommon/ImplicitArgs.hpp" #include "Compiler/Optimizer/OpenCLPasses/LocalBuffers/InlineLocalsResolution.hpp" #include "Compiler/CodeGenPublic.h" #include "Compiler/IGCPassSupport.h" #include "Compiler/CISACodeGen/helper.h" #include "Compiler/DebugInfo/Utils.h" #include "common/LLVMWarningsPush.hpp" #include <llvm/IR/Module.h> #include <llvm/IR/Instructions.h> #include <llvmWrapper/Support/Alignment.h> #include "common/LLVMWarningsPop.hpp" #include "Probe/Assertion.h" #include <unordered_set> using namespace llvm; using namespace IGC; using namespace IGC::IGCMD; // Register pass to igc-opt #define PASS_FLAG "igc-resolve-inline-locals" #define PASS_DESCRIPTION "Resolve inline local variables/buffers" #define PASS_CFG_ONLY false #define PASS_ANALYSIS false IGC_INITIALIZE_PASS_BEGIN(InlineLocalsResolution, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS) IGC_INITIALIZE_PASS_DEPENDENCY(MetaDataUtilsWrapper) IGC_INITIALIZE_PASS_END(InlineLocalsResolution, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS) char InlineLocalsResolution::ID = 0; const llvm::StringRef BUILTIN_MEMPOOL = "__builtin_IB_AllocLocalMemPool"; InlineLocalsResolution::InlineLocalsResolution() : ModulePass(ID), m_pGV(nullptr) { initializeInlineLocalsResolutionPass(*PassRegistry::getPassRegistry()); } const unsigned int InlineLocalsResolution::VALID_LOCAL_HIGH_BITS = 0x10000000; static bool useAsPointerOnly(Value* V) { IGC_ASSERT_MESSAGE(V->getType()->isPointerTy(), "Expect the input value is a pointer!"); SmallSet<PHINode*, 8> VisitedPHIs; SmallVector<Value*, 16> WorkList; WorkList.push_back(V); StoreInst* ST = nullptr; PHINode* PN = nullptr; while (!WorkList.empty()) { Value* Val = WorkList.pop_back_val(); for (auto* U : Val->users()) { Operator* Op = dyn_cast<Operator>(U); if (!Op) continue; switch (Op->getOpcode()) { default: // Bail out for unknown operations. return false; case Instruction::Store: ST = cast<StoreInst>(U); // Bail out if it's used as the value operand. if (ST->getValueOperand() == Val) return false; // FALL THROUGH case Instruction::Load: // Safe use in LD/ST as pointer only. continue; case Instruction::PHI: PN = cast<PHINode>(U); // Skip if it's already visited. if (VisitedPHIs.count(PN)) continue; VisitedPHIs.insert(PN); // FALL THROUGH case Instruction::BitCast: case Instruction::Select: case Instruction::GetElementPtr: // Need to check their usage further. break; } WorkList.push_back(U); } } return true; } bool InlineLocalsResolution::runOnModule(Module& M) { MetaDataUtils* pMdUtils = getAnalysis<MetaDataUtilsWrapper>().getMetaDataUtils(); ModuleMetaData* modMD = getAnalysis<MetaDataUtilsWrapper>().getModuleMetaData(); if (!modMD->compOpt.OptDisable) filterGlobals(M); // Compute the offset of each inline local in the kernel, // and their total size. llvm::MapVector<Function*, unsigned int> sizeMap; collectInfoOnSharedLocalMem(M); computeOffsetList(M, sizeMap); LLVMContext& C = M.getContext(); for (Function& F : M) { if (F.isDeclaration() || !isEntryFunc(pMdUtils, &F)) { continue; } unsigned int totalSize = 0; // Get the offset at which local arguments start auto sizeIter = sizeMap.find(&F); if (sizeIter != sizeMap.end()) { totalSize += sizeIter->second; } // Set the high 16 bits to a non-0 value. totalSize = (totalSize & 0xFFFF); bool IsFirstSLMArgument = true; for (Function::arg_iterator A = F.arg_begin(), AE = F.arg_end(); A != AE; ++A) { Argument* arg = &(*A); PointerType* ptrType = dyn_cast<PointerType>(arg->getType()); // Check that this is a pointer if (!ptrType) { continue; } // To the local address space if (ptrType->getAddressSpace() != ADDRESS_SPACE_LOCAL) { continue; } // Which is used if (arg->use_empty()) { continue; } bool UseAsPointerOnly = useAsPointerOnly(arg); unsigned Offset = totalSize; if (!UseAsPointerOnly) Offset |= VALID_LOCAL_HIGH_BITS; if (IsFirstSLMArgument) { auto BufType = ArrayType::get(Type::getInt8Ty(M.getContext()), 0); auto ExtSLM = new GlobalVariable(M, BufType, false, GlobalVariable::ExternalLinkage, nullptr, F.getName() + "-ExtSLM", nullptr, GlobalVariable::ThreadLocalMode::NotThreadLocal, ADDRESS_SPACE_LOCAL); auto NewPtr = ConstantExpr::getBitCast(ExtSLM, arg->getType()); arg->replaceAllUsesWith(NewPtr); // Update MD. LocalOffsetMD localOffset; localOffset.m_Var = ExtSLM; localOffset.m_Offset = Offset; modMD->FuncMD[&F].localOffsets.push_back(localOffset); IGC::appendToUsed(M, ExtSLM); IsFirstSLMArgument = false; } else { // FIXME: The following code should be removed as well by // populating similar adjustment in prolog during code // emission. // Ok, now we need to add an offset, in bytes, which is equal to totalSize. // Bitcast to i8*, GEP, bitcast back to original type. Value* sizeConstant = ConstantInt::get(Type::getInt32Ty(C), Offset); SmallVector<Value*, 1> idx(1, sizeConstant); Instruction* pInsertBefore = &(*F.begin()->getFirstInsertionPt()); Type* pLocalCharPtrType = Type::getInt8Ty(C)->getPointerTo(ADDRESS_SPACE_LOCAL); Instruction* pCharPtr = BitCastInst::CreatePointerCast(arg, pLocalCharPtrType, "localToChar", pInsertBefore); Value* pMovedCharPtr = GetElementPtrInst::Create(nullptr, pCharPtr, idx, "movedLocal", pInsertBefore); Value* pMovedPtr = CastInst::CreatePointerCast(pMovedCharPtr, ptrType, "charToLocal", pInsertBefore); // Running over arg users and use replaceUsesOfWith to fix them is not enough, // because it does not cover the usage of arg in metadata (e.g. for debug info intrinsic). // Thus, replaceAllUsesWith should be used in order to fix also debug info. arg->replaceAllUsesWith(pMovedPtr); // The above operation changed also the "arg" operand in "charPtr" to "movedPtr" // Thus, we need to fix it back (otherwise the LLVM IR will be invalid) pCharPtr->replaceUsesOfWith(pMovedPtr, arg); } } } return true; } void InlineLocalsResolution::filterGlobals(Module& M) { // This data structure saves all the unused nodes, // including the global variable definition itself, as well as all successive recursive user nodes, // in all the def-use trees corresponding to all the global variables in the entire Module. std::unordered_set<Value*> unusedNodes_forModule; // let's loop all global variables for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) { // We only care about global variables, not other globals. GlobalVariable* globalVar = dyn_cast<GlobalVariable>(&*I); if (!globalVar) { continue; } PointerType* ptrType = cast<PointerType>(globalVar->getType()); // We only care about local address space here. if (ptrType->getAddressSpace() != ADDRESS_SPACE_LOCAL) { continue; } // If the globalVar is determined to be unused, // this data structure saves the globalVar, // as well as all successive recursive user nodes in that def-use tree. std::unordered_set<Value*> unusedNodes_forOne; if (unusedGlobal(globalVar, unusedNodes_forOne)) unusedNodes_forModule.insert(unusedNodes_forOne.begin(), unusedNodes_forOne.end()); } // We only remove all the unused nodes for this Module, // after we are done processing all the global variables for the entire Module, // to prevent iterators becoming invalidated when elements get removed from the ilist. for (auto& element : unusedNodes_forModule) { // for all unused Values, // replace all uses with undefs // delete the values if (Instruction* node = dyn_cast<Instruction>(element)) { Type* Ty = node->getType(); if (!Ty->isVoidTy()) node->replaceAllUsesWith(UndefValue::get(Ty)); node->eraseFromParent(); } else if (GlobalVariable* node = dyn_cast<GlobalVariable>(element)) { Type* Ty = node->getType(); if (!Ty->isVoidTy()) node->replaceAllUsesWith(UndefValue::get(Ty)); node->eraseFromParent(); } // All other types of nodes are ignored. } } bool InlineLocalsResolution::unusedGlobal(Value* V, std::unordered_set<Value*>& unusedNodes) { for (Value::user_iterator U = V->user_begin(), UE = V->user_end(); U != UE; ++U) { if (GlobalVariable* globalVar = dyn_cast<GlobalVariable>(*U)) { if (!unusedGlobal(*U, unusedNodes)) return false; } else if (GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(*U)) { if (!unusedGlobal(*U, unusedNodes)) return false; } else if (BitCastInst* bitcast = dyn_cast<BitCastInst>(*U)) { if (!unusedGlobal(*U, unusedNodes)) return false; } else if (StoreInst* store = dyn_cast<StoreInst>(*U)) { if (store->isUnordered()) { if (store->getPointerOperand() == V) { if (!unusedGlobal(*U, unusedNodes)) return false; } else if (store->getValueOperand() == V) { return false; } } else { return false; } } else { // some other instruction return false; } } // add an unused node to the data structure unusedNodes.insert(V); return true; } void InlineLocalsResolution::collectInfoOnSharedLocalMem(Module& M) { // first we collect SLM usage on GET_MEMPOOL_PTR if (M.getFunction(BUILTIN_MEMPOOL) != nullptr) { const auto pCtx = getAnalysis<CodeGenContextWrapper>().getCodeGenContext(); const GT_SYSTEM_INFO platform = pCtx->platform.GetGTSystemInfo(); SmallVector<CallInst*, 8> callsToReplace; unsigned maxBytesOnModule = 0; unsigned maxAlignOnModule = 0; unsigned int maxWorkGroupSize = 448; if (pCtx->platform.enableMaxWorkGroupSizeCalculation() && platform.EUCount != 0 && platform.SubSliceCount != 0) { unsigned int maxNumEUsPerSubSlice = platform.EuCountPerPoolMin; if (platform.EuCountPerPoolMin == 0 || pCtx->platform.supportPooledEU()) { maxNumEUsPerSubSlice = platform.EUCount / platform.SubSliceCount; } const unsigned int numThreadsPerEU = platform.ThreadCount / platform.EUCount; unsigned int simdSizeUsed = 8; unsigned int maxWS = maxNumEUsPerSubSlice * numThreadsPerEU * simdSizeUsed; if (!iSTD::IsPowerOfTwo(maxWS)) { maxWS = iSTD::RoundPower2((DWORD)maxWS) >> 1; } maxWorkGroupSize = std::min(maxWS, 1024u); } // scan inst to collect all call instructions for (Function& F : M) { if (F.isDeclaration()) { continue; } unsigned maxBytesOnFunc = 0; for (auto I = inst_begin(&F), IE = inst_end(&F); I != IE; ++I) { Instruction* inst = &(*I); if (CallInst * CI = dyn_cast<CallInst>(inst)) { Function* pFunc = CI->getCalledFunction(); if (pFunc && pFunc->getName().equals(BUILTIN_MEMPOOL)) { // should always be called with constant operands IGC_ASSERT(isa<ConstantInt>(CI->getArgOperand(0))); IGC_ASSERT(isa<ConstantInt>(CI->getArgOperand(1))); IGC_ASSERT(isa<ConstantInt>(CI->getArgOperand(2))); const unsigned int allocAllWorkgroups = unsigned(cast<ConstantInt>(CI->getArgOperand(0))->getZExtValue()); const unsigned int numAdditionalElements = unsigned(cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue()); const unsigned int elementSize = unsigned(cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue()); unsigned int numElements = numAdditionalElements; if (allocAllWorkgroups) { numElements += maxWorkGroupSize; } const unsigned int size = numElements * elementSize; const unsigned int align = elementSize; maxBytesOnFunc = std::max(maxBytesOnFunc, size); maxBytesOnModule = std::max(maxBytesOnModule, size); maxAlignOnModule = std::max(maxAlignOnModule, align); callsToReplace.push_back(CI); } } } if (maxBytesOnFunc != 0) { m_FuncToMemPoolSizeMap[&F] = maxBytesOnFunc; } } if (!callsToReplace.empty()) { Type* bufType = ArrayType::get(Type::getInt8Ty(M.getContext()), uint64_t(maxBytesOnModule)); m_pGV = new GlobalVariable(M, bufType, false, GlobalVariable::ExternalLinkage, ConstantAggregateZero::get(bufType), "GenSLM.LocalMemPoolOnGetMemPoolPtr", nullptr, GlobalVariable::ThreadLocalMode::NotThreadLocal, ADDRESS_SPACE_LOCAL); m_pGV->setAlignment(IGCLLVM::getCorrectAlign(maxAlignOnModule)); for (auto call : callsToReplace) { CastInst* cast = new BitCastInst( m_pGV, call->getCalledFunction()->getReturnType(), "mempoolcast", call); cast->setDebugLoc(call->getDebugLoc()); call->replaceAllUsesWith(cast); call->eraseFromParent(); } } } // let's loop all global variables for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) { // We only care about global variables, not other globals. GlobalVariable* globalVar = dyn_cast<GlobalVariable>(&*I); if (!globalVar) { continue; } PointerType* ptrType = dyn_cast<PointerType>(globalVar->getType()); IGC_ASSERT_MESSAGE(ptrType, "The type of a global variable must be a pointer type"); if (!ptrType) { continue; } // We only care about local address space here. if (ptrType->getAddressSpace() != ADDRESS_SPACE_LOCAL) { continue; } // For each SLM buffer, set section to avoid alignment changing by llvm. // Add external linkage and DSO scope information. globalVar->setLinkage(GlobalValue::ExternalLinkage); globalVar->setDSOLocal(false); globalVar->setSection("localSLM"); // Find the functions which this globalVar belongs to.... for (Value::user_iterator U = globalVar->user_begin(), UE = globalVar->user_end(); U != UE; ++U) { Instruction* user = dyn_cast<Instruction>(*U); if (!user) { continue; } m_FuncToVarsMap[user->getParent()->getParent()].insert(globalVar); } } // set debugging info, and insert mov inst. for (const auto& I : m_FuncToVarsMap) { Function* userFunc = I.first; for (auto* G : I.second) { Instruction * pInsertBefore = &(*userFunc->begin()->getFirstInsertionPt()); TODO("Should inline local buffer points to origin offset 'globalVar' or to fixed offset 'pMovedPtr'?"); Utils::UpdateGlobalVarDebugInfo(G, G, pInsertBefore, true); } } } void InlineLocalsResolution::computeOffsetList(Module& M, llvm::MapVector<Function*, unsigned int>& sizeMap) { llvm::MapVector<Function*, llvm::MapVector<GlobalVariable*, unsigned int>> offsetMap; MetaDataUtils* pMdUtils = getAnalysis<MetaDataUtilsWrapper>().getMetaDataUtils(); ModuleMetaData* modMD = getAnalysis<MetaDataUtilsWrapper>().getModuleMetaData(); DataLayout DL = M.getDataLayout(); CallGraph& CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); if (m_FuncToVarsMap.empty()) { return; } // let's traverse the CallGraph to calculate the local // variables of kernel from all user functions. m_chkSet.clear(); for (auto& N : CG) { Function* f = N.second->getFunction(); if (!f || f->isDeclaration() || m_chkSet.find(f) != m_chkSet.end()) continue; traverseCGN(*N.second); } // set up the offsetMap; for (const auto& I : m_FuncToVarsMap) { Function* F = I.first; // loop through all global variables for (auto G : I.second) { auto itr = sizeMap.find(F); unsigned int offset = itr == sizeMap.end() ? 0 : itr->second; #if LLVM_VERSION_MAJOR < 11 offset = iSTD::Align(offset, DL.getPreferredAlignment(G)); #else offset = iSTD::Align(offset, DL.getPreferredAlign(G).value()); #endif // Save the offset of the current local // (set the high bits to be non-0 here too) offsetMap[F][G] = (offset & 0xFFFF); // And the total size after this local is added PointerType* ptrType = dyn_cast<PointerType>(G->getType()); Type* varType = ptrType->getElementType(); if (G == m_pGV) { // it is GetMemPoolPtr usage offset += m_FuncToMemPoolSizeMap[F]; } else { offset += (unsigned int)DL.getTypeAllocSize(varType); } sizeMap[F] = offset; } } // Ok, we've collected the information, now write it into the MD. for (auto& iter : sizeMap) { // ignore non-entry functions. if (!isEntryFunc(pMdUtils, iter.first)) { continue; } // If this function doesn't have any locals, no need for MD. if (iter.second == 0) { continue; } // We need the total size to have at least 32-byte alignment. // This is because right after the space allocated to the inline locals, // we are going to have inline parameters. So, we need to make sure the // first local parameter is appropriately aligned, which, at worst, // can be 256 bits. iter.second = iSTD::Align(iter.second, 32); // Add the size information of this function modMD->FuncMD[iter.first].localSize = iter.second; // And now the offsets. for (const auto& offsetIter : offsetMap[iter.first]) { unsigned Offset = offsetIter.second; if (!useAsPointerOnly(offsetIter.first)) Offset |= VALID_LOCAL_HIGH_BITS; LocalOffsetMD localOffset; localOffset.m_Var = offsetIter.first; localOffset.m_Offset = Offset; modMD->FuncMD[iter.first].localOffsets.push_back(localOffset); } } pMdUtils->save(M.getContext()); } void InlineLocalsResolution::traverseCGN(const llvm::CallGraphNode& CGN) { Function* f = CGN.getFunction(); // mark this function m_chkSet.insert(f); for (const auto& N : CGN) { Function* sub = N.second->getFunction(); if (!sub || sub->isDeclaration()) continue; // we reach here, because there is sub-function inside the node if (m_chkSet.find(sub) == m_chkSet.end()) { // this sub-routine is not visited before. // visit it first traverseCGN(*N.second); } // the sub-routine was visited before, collect information // count each global on this sub-routine GlobalVariableSet& GS_f = m_FuncToVarsMap[f]; const GlobalVariableSet& GS_sub = m_FuncToVarsMap[sub]; GS_f.insert(GS_sub.begin(), GS_sub.end()); // automatic storages if (m_FuncToMemPoolSizeMap.find(sub) != m_FuncToMemPoolSizeMap.end()) { // this sub-function has automatic storage if (m_FuncToMemPoolSizeMap.find(f) != m_FuncToMemPoolSizeMap.end()) { // caller has its own memory pool size, choose the max m_FuncToMemPoolSizeMap[f] = std::max(m_FuncToMemPoolSizeMap[f], m_FuncToMemPoolSizeMap[sub]); } else { m_FuncToMemPoolSizeMap[f] = m_FuncToMemPoolSizeMap[sub]; } } } }
37.183168
133
0.577642
ConiKost
33d65048f975aeb53fac61ef2caefc48b72fcd97
10,752
cpp
C++
aws-cpp-sdk-timestream-query/source/TimestreamQueryClient.cpp
Eliyahu-Machluf/aws-sdk-cpp
97b8d6cdc16df298b80941b94327a5026efa7f8c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-timestream-query/source/TimestreamQueryClient.cpp
Eliyahu-Machluf/aws-sdk-cpp
97b8d6cdc16df298b80941b94327a5026efa7f8c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-timestream-query/source/TimestreamQueryClient.cpp
Eliyahu-Machluf/aws-sdk-cpp
97b8d6cdc16df298b80941b94327a5026efa7f8c
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/core/utils/Outcome.h> #include <aws/core/auth/AWSAuthSigner.h> #include <aws/core/client/CoreErrors.h> #include <aws/core/client/RetryStrategy.h> #include <aws/core/http/HttpClient.h> #include <aws/core/http/HttpResponse.h> #include <aws/core/http/HttpClientFactory.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/utils/threading/Executor.h> #include <aws/core/utils/DNS.h> #include <aws/core/utils/logging/LogMacros.h> #include <aws/timestream-query/TimestreamQueryClient.h> #include <aws/timestream-query/TimestreamQueryEndpoint.h> #include <aws/timestream-query/TimestreamQueryErrorMarshaller.h> #include <aws/timestream-query/model/CancelQueryRequest.h> #include <aws/timestream-query/model/DescribeEndpointsRequest.h> #include <aws/timestream-query/model/QueryRequest.h> using namespace Aws; using namespace Aws::Auth; using namespace Aws::Client; using namespace Aws::TimestreamQuery; using namespace Aws::TimestreamQuery::Model; using namespace Aws::Http; using namespace Aws::Utils::Json; static const char* SERVICE_NAME = "timestream"; static const char* ALLOCATION_TAG = "TimestreamQueryClient"; TimestreamQueryClient::TimestreamQueryClient(const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG), SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<TimestreamQueryErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } TimestreamQueryClient::TimestreamQueryClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials), SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<TimestreamQueryErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } TimestreamQueryClient::TimestreamQueryClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider, SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<TimestreamQueryErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } TimestreamQueryClient::~TimestreamQueryClient() { } void TimestreamQueryClient::init(const ClientConfiguration& config) { SetServiceClientName("Timestream Query"); m_configScheme = SchemeMapper::ToString(config.scheme); if (config.endpointOverride.empty()) { m_uri = m_configScheme + "://" + TimestreamQueryEndpoint::ForRegion(config.region, config.useDualStack); } else { OverrideEndpoint(config.endpointOverride); } if (!config.endpointOverride.empty()) { m_enableEndpointDiscovery = false; } else { m_enableEndpointDiscovery = config.enableEndpointDiscovery; } } void TimestreamQueryClient::OverrideEndpoint(const Aws::String& endpoint) { if (endpoint.compare(0, 7, "http://") == 0 || endpoint.compare(0, 8, "https://") == 0) { m_uri = endpoint; } else { m_uri = m_configScheme + "://" + endpoint; } m_enableEndpointDiscovery = false; } CancelQueryOutcome TimestreamQueryClient::CancelQuery(const CancelQueryRequest& request) const { Aws::Http::URI uri = m_uri; if (m_enableEndpointDiscovery) { Aws::String endpointKey = "Shared"; Aws::String endpoint; if (m_endpointsCache.Get(endpointKey, endpoint)) { AWS_LOGSTREAM_TRACE("CancelQuery", "Making request to cached endpoint: " << endpoint); uri = m_configScheme + "://" + endpoint; } else { AWS_LOGSTREAM_TRACE("CancelQuery", "Endpoint discovery is enabled and there is no usable endpoint in cache. Discovering endpoints from service..."); DescribeEndpointsRequest endpointRequest; auto endpointOutcome = DescribeEndpoints(endpointRequest); if (endpointOutcome.IsSuccess() && !endpointOutcome.GetResult().GetEndpoints().empty()) { const auto& item = endpointOutcome.GetResult().GetEndpoints()[0]; m_endpointsCache.Put(endpointKey, item.GetAddress(), std::chrono::minutes(item.GetCachePeriodInMinutes())); uri = m_configScheme + "://" + item.GetAddress(); AWS_LOGSTREAM_TRACE("CancelQuery", "Endpoints cache updated. Address: " << item.GetAddress() << ". Valid in: " << item.GetCachePeriodInMinutes() << " minutes. Making request to newly discovered endpoint."); } else { AWS_LOGSTREAM_ERROR("CancelQuery", "Failed to discover endpoints " << endpointOutcome.GetError()); return CancelQueryOutcome(Aws::Client::AWSError<TimestreamQueryErrors>(TimestreamQueryErrors::RESOURCE_NOT_FOUND, "INVALID_ENDPOINT", "Failed to discover endpoint", false)); } } } Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); return CancelQueryOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } CancelQueryOutcomeCallable TimestreamQueryClient::CancelQueryCallable(const CancelQueryRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CancelQueryOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CancelQuery(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void TimestreamQueryClient::CancelQueryAsync(const CancelQueryRequest& request, const CancelQueryResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CancelQueryAsyncHelper( request, handler, context ); } ); } void TimestreamQueryClient::CancelQueryAsyncHelper(const CancelQueryRequest& request, const CancelQueryResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CancelQuery(request), context); } DescribeEndpointsOutcome TimestreamQueryClient::DescribeEndpoints(const DescribeEndpointsRequest& request) const { Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); return DescribeEndpointsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } DescribeEndpointsOutcomeCallable TimestreamQueryClient::DescribeEndpointsCallable(const DescribeEndpointsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeEndpointsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeEndpoints(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void TimestreamQueryClient::DescribeEndpointsAsync(const DescribeEndpointsRequest& request, const DescribeEndpointsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeEndpointsAsyncHelper( request, handler, context ); } ); } void TimestreamQueryClient::DescribeEndpointsAsyncHelper(const DescribeEndpointsRequest& request, const DescribeEndpointsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeEndpoints(request), context); } QueryOutcome TimestreamQueryClient::Query(const QueryRequest& request) const { Aws::Http::URI uri = m_uri; if (m_enableEndpointDiscovery) { Aws::String endpointKey = "Shared"; Aws::String endpoint; if (m_endpointsCache.Get(endpointKey, endpoint)) { AWS_LOGSTREAM_TRACE("Query", "Making request to cached endpoint: " << endpoint); uri = m_configScheme + "://" + endpoint; } else { AWS_LOGSTREAM_TRACE("Query", "Endpoint discovery is enabled and there is no usable endpoint in cache. Discovering endpoints from service..."); DescribeEndpointsRequest endpointRequest; auto endpointOutcome = DescribeEndpoints(endpointRequest); if (endpointOutcome.IsSuccess() && !endpointOutcome.GetResult().GetEndpoints().empty()) { const auto& item = endpointOutcome.GetResult().GetEndpoints()[0]; m_endpointsCache.Put(endpointKey, item.GetAddress(), std::chrono::minutes(item.GetCachePeriodInMinutes())); uri = m_configScheme + "://" + item.GetAddress(); AWS_LOGSTREAM_TRACE("Query", "Endpoints cache updated. Address: " << item.GetAddress() << ". Valid in: " << item.GetCachePeriodInMinutes() << " minutes. Making request to newly discovered endpoint."); } else { AWS_LOGSTREAM_ERROR("Query", "Failed to discover endpoints " << endpointOutcome.GetError()); return QueryOutcome(Aws::Client::AWSError<TimestreamQueryErrors>(TimestreamQueryErrors::RESOURCE_NOT_FOUND, "INVALID_ENDPOINT", "Failed to discover endpoint", false)); } } } Aws::StringStream ss; ss << "/"; uri.SetPath(uri.GetPath() + ss.str()); return QueryOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } QueryOutcomeCallable TimestreamQueryClient::QueryCallable(const QueryRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< QueryOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->Query(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void TimestreamQueryClient::QueryAsync(const QueryRequest& request, const QueryResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->QueryAsyncHelper( request, handler, context ); } ); } void TimestreamQueryClient::QueryAsyncHelper(const QueryRequest& request, const QueryResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, Query(request), context); }
43.707317
231
0.751581
Eliyahu-Machluf
33d715e1533c353d55ab2f62af27176130608be6
602
cpp
C++
3D PooFace/GDIPlusManager.cpp
guiteixeirapimentel/3DGameMechanics
ff02c0067841565cda6b5455fb6119a22783131a
[ "MIT" ]
null
null
null
3D PooFace/GDIPlusManager.cpp
guiteixeirapimentel/3DGameMechanics
ff02c0067841565cda6b5455fb6119a22783131a
[ "MIT" ]
null
null
null
3D PooFace/GDIPlusManager.cpp
guiteixeirapimentel/3DGameMechanics
ff02c0067841565cda6b5455fb6119a22783131a
[ "MIT" ]
null
null
null
#include "GDIPlusManager.h" #include <algorithm> namespace Gdiplus { using std::min; using std::max; } #include <gdiplus.h> #pragma comment(lib, "gdiplus.lib") ULONG_PTR GDIPlusManager::token = 0; int GDIPlusManager::refCount = 0; GDIPlusManager::GDIPlusManager() { if (refCount++ == 0) { Gdiplus::GdiplusStartupInput input; input.GdiplusVersion = 1; input.DebugEventCallback = nullptr; input.SuppressBackgroundThread = false; Gdiplus::GdiplusStartup(&token, &input, nullptr); } } GDIPlusManager::~GDIPlusManager() { if (--refCount == 0) { Gdiplus::GdiplusShutdown(token); } }
17.2
51
0.714286
guiteixeirapimentel