hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
58dd01e6655ce0699aee914f1990c9e77d51146b
12,637
cpp
C++
samples/BatchEffectApp/BatchDenoiseEffectApp.cpp
NVIDIA/MAXINE-VFX-SDK
7f69da2ee4dcb02e6b024b3f40c5892de84fcb45
[ "MIT" ]
77
2021-04-12T20:16:19.000Z
2022-03-31T03:43:41.000Z
samples/BatchEffectApp/BatchDenoiseEffectApp.cpp
Tfpl1/MAXINE-VFX-SDK
3df6c37852afad9f15ee0b85e51b5b49e611cfc0
[ "MIT" ]
null
null
null
samples/BatchEffectApp/BatchDenoiseEffectApp.cpp
Tfpl1/MAXINE-VFX-SDK
3df6c37852afad9f15ee0b85e51b5b49e611cfc0
[ "MIT" ]
21
2021-04-15T05:45:59.000Z
2022-02-24T09:51:22.000Z
/*############################################################################### # # Copyright (c) 2020 NVIDIA Corporation # # 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 <stdio.h> #include <string.h> #include <string> #include <cuda_runtime_api.h> #include "BatchUtilities.h" #include "nvCVOpenCV.h" #include "nvVideoEffects.h" #include "opencv2/opencv.hpp" #ifdef _MSC_VER #define strcasecmp _stricmp #endif // _MSC_VER #define BAIL_IF_ERR(err) do { if (0 != (err)) { goto bail; } } while(0) #define BAIL_IF_NULL(x, err, code) do { if ((void*)(x) == NULL) { err = code; goto bail; } } while(0) #define BAIL_IF_FALSE(x, err, code) do { if (!(x)) { err = code; goto bail; } } while(0) #define BAIL(err, code) do { err = code; goto bail; } while(0) bool FLAG_verbose = false; float FLAG_strength = 0.f, FLAG_scale = 1.0; int FLAG_mode = 0, FLAG_resolution = 0, FLAG_batchSize = 8; std::string FLAG_outFile, FLAG_modelDir; std::vector<const char*> FLAG_inFiles; // Set this when using OTA Updates // This path is used by nvVideoEffectsProxy.cpp to load the SDK dll // when using OTA Updates char *g_nvVFXSDKPath = NULL; static bool GetFlagArgVal(const char *flag, const char *arg, const char **val) { if (*arg != '-') return false; while (*++arg == '-') continue; const char *s = strchr(arg, '='); if (s == NULL) { if (strcmp(flag, arg) != 0) return false; *val = NULL; return true; } size_t n = s - arg; if ((strlen(flag) != n) || (strncmp(flag, arg, n) != 0)) return false; *val = s + 1; return true; } static bool GetFlagArgVal(const char *flag, const char *arg, std::string *val) { const char *valStr; if (!GetFlagArgVal(flag, arg, &valStr)) return false; val->assign(valStr ? valStr : ""); return true; } static bool GetFlagArgVal(const char *flag, const char *arg, bool *val) { const char *valStr; bool success = GetFlagArgVal(flag, arg, &valStr); if (success) { *val = (valStr == NULL || strcasecmp(valStr, "true") == 0 || strcasecmp(valStr, "on") == 0 || strcasecmp(valStr, "yes") == 0 || strcasecmp(valStr, "1") == 0 ); } return success; } static bool GetFlagArgVal(const char *flag, const char *arg, float *val) { const char *valStr; bool success = GetFlagArgVal(flag, arg, &valStr); if (success) *val = strtof(valStr, NULL); return success; } static bool GetFlagArgVal(const char *flag, const char *arg, long *val) { const char *valStr; bool success = GetFlagArgVal(flag, arg, &valStr); if (success) *val = strtol(valStr, NULL, 10); return success; } static bool GetFlagArgVal(const char *flag, const char *arg, int *val) { long longVal; bool success = GetFlagArgVal(flag, arg, &longVal); if (success) *val = (int)longVal; return success; } static void Usage() { printf( "BatchDenoiseEffectApp [flags ...] inFile1 [ inFileN ...]\n" " where flags is:\n" " --out_file=<path> output video files to be written (a pattern with one %%u or %%d), default \"BatchOut_%%02u.mp4\"\n" " --strength=<value> strength of denoising [0-1]\n" " --model_dir=<path> the path to the directory that contains the models\n" " --batchsize=<value> size of the batch (default: 8)\n" " --verbose verbose output\n" " and inFile1 ... are identically sized video files\n" ); } static int ParseMyArgs(int argc, char **argv) { int errs = 0; for (--argc, ++argv; argc--; ++argv) { bool help; const char *arg = *argv; if (arg[0] == '-') { if (arg[1] == '-') { // double-dash if (GetFlagArgVal("verbose", arg, &FLAG_verbose) || GetFlagArgVal("strength", arg, &FLAG_strength) || GetFlagArgVal("scale", arg, &FLAG_scale) || GetFlagArgVal("mode", arg, &FLAG_mode) || GetFlagArgVal("model_dir", arg, &FLAG_modelDir) || GetFlagArgVal("out_file", arg, &FLAG_outFile) || GetFlagArgVal("batch_size", arg, &FLAG_batchSize) ) { continue; } else if (GetFlagArgVal("help", arg, &help)) { // --help Usage(); errs = 1; } } else { // single dash for (++arg; *arg; ++arg) { if (*arg == 'v') { FLAG_verbose = true; } else { printf("Unknown flag ignored: \"-%c\"\n", *arg); } } continue; } } else { // no dash FLAG_inFiles.push_back(arg); } } return errs; } class App { public: NvVFX_Handle _eff; NvCVImage _src, _stg, _dst; CUstream _stream; unsigned _batchSize; App() : _eff(nullptr), _stream(0), _batchSize(0) {} ~App() { NvVFX_DestroyEffect(_eff); if (_stream) NvVFX_CudaStreamDestroy(_stream); } NvCV_Status init(const char* effectName, unsigned batchSize, const NvCVImage *srcImg) { NvCV_Status err = NVCV_ERR_UNIMPLEMENTED; _batchSize = batchSize; BAIL_IF_ERR(err = NvVFX_CreateEffect(effectName, &_eff)); BAIL_IF_ERR(err = AllocateBatchBuffer(&_src, _batchSize, srcImg->width, srcImg->height, NVCV_BGR, NVCV_F32, NVCV_PLANAR, NVCV_CUDA, 1)); // BAIL_IF_ERR(err = AllocateBatchBuffer(&_dst, _batchSize, srcImg->width, srcImg->height, NVCV_BGR, NVCV_F32, NVCV_PLANAR, NVCV_CUDA, 1)); // BAIL_IF_ERR(err = NvVFX_SetString(_eff, NVVFX_MODEL_DIRECTORY, FLAG_modelDir.c_str())); // { // Set parameters. NvCVImage nth; BAIL_IF_ERR(err = NvVFX_SetImage(_eff, NVVFX_INPUT_IMAGE, NthImage(0, srcImg->height, &_src, &nth))); // Set the first of the batched images in ... BAIL_IF_ERR(err = NvVFX_SetImage(_eff, NVVFX_OUTPUT_IMAGE, NthImage(0, _dst.height / _batchSize, &_dst, &nth))); // ... and out BAIL_IF_ERR(err = NvVFX_CudaStreamCreate(&_stream)); BAIL_IF_ERR(err = NvVFX_SetCudaStream(_eff, NVVFX_CUDA_STREAM, _stream)); BAIL_IF_ERR(err = NvVFX_Load(_eff)); } bail: return err; } }; NvCV_Status BatchProcess(const char* effectName, const std::vector<const char*>& srcVideos, unsigned batchSize, const char *outfilePattern) { NvCV_Status err = NVCV_SUCCESS; App app; cv::Mat ocv1, ocv2; NvCVImage nvx1, nvx2; unsigned srcWidth, srcHeight, dstHeight, i; void** arrayOfStates = nullptr; void** batchOfStates = nullptr; unsigned int stateSizeInBytes; int numOfVideoStreams = srcVideos.size(); std::vector<cv::VideoCapture> srcCaptures(numOfVideoStreams); std::vector<cv::VideoWriter> dstWriters(numOfVideoStreams); for (int i = 0; i < numOfVideoStreams; i++) { srcCaptures[i].open(srcVideos[i]); if (srcCaptures[i].isOpened()==false) BAIL(err, NVCV_ERR_READ); int width, height; double fps; width = (int)srcCaptures[i].get(cv::CAP_PROP_FRAME_WIDTH); height = (int)srcCaptures[i].get(cv::CAP_PROP_FRAME_HEIGHT); fps = srcCaptures[i].get(cv::CAP_PROP_FPS); const int fourcc_h264 = cv::VideoWriter::fourcc('H','2','6','4'); char fileName[1024]; snprintf(fileName, sizeof(fileName), outfilePattern, i); dstWriters[i].open(fileName, fourcc_h264, fps, cv::Size2i(width,height)); if (dstWriters[i].isOpened() == false) BAIL(err, NVCV_ERR_WRITE); } // Read in the first image, to determine the resolution for init() BAIL_IF_FALSE(srcVideos.size() > 0, err, NVCV_ERR_MISSINGINPUT); srcCaptures[0] >> ocv1; srcCaptures[0].set(cv::CAP_PROP_POS_FRAMES, 0); //resetting to first frame if (!ocv1.data) { printf("Cannot read video file \"%s\"\n", srcVideos[0]); BAIL(err, NVCV_ERR_READ); } NVWrapperForCVMat(&ocv1, &nvx1); srcWidth = nvx1.width; srcHeight = nvx1.height; BAIL_IF_ERR(err = app.init(effectName, batchSize, &nvx1)); // Init effect and buffers // Creating state objects, one per stream. BAIL_IF_ERR(err = NvVFX_GetU32(app._eff, NVVFX_STATE_SIZE, &stateSizeInBytes)); arrayOfStates = (void**)calloc(numOfVideoStreams, sizeof(void*)); // allocating void* array of numOfVideoStreams elements for (int i = 0; i < numOfVideoStreams; i++) { cudaMalloc(&arrayOfStates[i], stateSizeInBytes); cudaMemsetAsync(arrayOfStates[i], 0, stateSizeInBytes,app._stream); } //Creating batch array to hold states batchOfStates = (void**)calloc(batchSize, sizeof(void*)); dstHeight = app._dst.height / batchSize; BAIL_IF_ERR(err = NvCVImage_Alloc(&nvx2, app._dst.width, dstHeight, ((app._dst.numComponents == 1) ? NVCV_Y : NVCV_BGR), NVCV_U8, NVCV_CHUNKY, NVCV_CPU, 0)); CVWrapperForNvCVImage(&nvx2, &ocv2); for(int j=0;;j++) { for (int i = 0; i < batchSize; i++) { int capIdx = i%numOfVideoStreams; // interlacing frames from different video stream, but can in any order srcCaptures[capIdx] >> ocv1; if (ocv1.empty()) goto bail; batchOfStates[i] = arrayOfStates[capIdx]; NVWrapperForCVMat(&ocv1, &nvx1); if (!(nvx1.width == srcWidth && nvx1.height == srcHeight)) { printf("Input video file \"%s\" %ux%u does not match %ux%u\n" "Batching requires all video frames to be of the same size\n", srcVideos[i], nvx1.width, nvx1.height, srcWidth, srcHeight); BAIL(err, NVCV_ERR_MISMATCH); } BAIL_IF_ERR(err = TransferToNthImage(i, &nvx1, &app._src, 1.f / 255.f, app._stream, &app._stg)); ocv1.release(); } // Run batch BAIL_IF_ERR(err = NvVFX_SetU32(app._eff, NVVFX_BATCH_SIZE, (unsigned)batchSize)); // The batchSize can change every Run BAIL_IF_ERR(err = NvVFX_SetObject(app._eff, NVVFX_STATE, (void*)batchOfStates)); // The batch of states can change every Run BAIL_IF_ERR(err = NvVFX_Run(app._eff, 0)); for (i = 0; i < batchSize; ++i) { int writerIdx = i % numOfVideoStreams; BAIL_IF_ERR(err = TransferFromNthImage(i, &app._dst, &nvx2, 255.f, app._stream, &app._stg)); dstWriters[writerIdx] << ocv2; } // NvCVImage_Dealloc() is called in the destructors } bail: if (arrayOfStates) { for (unsigned i = 0; i < numOfVideoStreams; i++) { if (arrayOfStates[i]) cudaFree(arrayOfStates[i]); } free(arrayOfStates); } if (batchOfStates) free(batchOfStates); for (auto& cap : srcCaptures) { if (cap.isOpened()) cap.release(); } for (auto& writer : dstWriters) { if (writer.isOpened()) writer.release(); } return err; } int main(int argc, char** argv) { int nErrs; NvCV_Status vfxErr; nErrs = ParseMyArgs(argc, argv); if (nErrs) return nErrs; if (FLAG_outFile.empty()) FLAG_outFile = "BatchOut_%02u.mp4"; else if (std::string::npos == FLAG_outFile.find_first_of('%')) FLAG_outFile.insert(FLAG_outFile.size() - 4, "_%02u"); vfxErr = BatchProcess(NVVFX_FX_DENOISING, FLAG_inFiles, FLAG_batchSize, FLAG_outFile.c_str()); if (NVCV_SUCCESS != vfxErr) { Usage(); printf("Error: %s\n", NvCV_GetErrorStringFromCode(vfxErr)); nErrs = (int)vfxErr; } return nErrs; }
36.523121
168
0.616365
[ "vector" ]
58eb72a0686fb6c000a3c10d14141f6296530a34
1,380
cpp
C++
R-package/targeted/src/nb_interface.cpp
kkholst/target
a63f3121efeae2c3441d7d2d2261fdf85038868e
[ "Apache-2.0" ]
1
2021-09-17T19:01:21.000Z
2021-09-17T19:01:21.000Z
R-package/targeted/src/nb_interface.cpp
kkholst/target
a63f3121efeae2c3441d7d2d2261fdf85038868e
[ "Apache-2.0" ]
null
null
null
R-package/targeted/src/nb_interface.cpp
kkholst/target
a63f3121efeae2c3441d7d2d2261fdf85038868e
[ "Apache-2.0" ]
null
null
null
/*! @file nb_interface.cpp @author Klaus K. Holst @copyright 2018-2021, Klaus Kähler Holst @brief R interface for the Weighted Naive Bayes Classifier. The relevant bindings are created in \c RcppExports.cpp, \c RcppExports.h with \c Rcpp::compileAttributes() */ // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::interfaces(r, cpp)]] // [[Rcpp::plugins(cpp11)]] #include <RcppArmadillo.h> #include <vector> #include <target/nb.hpp> // [[Rcpp::export(name=".NB")]] Rcpp::List NB(arma::vec y, arma::mat x, arma::uvec xlev, arma::vec ylev, arma::vec weights, double laplacesmooth=1.0) { std::vector<target::raggedArray> res; res = target::nb(y, x, xlev, ylev, weights, laplacesmooth); return( Rcpp::wrap(res) ); } // [[Rcpp::export(name=".predNB")]] arma::mat predNB(arma::mat const &X, Rcpp::List const &condprob, Rcpp::List const &xord, arma::uvec multinomial, arma::vec prior, double threshold=1E-3) { target::raggedArray condprob0; for (unsigned i=0; i<condprob.size(); i++) { condprob0.push_back(condprob[i]); } target::raggedArray xord0; for (unsigned i=0; i<xord.size(); i++) { xord0.push_back(xord[i]); } arma::mat res = target::prednb(X, condprob0, xord0, multinomial, prior, threshold); return(res); }
27.058824
75
0.614493
[ "vector" ]
58f0c9b102142e158f167f0b567fea9f7f48dc41
2,921
cpp
C++
src/shove_integrator.cpp
avkhadiev/polymer
87b0452ec844a1f71d0da8cb45cb2158f4b9d796
[ "MIT" ]
1
2019-07-02T23:12:48.000Z
2019-07-02T23:12:48.000Z
src/shove_integrator.cpp
avkhadiev/polymer
87b0452ec844a1f71d0da8cb45cb2158f4b9d796
[ "MIT" ]
null
null
null
src/shove_integrator.cpp
avkhadiev/polymer
87b0452ec844a1f71d0da8cb45cb2158f4b9d796
[ "MIT" ]
null
null
null
// 2017 Artur Avkhadiev /*! \file shove_integrator.cpp */ #include <vector> #include <string> #include <algorithm> /* std::fill */ #include <cmath> /* pow */ #include <cassert> #include "../include/shove_integrator.h" /** * initialization: setup force updater with zero potential * no kinetic energy observables * no periodic boundary conditions */ ShoveIntegrator::ShoveIntegrator( double tol, Observable *wc, double tiny, int maxiter): RattleIntegrator(ForceUpdater(), tol, NULL, NULL, wc, 0.0, tiny, maxiter){} ShoveIntegrator::~ShoveIntegrator(){} /** * move: utilizes functions from RATTLE */ void ShoveIntegrator::move(double timestep, simple::AtomState &state, bool calculate_observables){ // really there is no time in configuration space. // speeds of the atoms in the state will already be such that the // the appropriate "timestep" is 1.0 _set_timestep(1.0); if(calculate_observables){ _zero_accumulators(); } simple::AtomPolymer molecule_last_step; simple::AtomPolymer molecule_half_step_to_correct; // loop over polymer molecules, perform verlet half-step and correction for (int im = 0; im < state.nm(); ++im){ // molecule contains positions and velocities at last step molecule_last_step = state.polymers.at(im); // pass molecule at last step to verlet integrator by value // the integrator returns the molecule // with uncorrected full-step positions // and uncorrected half-step velocities molecule_half_step_to_correct = _move_verlet_half_step(molecule_last_step); // pass both last-step molecule and molecule from verlet integrator // to RATTLE for iterative correction // molecule with corrected full-step positions and // corrected half-step velocities is stored in the state try { state.polymers.at(im) = _move_correct_half_step(molecule_last_step, molecule_half_step_to_correct); } catch (std::invalid_argument) { state.write_to_file("/Users/Arthur/stratt/polymer/test/", "log", true, true); fprintf(stderr, "%s\n", "RATTLE: wrote out crashing configuration to log"); throw; } } // loop over solvent molecules, perform verlet half-step simple::Solvent solvent; for (int is = 0; is < state.nsolvents(); ++is){ solvent = state.solvents.at(is); state.solvents.at(is) = _move_verlet_half_step(solvent); } // r(t + dt) has been calculated and corrected // ????????????????????????????????????????????? // SECOND STAGE --- VELOCITY CORRECTION // ????????????????????????????????????????????? // multiply accumulators by whatever factors necessary if(calculate_observables) { _correct_accumulators(); } }
37.935065
111
0.636768
[ "vector" ]
58f2da6267fba197442872ce8edaeec7869897e3
3,967
cpp
C++
applications/FemToDemApplication/fem_to_dem_application_variables.cpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
1
2019-08-01T09:01:08.000Z
2019-08-01T09:01:08.000Z
applications/FemToDemApplication/fem_to_dem_application_variables.cpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
null
null
null
applications/FemToDemApplication/fem_to_dem_application_variables.cpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
null
null
null
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ \. // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics FemDem Application // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Alejandro Cornejo Velazquez // #include "fem_to_dem_application_variables.h" namespace Kratos { KRATOS_CREATE_VARIABLE(bool, VOLUME_COUNTED) KRATOS_CREATE_VARIABLE(double, DAMAGE_ELEMENT) KRATOS_CREATE_VARIABLE(double, ERASED_VOLUME) KRATOS_CREATE_VARIABLE(double, TIME_UNIT_CONVERTER) KRATOS_CREATE_VARIABLE(Vector, STRESS_VECTOR) KRATOS_CREATE_VARIABLE(Vector, DISPLACEMENT_INCREMENT) KRATOS_CREATE_VARIABLE(double, YIELD_STRESS_C) KRATOS_CREATE_VARIABLE(double, YIELD_STRESS_T) KRATOS_CREATE_VARIABLE(int, INTERNAL_PRESSURE_ITERATION) KRATOS_CREATE_VARIABLE(double, FRAC_ENERGY_T) KRATOS_CREATE_VARIABLE(double, FRAC_ENERGY_C) KRATOS_CREATE_VARIABLE(Vector, STRESS_VECTOR_INTEGRATED) KRATOS_CREATE_VARIABLE(double, THRESHOLD) KRATOS_CREATE_VARIABLE(Vector, SMOOTHED_STRESS_VECTOR) KRATOS_CREATE_VARIABLE(std::string,YIELD_SURFACE) KRATOS_CREATE_VARIABLE(Vector, STRAIN_VECTOR) KRATOS_CREATE_VARIABLE(bool, TANGENT_CONSTITUTIVE_TENSOR) KRATOS_CREATE_VARIABLE(bool, SMOOTHING) KRATOS_CREATE_VARIABLE(double, IS_DAMAGED) KRATOS_CREATE_VARIABLE(double, NODAL_DAMAGE) KRATOS_CREATE_VARIABLE(int, RECONSTRUCT_PRESSURE_LOAD) KRATOS_CREATE_VARIABLE(int, IS_DYNAMIC) KRATOS_CREATE_VARIABLE(double, STRESS_THRESHOLD) KRATOS_CREATE_VARIABLE(double, INITIAL_THRESHOLD) KRATOS_CREATE_VARIABLE(int, INTEGRATION_COEFFICIENT) KRATOS_CREATE_VARIABLE(std::string, MAPPING_PROCEDURE) KRATOS_CREATE_VARIABLE(bool, GENERATE_DEM) KRATOS_CREATE_VARIABLE(bool, RECOMPUTE_NEIGHBOURS) KRATOS_CREATE_VARIABLE(bool, IS_DEM) KRATOS_CREATE_VARIABLE(bool, IS_SKIN) KRATOS_CREATE_VARIABLE(bool, PRESSURE_EXPANDED) KRATOS_CREATE_VARIABLE(double, DEM_RADIUS) KRATOS_CREATE_VARIABLE(bool, DEM_GENERATED) KRATOS_CREATE_VARIABLE(bool, INACTIVE_NODE) KRATOS_CREATE_VARIABLE(int, NUMBER_OF_ACTIVE_ELEMENTS) KRATOS_CREATE_VARIABLE(bool, NODAL_FORCE_APPLIED) KRATOS_CREATE_VARIABLE(double, NODAL_FORCE_X) KRATOS_CREATE_VARIABLE(double, NODAL_FORCE_Y) KRATOS_CREATE_VARIABLE(double, NODAL_FORCE_Z) KRATOS_CREATE_VARIABLE(Vector, NODAL_STRESS_VECTOR) KRATOS_CREATE_VARIABLE(double, EQUIVALENT_NODAL_STRESS) KRATOS_CREATE_VARIABLE(double, COHESION) KRATOS_CREATE_3D_VARIABLE_WITH_COMPONENTS(EQUIVALENT_NODAL_STRESS_GRADIENT) KRATOS_CREATE_3D_VARIABLE_WITH_COMPONENTS(AUXILIAR_GRADIENT) KRATOS_CREATE_VARIABLE(Matrix, STRAIN_TENSOR); KRATOS_CREATE_VARIABLE(Matrix, STRESS_TENSOR); KRATOS_CREATE_VARIABLE(Matrix, STRESS_TENSOR_INTEGRATED); // Composite KRATOS_CREATE_VARIABLE(Matrix, CONCRETE_STRESS_TENSOR); KRATOS_CREATE_VARIABLE(Matrix, STEEL_STRESS_TENSOR); KRATOS_CREATE_VARIABLE(Vector, CONCRETE_STRESS_VECTOR); KRATOS_CREATE_VARIABLE(Vector, STEEL_STRESS_VECTOR); KRATOS_CREATE_VARIABLE(double,YOUNG_MODULUS_STEEL); KRATOS_CREATE_VARIABLE(double,DENSITY_STEEL); KRATOS_CREATE_VARIABLE(double,POISSON_RATIO_STEEL); KRATOS_CREATE_VARIABLE(double,STEEL_VOLUMETRIC_PART); KRATOS_CREATE_VARIABLE(Matrix,CONCRETE_STRESS_TENSOR_INTEGRATED); KRATOS_CREATE_VARIABLE(double,YIELD_STRESS_C_STEEL); KRATOS_CREATE_VARIABLE(double,YIELD_STRESS_T_STEEL); KRATOS_CREATE_VARIABLE(double,FRACTURE_ENERGY_STEEL); KRATOS_CREATE_VARIABLE(double,PLASTIC_DISSIPATION_CAPAP); KRATOS_CREATE_VARIABLE(double,EQUIVALENT_STRESS_VM); KRATOS_CREATE_VARIABLE(int,HARDENING_LAW); KRATOS_CREATE_VARIABLE(double,MAXIMUM_STRESS); KRATOS_CREATE_VARIABLE(double,MAXIMUM_STRESS_POSITION); KRATOS_CREATE_VARIABLE(bool, IS_TAKEN) KRATOS_CREATE_VARIABLE(int, PRESSURE_ID) KRATOS_CREATE_3D_VARIABLE_WITH_COMPONENTS(LINE_LOAD); KRATOS_CREATE_3D_VARIABLE_WITH_COMPONENTS(SURFACE_LOAD); }
43.593407
77
0.82178
[ "vector" ]
58f3cf9a72ff8b9f92ef100f7656d0215c723ea7
9,539
cpp
C++
src/extensions/javascript/extractor.cpp
tinganho/lya
d956220da76d5658e8e2c0654db2068427463c60
[ "Apache-2.0" ]
1
2020-06-04T06:57:31.000Z
2020-06-04T06:57:31.000Z
src/extensions/javascript/extractor.cpp
tinganho/lya
d956220da76d5658e8e2c0654db2068427463c60
[ "Apache-2.0" ]
6
2018-01-05T02:55:59.000Z
2018-01-09T03:29:55.000Z
src/extensions/javascript/extractor.cpp
tinganho/lya
d956220da76d5658e8e2c0654db2068427463c60
[ "Apache-2.0" ]
null
null
null
#include "extractor.h" #include <tuple> #include <libxml++/libxml++.h> #include <libxml++/parsers/saxparser.h> #include "types.h" #include "token_scanner.h" #include "diagnostics.h" #include "utils.h" using namespace std; using namespace Lya::lib::types; using namespace Lya::lib::utils; using namespace Lya::javascript_extension::diagnostics; namespace Lya::javascript_extension { const vector<Glib::ustring> types = { "string", "number", "Date" }; JavaScriptLocalizationExtractor::JavaScriptLocalizationExtractor( const string& _file, const vector<Glib::ustring>& function_names, JavaScriptLanguage _language): scanner(read_file(_file)), t(Token::None), language(_language), function_names(function_names) { } tuple<vector<LocalizationLocation>, vector<::types::Diagnostic>> JavaScriptLocalizationExtractor::extract(uint64_t start_line) { vector<LocalizationLocation> localizations; while (true) { Token t = next_token(); if (t == Token::EndOfFile) { break; } switch (t) { case Token::Identifier: { Glib::ustring accessor; SpanLocation start_location = scanner.get_token_location(); bool success = try_scan_localization_function_accessor(get_value(), accessor); if (success && scan_expected(Token::Dot)) { if (scan_expected(Token::Identifier)) { Glib::ustring localization_id = get_value(); auto params = scan_parameter_list(); if (!has_diagnostics) { bool ok = get<1>(params); if (!ok) { continue; } LocalizationLocation l { localization_id, get<vector<Parameter>>(params), SpanLocation { start_location.line, start_location.column, scanner.position - start_location.position } }; localizations.push_back(l); } } } break; } case Token::SlashAsterix: scan_multiline_comment(); break; case Token::EndOfFile: goto return_statement; default:; } } return_statement: if (has_diagnostics) { return make_tuple(vector<LocalizationLocation> {}, diagnostics); } return make_tuple(localizations, diagnostics); } void JavaScriptLocalizationExtractor::scan_multiline_comment() { while (true) { Token t = next_token(); switch (t) { case Token::AsterixSlash: case Token::EndOfFile: goto outer; default:; } } outer:; } tuple<vector<Parameter>, bool> JavaScriptLocalizationExtractor::scan_parameter_list() { vector<Parameter> params; bool ok = true; string captured_type; if (scan_expected(Token::OpenParen)) { while (true) { Token t = next_token(true, true); switch (t) { case Token::Identifier: { if (language == JavaScriptLanguage::TypeScript) { add_diagnostic(D::You_must_provide_a_type_comment_for_the_argument_0, get_value()); ok = false; break; } string value = get_value(); if (value == "null" || value == "undefined" || value == "true" || value == "false") { add_diagnostic(D::Argument_must_be_a_variable_or_defined_by_a_preceding_comment); ok = false; break; } Token peek = peek_next_token(true, true); if (peek != Token::Comma && peek != Token::CloseParen) { scan_invalid_argument(); ok = false; break; } Parameter p { value, false }; params.push_back(p); break; } case Token::SlashAsterix: { bool scanned_ok; IdentifierType identifier_type; tie(identifier_type, scanned_ok) = scan_type_and_or_identifier(); if (!scanned_ok) { ok = false; break; } if (!scan_expected(Token::AsterixSlash)) { ok = false; break; } string identifier; if (identifier_type.identifier != nullptr) { if (!scan_expected(Token::Identifier)) { ok = false; break; } identifier = get_value(); } else { identifier = *identifier_type.identifier; } Parameter p { identifier, false, *identifier_type.type }; params.push_back(p); break; } case Token::String: scan_invalid_argument(); ok = false; break; case Token::EndOfFile: add_diagnostic(D::Unexpected_end_of_file); goto return_statement; case Token::InvalidArgument: ok = false; add_diagnostic(D::Argument_must_be_a_variable_or_defined_by_a_preceding_comment); break; case Token::CloseParen: goto return_statement; case Token::Comma: break; default: ok = false; add_diagnostic(D::Argument_must_be_a_variable_or_defined_by_a_preceding_comment); } } } return_statement: return make_tuple(params, ok); } void JavaScriptLocalizationExtractor::scan_invalid_argument() { int start_position = scanner.start_position; SpanLocation location = scanner.get_token_location(); Token t = next_token(); if (t == Token::OpenParen) { int open_parens = 0; while (true) { if (t == Token::EndOfFile) { break; } switch (t) { case Token::OpenParen: open_parens++; break; case Token::CloseParen: if (--open_parens == 0) { goto outer; } break; default:; } t = next_token(); } } else { while (true) { switch (t) { case Token::EndOfFile: case Token::Comma: case Token::CloseParen: scanner.decrement_position(); goto outer; default:; } t = next_token(); } } outer: location.length = scanner.position - start_position; diagnostics.push_back(create_diagnostic(location, D::Argument_must_be_a_variable_or_defined_by_a_preceding_comment)); } bool JavaScriptLocalizationExtractor::is_localization_function_name(const Glib::ustring &function_name) { for (const Glib::ustring& fn : function_names) { if (function_name == fn) { return true; } } return false; } bool JavaScriptLocalizationExtractor::try_scan_localization_function_accessor( const Glib::ustring& accessor, Glib::ustring& localization_function_name_placeholder ) { scanner.save(); if (is_localization_function_name(accessor) && next_token() == Token::Dot) { localization_function_name_placeholder = accessor; scanner.revert(); return true; } if (next_token() == Token::Identifier) { return try_scan_localization_function_accessor( accessor + "." + get_value(), localization_function_name_placeholder); } scanner.revert(); return false; } bool JavaScriptLocalizationExtractor::scan_expected(const Token& expected_token) { Token current_token = next_token(); if (current_token == expected_token) { return true; } add_diagnostic(D::Expected_0_but_got_1, token_enum_to_string.find(current_token)->second, token_enum_to_string.find(expected_token)->second); return false; } tuple<IdentifierType, bool> JavaScriptLocalizationExtractor::scan_type_and_or_identifier() { return scan_type_and_or_identifier(false); } tuple<IdentifierType, bool> JavaScriptLocalizationExtractor::scan_type_and_or_identifier(bool expect_type) { scan_expected(Token::Identifier); Glib::ustring type = get_value(); if (is_of_supported_type(type)) { if (peek_next_token() == Token::OpenBracket) { next_token(); scan_expected(Token::CloseBracket); type += "[]"; } IdentifierType identifier_type { make_shared<Glib::ustring>(type), nullptr }; return make_tuple(identifier_type, true); } else if (!expect_type && peek_next_token() == Token::Colon) { next_token(); return scan_type_and_or_identifier(/*expect_type*/ true); } add_diagnostic(D::Unknown_type_definition_0, type); return make_tuple(IdentifierType {}, false); } bool JavaScriptLocalizationExtractor::is_of_supported_type(const Glib::ustring& type) { for (const Glib::ustring& t : types) { if (t == type) { return true; } } return false; } Token JavaScriptLocalizationExtractor::next_token() { return t = scanner.next_token(false, false); } Token JavaScriptLocalizationExtractor::next_token(bool skip_whitespace, bool in_parameter_position) { return t = scanner.next_token(skip_whitespace, in_parameter_position); } Token JavaScriptLocalizationExtractor::peek_next_token() { return peek_next_token(false, false); } Token JavaScriptLocalizationExtractor::peek_next_token(bool skip_whitespace, bool in_parameter_position) { scanner.save(); const Token t = next_token(skip_whitespace, in_parameter_position); scanner.revert(); return t; } Glib::ustring JavaScriptLocalizationExtractor::get_value() const { return scanner.get_token_value(); } SpanLocation JavaScriptLocalizationExtractor::get_token_location() const { return scanner.get_token_location(); }; } // Lya::JavaScriptExtension
28.645646
127
0.631303
[ "vector" ]
58f40babf0502c2f066fa2b1660e11deec8525ac
1,729
cpp
C++
Source/Simulation/Simulation.cpp
Adelost/AberrantEngine
1282bfd1aaae6b197253ab6c2a1e7878e84ac769
[ "CC-BY-4.0" ]
null
null
null
Source/Simulation/Simulation.cpp
Adelost/AberrantEngine
1282bfd1aaae6b197253ab6c2a1e7878e84ac769
[ "CC-BY-4.0" ]
null
null
null
Source/Simulation/Simulation.cpp
Adelost/AberrantEngine
1282bfd1aaae6b197253ab6c2a1e7878e84ac769
[ "CC-BY-4.0" ]
null
null
null
#include "Simulation.h" //#include <Engine/Engine.h> #include <Components/Test.h> #include <Utils/Console.h> #include <Components/Input.h> //#include <Utils/Array.h> //#include <vector> Simulation::Simulation() { ////Component::Graphic::initClass(); //Component::Apple::initClass(); //Component::Banana::initClass(); //Component::Citrus::initClass(); /*Entity* e; e = Entity::create(); auto cApple = Component::Apple::create(e); int size = sizeof(Component::Apple); Component::Banana::create(e); Component::Citrus::create(e); e = Entity::create(); Component::Banana::create(e); Component::Citrus::create(e); Component::Input input; input.button("Forward");*/ //sys::TimeSystem::Time.start(); } void Simulation::update() { // Calculate delta time sys::Time.update(); //sys::Time.delta(); //sys::Time.delta(); //sys::Time.delta(); Array<int> foo; //System::GL.draw(); //System::GUI. //System::Input.setButton(); //Component::Input input; //Component::Input; //System::Input.delta(); //ecs::_Time.tick(); //ecs::Time time; //Component::Alpha a(1); ////System::input //for (auto cApple : Component::Apple::iterator) //{ // int id = cApple->entityId(); // int size = sizeof(cApple); // auto cBanana = Component::Banana::get(id); // if (!cBanana) // continue; // auto cCitrus = Component::Citrus::get(id); // if (!cCitrus) // continue; //} //for (auto cGraphic : Component::Graphic::iterator) //{ // Component::Transform* cTransform = cGraphic->cTransform.get(); // //int id = cGraphic->entityId(); //} } //System::Input; //System::Camera //System::Translation; //System::Offset; //System::Lookat; //System::Animation; //System::Sound; //System::Graphic;
17.464646
66
0.640254
[ "vector", "transform" ]
58f65f9a82b97421527b1af0ba9da0f9e0181f1c
2,563
hpp
C++
src/Huffman.hpp
uchiiii/CompactDataStructure
404cd1a2ac9d5b29eb39b1d9bfac207f49da5c49
[ "MIT" ]
6
2020-06-20T13:42:48.000Z
2021-06-14T15:59:06.000Z
src/Huffman.hpp
uchiiii/CompactDataStructure
404cd1a2ac9d5b29eb39b1d9bfac207f49da5c49
[ "MIT" ]
2
2020-08-05T06:00:21.000Z
2020-08-05T06:01:03.000Z
src/Huffman.hpp
uchiiii/CompactDataStructure
404cd1a2ac9d5b29eb39b1d9bfac207f49da5c49
[ "MIT" ]
null
null
null
#ifndef Huffman_hpp #define Huffman_hpp #include<unordered_map> #include<queue> #include<iostream> #include<vector> #include<string> using namespace std; struct Huffman { unordered_map<char, string> mp; void build(unordered_map<char,int> mp) { auto c = [](node *l, node *r) { return l->val > r->val;}; priority_queue<node*, vector<node*>, decltype(c)> que(c); for(auto &[key, cnt]:mp) { que.push(new node(key, cnt)); } while(que.size() != 1) { node* left = que.top(); que.pop(); node* right = que.top(); que.pop(); node* par = new node('$', left->val + right->val); par->left = left; par->right = right; que.push(par); } root = que.top(); que.pop(); search(root); } void build(vector<char> codes, vector<int> cnt) { auto c = [](node *l, node *r) { return l->val > r->val;}; priority_queue<node*, vector<node*>, decltype(c)> que(c); for(int i = 0; i <= (int)codes.size()-1; i++) { que.push(new node(codes[i], cnt[i])); } while(que.size() != 1) { node* left = que.top(); que.pop(); node* right = que.top(); que.pop(); node* par = new node('$', left->val + right->val); par->left = left; par->right = right; que.push(par); } root = que.top(); que.pop(); search(root); } string encode(string s) { string ans = ""; for(int i=0; i<s.size(); i++) { ans += mp[s[i]]; } return ans; } string decode(string v) { node* cur = root; string ans = ""; for(int i=0; i<v.size(); i++) { if(v[i]=='0') cur = cur->left; else cur = cur->right; if(cur->left == NULL and cur->right == NULL) { ans += cur->code; cur = root; } } return ans; } private: struct node { int val; char code; node *left, *right; node(char c, int v) { val = v; code = c; left = right = NULL; } }; node* root; void search(node* nd, string s="") { if(nd->left == NULL and nd->right == NULL) { mp[nd->code] = s; return; } if(nd->left != NULL) { search(nd->left, s + "0"); } if(nd->right != NULL){ search(nd->right, s + "1"); } } }; #endif
25.888889
65
0.446352
[ "vector" ]
58f6bfe0b936528e65e1e55a2b4d94cadabce35e
4,887
cpp
C++
middleware/service/source/manager/api/state.cpp
casualcore/casual
047a4eaabbba52ad3ce63dc698a9325ad5fcec6d
[ "MIT" ]
null
null
null
middleware/service/source/manager/api/state.cpp
casualcore/casual
047a4eaabbba52ad3ce63dc698a9325ad5fcec6d
[ "MIT" ]
null
null
null
middleware/service/source/manager/api/state.cpp
casualcore/casual
047a4eaabbba52ad3ce63dc698a9325ad5fcec6d
[ "MIT" ]
1
2022-02-21T18:30:25.000Z
2022-02-21T18:30:25.000Z
//! //! Copyright (c) 2019, The casual project //! //! This software is licensed under the MIT license, https://opensource.org/licenses/MIT //! #include "casual/service/manager/api/state.h" #include "service/manager/admin/api.h" #include "common/algorithm.h" namespace casual { using namespace common; namespace service { namespace manager { namespace api { inline namespace v1 { namespace local { namespace { namespace transform { auto state( admin::model::State state) { Model result; auto transform_service = []( auto& service) { model::Service result; result.name = service.name; result.category = service.category; if( service.execution.timeout.duration) result.timeout = service.execution.timeout.duration.value(); auto tranform_mode = []( auto mode) { using Enum = decltype( mode); switch( mode) { case Enum::automatic: return model::Service::Transaction::automatic; case Enum::join: return model::Service::Transaction::join; case Enum::atomic: return model::Service::Transaction::atomic; case Enum::none: return model::Service::Transaction::none; case Enum::branch: return model::Service::Transaction::branch; } assert( ! "unknown transaction mode"); }; result.transaction = tranform_mode( service.transaction); auto transform_metric = []( auto& metric) { model::service::Metric result; auto transform_sub = []( auto metric) { model::Metric result; result.count = metric.count; result.total = metric.total; result.limit.min = metric.limit.min; result.limit.max = metric.limit.max; return result; }; result.invoked = transform_sub( metric.invoked); result.pending = transform_sub( metric.pending); result.last = metric.last; result.remote = metric.remote; return result; }; result.metric = transform_metric( service.metric); auto tranform_sequential = []( auto& instance) { model::service::instance::Sequential result; result.pid = instance.pid.value(); return result; }; algorithm::transform( service.instances.sequential, result.instances.sequential, tranform_sequential); auto tranform_concurrent = []( auto& instance) { model::service::instance::Concurrent result; result.pid = instance.pid.value(); result.hops = instance.hops; return result; }; algorithm::transform( service.instances.concurrent, result.instances.concurrent, tranform_concurrent); return result; }; algorithm::transform( state.services, result.services, transform_service); return result; } } // transform } // <unnamed> } // local Model state() { return local::transform::state( admin::api::state()); } } // v1 } // api } // manager } // service } // casual
39.731707
132
0.388991
[ "model", "transform" ]
58faab09a44f1edb6ea759eb0d961f06efc1b01d
707
cpp
C++
leetcode/0435_Non-overlapping_Intervals/result.cpp
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
leetcode/0435_Non-overlapping_Intervals/result.cpp
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
leetcode/0435_Non-overlapping_Intervals/result.cpp
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
/** * Copyright (C) 2021 All rights reserved. * * FileName :result.cpp * Author :C.K * Email :theck17@163.com * DateTime :2021-09-28 22:28:44 * Description : */ using namespace std; bool comp(vector<int> &a,vector<int> &b) { return a[1]<b[1]; } class Solution { public: int eraseOverlapIntervals(vector<vector<int>>& intervals) { int ans=-1; if(intervals.size()==0) return 0; sort(intervals.begin(),intervals.end(),comp); vector<int> prev= intervals[0]; for(vector<int> i: intervals) { if(prev[1]>i[0]) { ans++; }else prev=i; } return ans; } }; int main(){ return 0; }
20.794118
60
0.540311
[ "vector" ]
450bc6b80ecf9d30deecd2fe93b399cc4e93fded
22,063
cpp
C++
src/data/datasets/datasetmesh.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
5
2016-03-17T07:02:11.000Z
2021-12-12T14:43:58.000Z
src/data/datasets/datasetmesh.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
null
null
null
src/data/datasets/datasetmesh.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
3
2015-10-29T15:21:01.000Z
2020-11-25T09:41:21.000Z
/* * datasetmesh.cpp * * Created on: Jul 19, 2012 * @author Ralph Schurade */ #include "datasetmesh.h" #include "datasetscalar.h" #include "../models.h" #include "../vptr.h" #include "../mesh/trianglemesh2.h" #include "../../gui/gl/glfunctions.h" #include "../../gui/gl/colormapfunctions.h" #include "../../gui/gl/meshrenderer.h" #include <QFile> #include <QFileDialog> DatasetMesh::DatasetMesh( TriangleMesh2* mesh, QDir fileName ) : Dataset( fileName, Fn::DatasetType::MESH_BINARY ), m_renderer( 0 ) { m_mesh.push_back( mesh ); initProperties(); finalizeProperties(); } DatasetMesh::DatasetMesh( QDir fileName, Fn::DatasetType type ) : Dataset( fileName, type ), m_renderer( 0 ) { initProperties(); } DatasetMesh::~DatasetMesh() { } void DatasetMesh::initProperties() { float min = 0.0; float max = 1.0; m_properties["maingl"].createRadioGroup( Fn::Property::D_COLORMODE, { "per mesh", "mri", "per vertex", "vertex data" }, 0, "general" ); m_properties["maingl"].createBool( Fn::Property::D_INTERPOLATION, true, "general" ); m_properties["maingl"].createInt( Fn::Property::D_COLORMAP, 1, "general" ); m_properties["maingl"].createFloat( Fn::Property::D_SELECTED_MIN, min, min, max, "general" ); m_properties["maingl"].createFloat( Fn::Property::D_SELECTED_MAX, max, min, max, "general" ); m_properties["maingl"].createFloat( Fn::Property::D_LOWER_THRESHOLD, min + ( max - min ) / 1000., min, max, "general" ); m_properties["maingl"].createFloat( Fn::Property::D_UPPER_THRESHOLD, max, min, max, "general" ); m_properties["maingl"].createColor( Fn::Property::D_COLOR, QColor( 255, 255, 255 ), "general" ); m_properties["maingl"].createFloat( Fn::Property::D_ALPHA, 1.f, 0.01f, 1.f, "general" ); m_properties["maingl"].createButton( Fn::Property::D_COPY_COLORS, "general" ); connect( m_properties["maingl"].getProperty( Fn::Property::D_COPY_COLORS ), SIGNAL( valueChanged( QVariant ) ), this, SLOT( slotCopyColors() ) ); m_properties["maingl"].createButton( Fn::Property::D_COPY_VALUES, "general" ); connect( m_properties["maingl"].getProperty( Fn::Property::D_COPY_VALUES ), SIGNAL( valueChanged( QVariant ) ), this, SLOT( slotCopyValues() ) ); GLFunctions::createColormapBarProps( m_properties["maingl"] ); m_properties["maingl"].createRadioGroup( Fn::Property::D_PAINTMODE, { "off", "paint", "paint values" }, 0, "paint" ); m_properties["maingl"].createFloat( Fn::Property::D_PAINTSIZE, 20.f, 1.f, 1000.f, "paint" ); m_properties["maingl"].createColor( Fn::Property::D_PAINTCOLOR, QColor( 255, 0, 0 ), "paint" ); m_properties["maingl"].createFloat( Fn::Property::D_PAINTVALUE, 0.5f, -1.0f, 1.0f, "paint" ); m_properties["maingl"].createFloat( Fn::Property::D_MIN, min ); m_properties["maingl"].createFloat( Fn::Property::D_MAX, max ); connect( m_properties["maingl"].getProperty( Fn::Property::D_SELECTED_MIN ), SIGNAL( valueChanged( QVariant ) ), m_properties["maingl"].getProperty( Fn::Property::D_LOWER_THRESHOLD ), SLOT( setMax( QVariant ) ) ); connect( m_properties["maingl"].getProperty( Fn::Property::D_SELECTED_MAX ), SIGNAL( valueChanged( QVariant ) ), m_properties["maingl"].getProperty( Fn::Property::D_UPPER_THRESHOLD ), SLOT( setMin( QVariant ) ) ); connect( m_properties["maingl"].getProperty( Fn::Property::D_PAINTMODE ), SIGNAL( valueChanged( QVariant ) ), this, SLOT( paintModeChanged( QVariant ) ) ); m_properties["maingl"].createBool( Fn::Property::D_RENDER_WIREFRAME, false, "special" ); m_properties["maingl"].createBool( Fn::Property::D_MESH_CUT_LOWER_X, false, "special" ); m_properties["maingl"].createBool( Fn::Property::D_MESH_CUT_LOWER_Y, false, "special" ); m_properties["maingl"].createBool( Fn::Property::D_MESH_CUT_LOWER_Z, false, "special" ); m_properties["maingl"].createBool( Fn::Property::D_MESH_CUT_HIGHER_X, false, "special" ); m_properties["maingl"].createBool( Fn::Property::D_MESH_CUT_HIGHER_Y, false, "special" ); m_properties["maingl"].createBool( Fn::Property::D_MESH_CUT_HIGHER_Z, false, "special" ); m_properties["maingl"].createFloat( Fn::Property::D_ADJUST_X, 0.0f, -500.0f, 500.0f, "special" ); m_properties["maingl"].createFloat( Fn::Property::D_ADJUST_Y, 0.0f, -500.0f, 500.0f, "special" ); m_properties["maingl"].createFloat( Fn::Property::D_ADJUST_Z, 0.0f, -500.0f, 500.0f, "special" ); m_properties["maingl"].createFloat( Fn::Property::D_ROTATE_X, 0.0f, 0.0f, 360.0f, "special" ); m_properties["maingl"].createFloat( Fn::Property::D_ROTATE_Y, 0.0f, 0.0f, 360.0f, "special" ); m_properties["maingl"].createFloat( Fn::Property::D_ROTATE_Z, 0.0f, 0.0f, 360.0f, "special" ); m_properties["maingl"].createFloat( Fn::Property::D_SCALE_X, 1.0f, 0.0f, 10.0f, "special" ); m_properties["maingl"].createFloat( Fn::Property::D_SCALE_Y, 1.0f, 0.0f, 10.0f, "special" ); m_properties["maingl"].createFloat( Fn::Property::D_SCALE_Z, 1.0f, 0.0f, 10.0f, "special" ); m_properties["maingl"].createButton( Fn::Property::D_MESH_MAKE_PERMANENT, "special" ); connect( m_properties["maingl"].getProperty( Fn::Property::D_MESH_MAKE_PERMANENT ), SIGNAL( valueChanged( QVariant ) ), this, SLOT( makePermanent() ) ); m_properties["maingl"].createBool( Fn::Property::D_LIGHT_SWITCH, true, "light" ); m_properties["maingl"].createFloat( Fn::Property::D_LIGHT_AMBIENT, 0.3f, 0.0f, 1.0f, "light" ); m_properties["maingl"].createFloat( Fn::Property::D_LIGHT_DIFFUSE, 0.6f, 0.0f, 1.0f, "light" ); m_properties["maingl"].createFloat( Fn::Property::D_LIGHT_SPECULAR, 0.5f, 0.0f, 1.0f, "light" ); m_properties["maingl"].createFloat( Fn::Property::D_MATERIAL_AMBIENT, 0.5f, 0.0f, 10.0f, "light" ); m_properties["maingl"].createFloat( Fn::Property::D_MATERIAL_DIFFUSE, 0.8f, 0.0f, 10.0f, "light" ); m_properties["maingl"].createFloat( Fn::Property::D_MATERIAL_SPECULAR, 0.61f, 0.0f, 10.0f, "light" ); m_properties["maingl"].createFloat( Fn::Property::D_MATERIAL_SHININESS, 1.0f, 0.0f, 200.0f, "light" ); m_properties["maingl"].createInt( Fn::Property::D_MESH_NUM_VERTEX, 0 ); m_properties["maingl"].createInt( Fn::Property::D_MESH_NUM_TRIANGLES, 0 ); m_properties["maingl"].createInt( Fn::Property::D_GLYPHSET_PICKED_ID, 0 ); m_properties["maingl"].createInt( Fn::Property::D_START_INDEX, 0 ); m_properties["maingl"].createInt( Fn::Property::D_END_INDEX, 0 ); if( m_mesh.size() > 0 ) { m_properties["maingl"].set( Fn::Property::D_MESH_NUM_VERTEX, m_mesh[0]->numVerts() ); m_properties["maingl"].set( Fn::Property::D_MESH_NUM_TRIANGLES, m_mesh[0]->numTris() ); m_properties["maingl"].set( Fn::Property::D_START_INDEX, 0 ); m_properties["maingl"].set( Fn::Property::D_END_INDEX, m_mesh[0]->numTris() ); } m_properties["maingl"].createList( Fn::Property::D_USE_TRANSFORM, { "user defined", "qform", "sform", "qform inverted", "sform inverted" }, 0, "transform" ); connect( m_properties["maingl"].getProperty( Fn::Property::D_USE_TRANSFORM ), SIGNAL( valueChanged( QVariant ) ), this, SLOT( transformChanged( QVariant ) ) ); m_properties["maingl"].createMatrix( Fn::Property::D_TRANSFORM, m_transform, "transform" ); m_properties["maingl"].createButton( Fn::Property::D_APPLY_TRANSFORM, "transform" ); connect( m_properties["maingl"].getProperty( Fn::Property::D_APPLY_TRANSFORM ), SIGNAL( valueChanged( QVariant ) ), this, SLOT( applyTransform() ) ); m_properties["maingl"].createBool( Fn::Property::D_INVERT_VERTEX_ORDER, false, "transform" ); transformChanged( 0 ); } void DatasetMesh::finalizeProperties() { PropertyGroup props2( m_properties["maingl"] ); m_properties.insert( "maingl2", props2 ); m_properties["maingl2"].getProperty( Fn::Property::D_ACTIVE )->setPropertyTab( "general" ); connect( m_properties["maingl2"].getProperty( Fn::Property::D_SELECTED_MIN ), SIGNAL( valueChanged( QVariant ) ), m_properties["maingl2"].getProperty( Fn::Property::D_LOWER_THRESHOLD ), SLOT( setMax( QVariant ) ) ); connect( m_properties["maingl2"].getProperty( Fn::Property::D_SELECTED_MAX ), SIGNAL( valueChanged( QVariant ) ), m_properties["maingl2"].getProperty( Fn::Property::D_UPPER_THRESHOLD ), SLOT( setMin( QVariant ) ) ); connect( m_properties["maingl2"].getProperty( Fn::Property::D_PAINTMODE ), SIGNAL( valueChanged( QVariant ) ), this, SLOT( paintModeChanged( QVariant ) ) ); } void DatasetMesh::setProperties() { m_properties["maingl"].createList( Fn::Property::D_SURFACE, m_displayList, 0, "general" ); //m_properties["maingl2"].create( Fn::Property::D_SURFACE, m_displayList, 0, "general" ); if( m_mesh.size() > 0 ) { m_properties["maingl"].set( Fn::Property::D_START_INDEX, 0 ); m_properties["maingl"].set( Fn::Property::D_END_INDEX, m_mesh[0]->numTris() ); } } /***************************************************************************************************************************************************** * * adds TriangleMesh to the list of meshes only if those meshes have the exact same number of vertexes * ****************************************************************************************************************************************************/ void DatasetMesh::addMesh( TriangleMesh2* tm, QString displayString ) { if ( m_mesh.size() > 0 ) { unsigned int numVerts = m_mesh[0]->numVerts(); if ( numVerts != tm->numVerts() ) { return; } } m_mesh.push_back( tm ); m_displayList.push_back( displayString ); m_properties["maingl"].set( Fn::Property::D_START_INDEX, 0 ); m_properties["maingl"].set( Fn::Property::D_END_INDEX, m_mesh[0]->numTris() ); } int DatasetMesh::getNumberOfMeshes() { return m_mesh.size(); } TriangleMesh2* DatasetMesh::getMesh() { if ( m_mesh.size() > 0 ) { return m_mesh[0]; } return 0; } TriangleMesh2* DatasetMesh::getMesh( int id ) { if ( (int)m_mesh.size() > id ) { return m_mesh[id]; } return 0; } TriangleMesh2* DatasetMesh::getMesh( QString target ) { int n = properties( target ).get( Fn::Property::D_SURFACE ).toInt(); return m_mesh[n]; } void DatasetMesh::draw( QMatrix4x4 pMatrix, QMatrix4x4 mvMatrix, int width, int height, int renderMode, QString target ) { if ( !properties( target ).get( Fn::Property::D_ACTIVE ).toBool() ) { return; } if ( m_resetRenderer ) { delete m_renderer; m_renderer = 0; m_resetRenderer = false; } if ( m_renderer == 0 ) { m_renderer = new MeshRenderer( getMesh(target) ); m_renderer->init(); } m_renderer->setMesh( getMesh(target) ); m_renderer->draw( pMatrix, mvMatrix, width, height, renderMode, properties( target ) ); GLFunctions::drawColormapBar( properties( target ), width, height, renderMode ); } bool DatasetMesh::mousePick( int pickId, QVector3D pos, Qt::KeyboardModifiers modifiers, QString target ) { int paintMode = m_properties[target].get( Fn::Property::D_PAINTMODE ).toInt(); if ( pickId == 0 || paintMode == 0 || !( modifiers & Qt::ControlModifier ) ) { return false; } QColor color; if ( ( modifiers & Qt::ControlModifier ) && !( modifiers & Qt::ShiftModifier ) ) { color = m_properties["maingl"].get( Fn::Property::D_PAINTCOLOR ).value<QColor>(); } else if ( ( modifiers & Qt::ControlModifier ) && ( modifiers & Qt::ShiftModifier ) ) { color = m_properties["maingl"].get( Fn::Property::D_COLOR ).value<QColor>(); } else { return false; } std::vector<unsigned int> picked = getMesh( target )->pick( pos, m_properties["maingl"].get( Fn::Property::D_PAINTSIZE ).toFloat() ); if ( picked.size() > 0 ) { m_renderer->beginUpdateColor(); for ( unsigned int i = 0; i < picked.size(); ++i ) { m_renderer->updateColor( picked[i], color.redF(), color.greenF(), color.blueF(), 1.0 ); for ( unsigned int m = 0; m < m_mesh.size(); ++m ) { if ( paintMode == 1 ) //paint color { m_mesh[m]->setVertexColor( picked[i], color ); } else if ( paintMode == 2 ) //paint values { //float value = m_mesh[0]->getVertexData( picked[i] ) + m_properties[target]->get( Fn::Property::D_PAINTVALUE ).toFloat(); float value = m_properties[target].get( Fn::Property::D_PAINTVALUE ).toFloat(); if ( value < 0.0 ) { value = 0.0; } if ( value > 1.0 ) { value = 1.0; } if ( ( modifiers & Qt::ShiftModifier ) ) { value = 0.0; } m_mesh[m]->setVertexData( picked[i], value ); } } } m_renderer->endUpdateColor(); return true; } return false; } void DatasetMesh::paintModeChanged( QVariant mode ) { if ( mode.toInt() == 1 ) { m_properties["maingl"].set( Fn::Property::D_COLORMODE, 2 ); } if ( mode.toInt() == 2 ) { m_properties["maingl"].set( Fn::Property::D_COLORMODE, 3 ); } } void DatasetMesh::makePermanent() { QMatrix4x4 mMatrix; mMatrix.setToIdentity(); if( m_properties["maingl"].contains( Fn::Property::D_ROTATE_X ) ) { mMatrix.rotate( -m_properties["maingl"].get( Fn::Property::D_ROTATE_X ).toFloat(), 1.0, 0.0, 0.0 ); mMatrix.rotate( -m_properties["maingl"].get( Fn::Property::D_ROTATE_Y ).toFloat(), 0.0, 1.0, 0.0 ); mMatrix.rotate( -m_properties["maingl"].get( Fn::Property::D_ROTATE_Z ).toFloat(), 0.0, 0.0, 1.0 ); mMatrix.scale( m_properties["maingl"].get( Fn::Property::D_SCALE_X ).toFloat(), m_properties["maingl"].get( Fn::Property::D_SCALE_Y ).toFloat(), m_properties["maingl"].get( Fn::Property::D_SCALE_Z ).toFloat() ); } int adjustX = m_properties["maingl"].get( Fn::Property::D_ADJUST_X ).toFloat(); int adjustY = m_properties["maingl"].get( Fn::Property::D_ADJUST_Y ).toFloat(); int adjustZ = m_properties["maingl"].get( Fn::Property::D_ADJUST_Z ).toFloat(); int numVerts = m_mesh[0]->numVerts(); for( int i = 0; i < numVerts; ++i ) { QVector3D vert = m_mesh[0]->getVertex( i ); vert = vert * mMatrix; vert.setX( vert.x() + adjustX ); vert.setY( vert.y() + adjustY ); vert.setZ( vert.z() + adjustZ ); m_mesh[0]->setVertex( i, vert ); } m_mesh[0]->finalize(); m_resetRenderer = true; m_properties["maingl"].set( Fn::Property::D_ROTATE_X, 0 ); m_properties["maingl"].set( Fn::Property::D_ROTATE_Y, 0 ); m_properties["maingl"].set( Fn::Property::D_ROTATE_Z, 0 ); m_properties["maingl"].set( Fn::Property::D_ADJUST_X, 0 ); m_properties["maingl"].set( Fn::Property::D_ADJUST_Y, 0 ); m_properties["maingl"].set( Fn::Property::D_ADJUST_Z, 0 ); m_properties["maingl"].set( Fn::Property::D_SCALE_X, 1 ); m_properties["maingl"].set( Fn::Property::D_SCALE_Y, 1 ); m_properties["maingl"].set( Fn::Property::D_SCALE_Z, 1 ); Models::d()->submit(); } QString DatasetMesh::getSaveFilter() { return QString( "Mesh binary (*.vtk);; Mesh ascii (*.asc);; Mesh 1D data (*.1D);; Mesh rgb data (*.rgb);; Mesh obj (*.obj);; Mesh VRML (*.wrl);; Mesh JSON (*.json);; all files (*.*)" ); } QString DatasetMesh::getDefaultSuffix() { return QString( "vtk" ); } void DatasetMesh::transformChanged( QVariant value ) { QMatrix4x4 qForm; QMatrix4x4 sForm; QList<Dataset*>dsl = Models::getDatasets( Fn::DatasetType::NIFTI_ANY ); if ( dsl.size() > 0 ) { qForm = dsl.first()->properties().get( Fn::Property::D_Q_FORM ).value<QMatrix4x4>(); sForm = dsl.first()->properties().get( Fn::Property::D_S_FORM ).value<QMatrix4x4>(); } m_properties["maingl"].getWidget( Fn::Property::D_TRANSFORM )->setEnabled( false ); switch ( value.toInt() ) { case 0: m_transform.setToIdentity(); m_properties["maingl"].getWidget( Fn::Property::D_TRANSFORM )->setEnabled( true ); break; case 1: m_transform = qForm; break; case 2: m_transform = sForm; break; case 3: m_transform = qForm.inverted(); break; case 4: m_transform = sForm.inverted(); break; default: m_transform.setToIdentity(); break; } m_properties["maingl"].set( Fn::Property::D_TRANSFORM, m_transform ); Models::d()->submit(); } void DatasetMesh::applyTransform() { m_transform = m_properties["maingl"].get( Fn::Property::D_TRANSFORM ).value<QMatrix4x4>(); int n = properties( "maingl" ).get( Fn::Property::D_SURFACE ).toInt(); TriangleMesh2* mesh = m_mesh[n]; m_transform = m_properties["maingl"].get( Fn::Property::D_TRANSFORM ).value<QMatrix4x4>(); for ( unsigned int i = 0; i < mesh->numVerts(); ++i ) { QVector3D vert = mesh->getVertex( i ); vert = m_transform * vert; mesh->setVertex( i, vert ); } mesh->finalize(); m_resetRenderer = true; transformChanged( 0 ); Models::d()->submit(); } void DatasetMesh::slotCopyColors() { int n = properties( "maingl" ).get( Fn::Property::D_SURFACE ).toInt(); TriangleMesh2* mesh = m_mesh[n]; if( m_properties["maingl"].get( Fn::Property::D_COLORMODE ).toInt() == 3 ) { QColor color; float selectedMin = properties( "maingl" ).get( Fn::Property::D_SELECTED_MIN ).toFloat(); float selectedMax = properties( "maingl" ).get( Fn::Property::D_SELECTED_MAX ).toFloat(); m_renderer->beginUpdateColor(); for ( unsigned int i = 0; i < mesh->numVerts(); ++i ) { ColormapBase cmap = ColormapFunctions::getColormap( properties( "maingl" ).get( Fn::Property::D_COLORMAP ).toInt() ); float value = ( mesh->getVertexData( i ) - selectedMin ) / ( selectedMax - selectedMin ); color = cmap.getColor( qMax( 0.0f, qMin( 1.0f, value ) ) ); mesh->setVertexColor( i, color ); } m_renderer->endUpdateColor(); } else { QList<QVariant>dsl = Models::d()->data( Models::d()->index( 0, (int)Fn::Property::D_DATASET_LIST ), Qt::DisplayRole ).toList(); QList<DatasetScalar*> texList; for ( int k = 0; k < dsl.size(); ++k ) { Dataset* ds = VPtr<Dataset>::asPtr( dsl[k] ); if ( ds->properties().get( Fn::Property::D_ACTIVE ).toBool() && ds->properties().get( Fn::Property::D_HAS_TEXTURE ).toBool() ) { texList.push_back( VPtr<DatasetScalar>::asPtr( dsl[k] ) ); if ( texList.size() == 5 ) { break; } } } if ( texList.empty() ) { return; } //TriangleMesh2* mesh = getMesh(); m_renderer->beginUpdateColor(); for ( unsigned int i = 0; i < mesh->numVerts(); ++i ) { QColor c = texList[0]->getColorAtPos( mesh->getVertex( i ) ); for ( int k = 1; k < texList.size(); ++k ) { QColor c2 = texList[k]->getColorAtPos( mesh->getVertex( i ) ); c.setRedF( ( 1.0 - c2.alphaF() ) * c.redF() + c2.alphaF() * c2.redF() ); c.setGreenF( ( 1.0 - c2.alphaF() ) * c.greenF() + c2.alphaF() * c2.greenF() ); c.setBlueF( ( 1.0 - c2.alphaF() ) * c.blueF() + c2.alphaF() * c2.blueF() ); } if ( c.redF() + c.greenF() + c.blueF() > 0 ) { mesh->setVertexColor( i, c ); } else { QColor col = m_properties["maingl"].get( Fn::Property::D_COLOR ).value<QColor>(); mesh->setVertexColor( i, col ); } } m_renderer->endUpdateColor(); } } void DatasetMesh::slotCopyValues() { int n = properties( "maingl" ).get( Fn::Property::D_SURFACE ).toInt(); TriangleMesh2* mesh = m_mesh[n]; QList<QVariant>dsl = Models::d()->data( Models::d()->index( 0, (int)Fn::Property::D_DATASET_LIST ), Qt::DisplayRole ).toList(); QList<Dataset*> texList = Models::getDatasets( Fn::DatasetType::NIFTI_SCALAR ); if ( texList.empty() ) { return; } float min = std::numeric_limits<float>::max(); float max = -std::numeric_limits<float>::max(); DatasetScalar* ds = dynamic_cast<DatasetScalar*>( texList[0] ); //TriangleMesh2* mesh = getMesh(); m_renderer->beginUpdateColor(); for ( unsigned int i = 0; i < mesh->numVerts(); ++i ) { float value = ds->getValueAtPos( mesh->getVertex( i ) ); min = qMin( value, min ); max = qMax( value, max ); mesh->setVertexData( i, value ); } m_renderer->endUpdateColor(); m_properties["maingl"].getProperty( Fn::Property::D_MIN )->setValue( min ); m_properties["maingl"].getProperty( Fn::Property::D_MAX )->setValue( max ); m_properties["maingl"].getProperty( Fn::Property::D_SELECTED_MIN )->setValue( min ); m_properties["maingl"].getProperty( Fn::Property::D_SELECTED_MAX )->setValue( max ); m_properties["maingl"].getProperty( Fn::Property::D_LOWER_THRESHOLD )->setValue( min ); m_properties["maingl"].getProperty( Fn::Property::D_UPPER_THRESHOLD )->setValue( max ); m_properties["maingl"].set( Fn::Property::D_COLORMODE, 3 ); }
39.610413
189
0.603318
[ "mesh", "vector", "transform" ]
4515e3800dccd54ca78846a38213ef17bb7610ee
1,885
cpp
C++
motioncorr_v2.1/src/SP++3/test/correlation_usefftw_test.cpp
cianfrocco-lab/Motion-correction
c77ee034bba2ef184837e070dde43f75d8a4e1e7
[ "MIT" ]
11
2015-12-21T19:47:53.000Z
2021-01-21T02:58:43.000Z
src/SP++3/test/correlation_usefftw_test.cpp
wjiang/motioncorr
14ed37d1cc72e55d1592e78e3dda758cd46a3698
[ "Naumen", "Condor-1.1", "MS-PL" ]
5
2016-05-24T10:55:18.000Z
2016-06-10T01:07:42.000Z
src/SP++3/test/correlation_usefftw_test.cpp
wjiang/motioncorr
14ed37d1cc72e55d1592e78e3dda758cd46a3698
[ "Naumen", "Condor-1.1", "MS-PL" ]
9
2016-04-26T10:14:20.000Z
2020-10-14T07:34:59.000Z
/***************************************************************************** * fastcorr_usefftw_test.cpp * * Fast correlation by using FFTW testing. * * Zhang Ming, 2010-10, Xi'an Jiaotong University. *****************************************************************************/ #define BOUNDS_CHECK #include <iostream> #include <iomanip> #include <correlation_usefftw.h> using namespace std; using namespace splab; typedef double Type; const int M = 3; const int N = 5; int main() { Vector<Type> xn( M ), yn( N ); for( int i=0; i<M; ++i ) xn[i] = i; for( int i=0; i<N; ++i ) yn[i] = i-N/2; cout << setiosflags(ios::fixed) << setprecision(4); cout << "xn: " << xn << endl; cout << "yn: " << yn << endl; // fast auto and cross correlation functions by using FFTW cout << "fast auto-correlation of xn: " << fastCorrFFTW(xn) << endl; cout << "fast biased auto-correlation of xn: " << fastCorrFFTW(xn,"biased") << endl; cout << "fast unbiased auto-correlation of xn: " << fastCorrFFTW(xn,"unbiased") << endl; cout << "fast cross-correlation of xn and yn: " << fastCorrFFTW(xn,yn) << endl; cout << "fast cross-correlation of yn and xn: " << fastCorrFFTW(yn,xn) << endl; cout << "fast biased cross-correlation of xn and yn: " << fastCorrFFTW(xn,yn,"biased") << endl; cout << "fast biased cross-correlation of yn and xn: " << fastCorrFFTW(yn,xn,"biased") << endl; cout << "fast unbiased cross-correlation of xn and yn: " << fastCorrFFTW(xn,yn,"unbiased") << endl; cout << "fast unbiased cross-correlation of yn and xn: " << fastCorrFFTW(yn,xn,"unbiased") << endl; return 0; }
29.453125
80
0.502387
[ "vector" ]
93236074e8b14603ca8e7a921a84fc26cd4e06a9
3,016
hpp
C++
examples/iban/iban.hpp
nlohmann/fuzzcover
d9d7dc7ed54c428c6dd6368b439eb406a39b9c76
[ "MIT" ]
21
2019-11-25T00:39:42.000Z
2022-03-26T11:30:01.000Z
examples/iban/iban.hpp
sthagen/fuzzcover
837407cdf5372f6473bc8aec9d357d8dc568d67c
[ "MIT" ]
null
null
null
examples/iban/iban.hpp
sthagen/fuzzcover
837407cdf5372f6473bc8aec9d357d8dc568d67c
[ "MIT" ]
3
2020-05-21T08:01:17.000Z
2020-09-17T19:31:08.000Z
#pragma once #include <string> #include <iostream> #include <map> #include <algorithm> #include <cctype> bool is_valid_iban( const std::string &ibanstring ) { static std::map<std::string, int> countrycodes { {"AL" , 28} , {"AD" , 24} , {"AT" , 20} , {"AZ" , 28 } , {"BE" , 16} , {"BH" , 22} , {"BA" , 20} , {"BR" , 29 } , {"BG" , 22} , {"CR" , 21} , {"HR" , 21} , {"CY" , 28 } , {"CZ" , 24} , {"DK" , 18} , {"DO" , 28} , {"EE" , 20 } , {"FO" , 18} , {"FI" , 18} , {"FR" , 27} , {"GE" , 22 } , {"DE" , 22} , {"GI" , 23} , {"GR" , 27} , {"GL" , 18 } , {"GT" , 28} , {"HU" , 28} , {"IS" , 26} , {"IE" , 22 } , {"IL" , 23} , {"IT" , 27} , {"KZ" , 20} , {"KW" , 30 } , {"LV" , 21} , {"LB" , 28} , {"LI" , 21} , {"LT" , 20 } , {"LU" , 20} , {"MK" , 19} , {"MT" , 31} , {"MR" , 27 } , {"MU" , 30} , {"MC" , 27} , {"MD" , 24} , {"ME" , 22 } , {"NL" , 18} , {"NO" , 15} , {"PK" , 24} , {"PS" , 29 } , {"PL" , 28} , {"PT" , 25} , {"RO" , 24} , {"SM" , 27 } , {"SA" , 24} , {"RS" , 22} , {"SK" , 24} , {"SI" , 19 } , {"ES" , 24} , {"SE" , 24} , {"CH" , 21} , {"TN" , 24 } , {"TR" , 26} , {"AE" , 23} , {"GB" , 22} , {"VG" , 24 } } ; std::string teststring( ibanstring ) ; std::remove_if(teststring.begin(), teststring.end(), [](const char c) { return c == ' '; }); if ( countrycodes.find( teststring.substr(0 , 2 )) == countrycodes.end( ) ) return false ; if ( teststring.length( ) != countrycodes[ teststring.substr( 0 , 2 ) ] ) return false ; if (!std::all_of(teststring.begin(), teststring.end(), [](const char c){ return std::isalnum(c); })) return false ; std::transform(teststring.begin(), teststring.end(), teststring.begin(), [](unsigned char c){ return std::toupper(c); }); //to_upper( teststring ) ; std::rotate(teststring.begin(), teststring.begin() + 4, teststring.end()); std::string numberstring ;//will contain the letter substitutions for (const auto& c : teststring) { if (std::isdigit(c)) numberstring += c ; if (std::isupper(c)) numberstring += std::to_string(static_cast<int>(c) - 55); } //implements a stepwise check for mod 97 in chunks of 9 at the first time // , then in chunks of seven prepended by the last mod 97 operation converted //to a string int segstart = 0 ; int step = 9 ; std::string prepended ; long number = 0 ; while ( segstart < numberstring.length( ) - step ) { number = std::stol( prepended + numberstring.substr( segstart , step ) ) ; int remainder = number % 97 ; prepended = std::to_string( remainder ) ; if ( remainder < 10 ) prepended = "0" + prepended ; segstart = segstart + step ; step = 7 ; } number = std::stol( prepended + numberstring.substr( segstart )) ; return ( number % 97 == 1 ) ; }
45.014925
125
0.477122
[ "transform" ]
9325191361d67f998d0400802037f767acc476e7
17,190
cpp
C++
mainapp/Classes/Games/ComprehensionTest/ComprehensionScene.cpp
JaagaLabs/GLEXP-Team-KitkitSchool
f94ea3e53bd05fdeb2a9edcc574bc054e575ecc0
[ "Apache-2.0" ]
45
2019-05-16T20:49:31.000Z
2021-11-05T21:40:54.000Z
mainapp/Classes/Games/ComprehensionTest/ComprehensionScene.cpp
rdsmarketing/GLEXP-Team-KitkitSchool
6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e
[ "Apache-2.0" ]
10
2019-05-17T13:38:22.000Z
2021-07-31T19:38:27.000Z
mainapp/Classes/Games/ComprehensionTest/ComprehensionScene.cpp
rdsmarketing/GLEXP-Team-KitkitSchool
6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e
[ "Apache-2.0" ]
29
2019-05-16T17:49:26.000Z
2021-12-30T16:36:24.000Z
// // ComprehensionScene.cpp // // Created by Gunho Lee on 12/10/16. // // #include "ComprehensionScene.hpp" #include <string> #include <vector> #include <numeric> #include <algorithm> #include "ui/CocosGUI.h" #include "Managers/GameSoundManager.h" #include "Managers/LanguageManager.hpp" //#include "Managers/UserManager.hpp" //#include "Managers/StrictLogManager.h" #include "Utils/TodoUtil.h" #include "Common/Basic/ScopeGuard.h" #include "Common/Basic/NodeScopeGuard.h" #include "3rdParty/CCNativeAlert.h" #include "Common/Controls/TodoSchoolBackButton.hpp" #include "Common/Controls/CompletePopup.hpp" #include "Common/Controls/PopupBase.hpp" #include "CompTrace/CompTrace.h" #include "FillTheBlanks/FillTheBlanksScene.hpp" #include "Matching/MatchingScene.hpp" #include "Reordering/ReorderingScene.hpp" #include "MultipleChoices/MultipleChoicesScene.hpp" #include "CCAppController.hpp" using namespace cocos2d::ui; using cocos2d::StringUtils::format; using namespace std; using namespace ComprehensionTest; namespace ComprehensionSceneSpace { const char* solveEffect = "Common/Sounds/Effect/UI_Star_Collected.m4a"; const char* missEffect = "Common/Sounds/Effect/Help.m4a"; const char* pageTurnEffect = "Common/Sounds/Effect/Card_Move_Right.m4a"; const char* defaultFont = FONT_ANDIKA_BOLD; const Size gameSize = Size(2560, 1800); Size winSize; } using namespace ComprehensionSceneSpace; bool ComprehensionScene::_isSolveAll = false; Scene* ComprehensionScene::createScene(string bookFolder, int set) { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = ComprehensionScene::create(); layer->setBookData(bookFolder, set); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } Scene* ComprehensionScene::createScene(string bookFolder, int set, bool checkCompleteCondition) { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = ComprehensionScene::create(); layer->setBookData(bookFolder, set); layer->setCheckCompleteCondition(checkCompleteCondition); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } int ComprehensionScene::getNumSet(string bookFolder) { auto filedata = FileUtils::getInstance()->getStringFromFile(bookFolder+"/compquiz.txt"); std::istringstream iss(filedata); std::string line; bool hasContents = false; int numSet = 0; while(iss.good()) { TodoUtil::safegetline(iss, line); if(line.length() == 0 && !iss.good()) { break; } if (line.length()>0 && line.front()=='-') { if (hasContents) numSet++; hasContents = false; } if (!line.empty()) hasContents = true; } if (hasContents) numSet++; return numSet; } bool ComprehensionScene::init() { if (!Layer::init()) { return false; } _isSolveAll = false; _touchEnabled = false; GameSoundManager::getInstance()->preloadEffect(solveEffect); GameSoundManager::getInstance()->preloadEffect(missEffect); GameSoundManager::getInstance()->preloadEffect(pageTurnEffect); winSize = getContentSize(); auto bg = Sprite::create("ComprehensionTest/Common/_comprehenson_background.png"); auto bgSize = bg->getContentSize(); float bgScale = MAX(winSize.width/bgSize.width, winSize.height/bgSize.height); bg->setScale(bgScale); bg->setPosition(winSize/2); addChild(bg); _paperBottom = Sprite::create("ComprehensionTest/Common/comprehensive_papers_bottom.png"); _paperBottom->setAnchorPoint(Vec2::ANCHOR_MIDDLE_BOTTOM); _paperBottom->setPosition(winSize.width / 2, 0.f); addChild(_paperBottom); _pageNode = Node::create(); _pageNode->setContentSize(winSize); addChild(_pageNode); _currentPageGridZ = 0; auto blockerView = Node::create(); blockerView->setContentSize(winSize); _blocker = EventListenerTouchOneByOne::create(); _blocker->setSwallowTouches(true); _blocker->onTouchBegan = [](Touch* T, Event* E) { return true; }; blockerView->getEventDispatcher()->addEventListenerWithSceneGraphPriority(_blocker, blockerView); addChild(blockerView); _blocker->setEnabled(false); auto backButton = TodoSchoolBackButton::create(); backButton->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); backButton->setPosition(Vec2(25, winSize.height-25)); addChild(backButton); _progressBar = ProgressIndicator::create(); _progressBar->setPosition(Vec2(winSize.width/2, winSize.height - _progressBar->getContentSize().height)); addChild(_progressBar); return true; } void ComprehensionScene::onEnter() { Layer::onEnter(); // _progressBar->setMax((int)sheet.size()); } void ComprehensionScene::onEnterTransitionDidFinish() { onStart(); } void ComprehensionScene::showBookChooser() { auto chooser = PopupBase::create(this, gameSize); auto innerView = Node::create(); // NB(xenosoz, 2018): Prevent iOS crash. auto list = [&] { if (!FileUtils::getInstance()->fullPathForFilename("Books/BookData/").empty()) { // NB(xenosoz, 2018): Good on non-iOS. return FileUtils::getInstance()->listFiles("Books/BookData/"); } if (!FileUtils::getInstance()->fullPathForFilename("Books/BookData").empty()) { // NB(xenosoz, 2018): Good on iOS. return FileUtils::getInstance()->listFiles("Books/BookData"); } return vector<string>(); }(); float y = -80; for (auto folder : list) { string quizPath = folder + "compquiz.txt"; if (FileUtils::getInstance()->isFileExist(quizPath)) { auto button = Button::create(); button->setTitleFontSize(50); button->setTitleColor(Color3B::WHITE); auto book = TodoUtil::split(folder, '/').back(); button->setTitleText(book); button->setPosition(Vec2(gameSize.width/2, y-=80)); innerView->addChild(button); button->addClickEventListener([this, folder, button, chooser](Ref*) { _bookFolder = folder; this->showSetChooser(); chooser->dismiss(true); }); } } auto height = -y + 100; auto scroll = ui::ScrollView::create(); scroll->setContentSize(gameSize); scroll->setInnerContainerSize(Size(gameSize.width, height)); innerView->setPosition(Vec2(0, height)); scroll->addChild(innerView); chooser->addChild(scroll); chooser->show(this, true); } void ComprehensionScene::showSetChooser() { auto chooser = PopupBase::create(this, gameSize); auto innerView = Node::create(); float y = -80; int num = getNumSet(_bookFolder); for (int i=1; i<=num; i++) { auto button = Button::create(); button->setTitleFontSize(50); button->setTitleColor(Color3B::WHITE); button->setTitleText(TodoUtil::itos(i)); button->setPosition(Vec2(gameSize.width/2, y-=80)); innerView->addChild(button); button->addClickEventListener([this, i, button, chooser](Ref*) { _problemSetIndex = i; if (true) { auto skip = Button::create(); skip->setTitleFontSize(100); auto folderName = TodoUtil::split(_bookFolder, '/').back(); skip->setTitleText(format("[%s - %d] Skip", folderName.c_str(), _problemSetIndex)); skip->setAnchorPoint(Vec2::ANCHOR_TOP_RIGHT); skip->setPosition(Vec2(winSize.width-25, winSize.height-25)); addChild(skip); skip->addTouchEventListener([this](Ref*,Widget::TouchEventType e) { if (e == Widget::TouchEventType::ENDED) { onSolve(); } }); } selectProblem(); showProblem(); _progressBar->setMax(problemSet.size()); _progressBar->setCurrent(_currentProblem + 1); chooser->dismiss(true); }); } auto height = -y + 100; auto scroll = ui::ScrollView::create(); scroll->setContentSize(gameSize); scroll->setInnerContainerSize(Size(gameSize.width, height)); innerView->setPosition(Vec2(0, height)); scroll->addChild(innerView); chooser->addChild(scroll); chooser->show(this, true); } void ComprehensionScene::onStart() { _currentProblem = 0; if (_bookFolder=="") { showBookChooser(); return; } if (_problemSetIndex==0) { showSetChooser(); return; } selectProblem(); showProblem(); _progressBar->setMax(problemSet.size()); _progressBar->setCurrent(_currentProblem + 1); } void ComprehensionScene::onSolve() { // StrictLogManager::shared()->comprehension_Solve(_bookFolder, _problemSetIndex, _currentProblem); _blocker->setEnabled(true); _progressBar->setCurrent(_currentProblem+1, true); _currentProblem++; auto previousPageGrid = _pageGrid; showProblem(); /* previousPageGrid->retain(); previousPageGrid->removeFromParent(); _pageNode->addChild(previousPageGrid); previousPageGrid->release(); */ GameSoundManager::getInstance()->playEffectSound(pageTurnEffect); float delay = 1.5f; this->runAction(Sequence::create(DelayTime::create(0.1+delay/2), CallFunc::create([this](){ _progressBar->setCurrent(_currentProblem+1); }), NULL)); auto turnSeq = Sequence::create(DelayTime::create(0.1), PageTurn3D::create(delay, Size(100,100)), FadeOut::create(0.1), CallFunc::create([this, previousPageGrid](){ previousPageGrid->removeFromParent(); _blocker->setEnabled(false); }), nullptr); previousPageGrid->runAction(turnSeq); } void ComprehensionScene::setCheckCompleteCondition(bool checkCompleteCondition) { _checkCompleteCondition = checkCompleteCondition; } void ComprehensionScene::setBookData(string bookFolder, int set) { _bookFolder = bookFolder; _problemSetIndex = set; //_bookNo = bookNo; //_languageTag = languageTag; } std::string ComprehensionScene::getBookName() { return TodoUtil::split(_bookFolder, '/').back(); } int ComprehensionScene::getCurrentProblem() { return _currentProblem; } NodeGrid* ComprehensionScene::createPageGrid() { auto grid = NodeGrid::create(); grid->setContentSize(winSize); auto paperTop = Sprite::create("ComprehensionTest/Common/comprehensive_papers_top.png"); paperTop->setAnchorPoint(Vec2::ANCHOR_MIDDLE_BOTTOM); paperTop->setPosition(winSize.width / 2, 0.f); grid->addChild(paperTop); return grid; } void checkData(vector<string>& v, int line) { string lineStr = TodoUtil::itos(line); if (v.size()<1) { NativeAlert::show("Error in Comp Data (line "+lineStr+")", "no subgame definition", "OK"); return; } int requiredColumns = 0; if (v[0] == "matching") { requiredColumns = 5; } else if (v[0] == "fill the blanks") { requiredColumns = 4; } else if (v[0] == "reordering") { requiredColumns = 2; } else if (v[0] == "multiple choices") { requiredColumns = 4; } else if (v[0] == "tracing") { requiredColumns = 2; } else { NativeAlert::show("Error in Comp Data (line "+lineStr+")", "no subgame definition", "OK"); return; } if (v.size()<requiredColumns) { NativeAlert::show("Error in Comp Data (line "+lineStr+")", v[0]+"needs "+TodoUtil::itos(requiredColumns)+" columns, not "+TodoUtil::itos(v.size()), "OK"); return; } } void ComprehensionScene::selectProblem() { auto filedata = FileUtils::getInstance()->getStringFromFile(_bookFolder+"/compquiz.txt"); std::istringstream iss(filedata); std::string line; bool setStarted = false; bool problemStarted = false; int currentSet = 1; vector<string> v; while(iss.good()) { TodoUtil::safegetline(iss, line); if(line.length() == 0 && !iss.good()) { break; } if (currentSet>_problemSetIndex) break; if (line.length()>0 && line.front()=='-') { currentSet++; continue; } if (currentSet == _problemSetIndex) { line = TodoUtil::trim(line); if (!setStarted && line.empty()) { continue; } else { setStarted = true; } if (!line.empty()) { v.push_back(line); problemStarted = true; } else { if (problemStarted) { ComprehensionProblem p; p.first = v[0]; p.second = v; problemSet.push_back(p); v.clear(); problemStarted = false; } } } } if (v.size()>0 && currentSet == _problemSetIndex) { ComprehensionProblem p; p.first = v[0]; p.second = v; problemSet.push_back(p); } } void ComprehensionScene::showProblem() { // All clear if (_currentProblem == problemSet.size()) { _paperBottom->setVisible(false); auto CP = CompletePopup::create(); CP->show(1.f, [this] { auto Guard = NodeScopeGuard(this); _isSolveAll = true; if (_checkCompleteCondition) { CCAppController::sharedAppController()->handleGameComplete(1); } else { CCAppController::sharedAppController()->handleGameQuit(); } }); return; } else { _pageGrid = createPageGrid(); _pageNode->addChild(_pageGrid, _currentPageGridZ--); _gameNode = Node::create(); _gameNode->setContentSize(winSize); _pageGrid->addChild(_gameNode); } std::string comprehensionTestName = problemSet[_currentProblem].first; if (comprehensionTestName == "matching") { _gameNode->addChild(Matching::MatchingScene::createLayer(this)); } else if (comprehensionTestName == "fill the blanks") { _gameNode->addChild(FillTheBlanks::FillTheBlanksScene::createLayer(this)); } else if (comprehensionTestName == "reordering") { _gameNode->addChild(Reordering::ReorderingScene::createLayer(this)); } else if (comprehensionTestName == "multiple choices") { _gameNode->addChild(MultipleChoices::MultipleChoicesScene::createLayer(this)); } else if (comprehensionTestName.find("tracing") != string::npos) { _gameNode->addChild(CompTrace().createLayer(this)); } } Button* ComprehensionScene::drawSoundButton(Node* targetNode) { auto soundButton = Button::create("ComprehensionTest/Common/comprehension_speaker_normal.png", "ComprehensionTest/Common/comprehension_speaker_active.png"); soundButton->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); soundButton->setPosition(Vec2(175.f, targetNode->getContentSize().height - 185.f)); targetNode->addChild(soundButton); return soundButton; } void ComprehensionScene::drawQuestionTitle(string titleText, Node* parentNode, float addLeftPadding) { // if (TodoUtil::trim(titleText).size() <= 0) // return; float leftPadding = 200.f; float rightPadding = 200.f; auto questionHighlight = Sprite::create("ComprehensionTest/Common/comprehention_question_highlight.png"); questionHighlight->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); questionHighlight->setPosition(200.f, parentNode->getContentSize().height - 300.f); parentNode->addChild(questionHighlight); auto titleLabel = TodoUtil::createLabel(titleText, 60.f, Size::ZERO, FONT_ANDIKA_BOLD, Color4B(77, 77, 77, 255)); titleLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); titleLabel->setPosition(leftPadding + addLeftPadding, questionHighlight->getContentSize().height / 2); questionHighlight->addChild(titleLabel); float maxLabelWidth = questionHighlight->getContentSize().width - leftPadding - rightPadding; float titleLabelWidth = titleLabel->getContentSize().width; if (titleLabelWidth > maxLabelWidth) { titleLabel->setScale(maxLabelWidth / titleLabelWidth); } }
28.088235
168
0.617685
[ "object", "vector" ]
9328737be9dc01ff7017b00b20107d36a8fd2df7
2,671
cpp
C++
src/Game/GHAMAnimFactoryGPU.cpp
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
src/Game/GHAMAnimFactoryGPU.cpp
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
src/Game/GHAMAnimFactoryGPU.cpp
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
// Copyright Golden Hammer Software #include "GHAMAnimFactoryGPU.h" #include "GHGPUVertexAnimController.h" #include "GHString/GHStringIdFactory.h" #include "GHVBAnimData.h" #include "GHTransformAnimController.h" #include "GHTransformAnimData.h" #include "GHSkinAnimControllerCPU.h" #include "GHTransformNode.h" #include "GHSkeletonAnimController.h" GHAMAnimFactoryGPU::GHAMAnimFactoryGPU(const GHTimeVal& time, GHStringIdFactory& hashTable) : mTime(time) , mInterpProp(hashTable.generateHash("interppct")) { } GHFrameAnimControllerVB* GHAMAnimFactoryGPU::createMeshAnim(void) const { unsigned int lowStreamTarget = 1; unsigned int highStreamTarget = 2; unsigned int sourceStreamId = 0; GHFrameAnimControllerVB* ret = new GHGPUVertexAnimController(lowStreamTarget, highStreamTarget, sourceStreamId, mInterpProp, mTime); GHVBAnimData* animData = new GHVBAnimData; ret->setAnimData(animData); return ret; } GHTransformAnimController* GHAMAnimFactoryGPU::createNodeAnim(void) const { GHTransformAnimController* ret = new GHTransformAnimController(mTime); ret->setAnimData(new GHTransformAnimData); return ret; } GHSkinAnimController* GHAMAnimFactoryGPU::createSkinAnim(const std::vector<GHIdentifier>& nodeIds) const { return new GHSkinAnimControllerCPU(nodeIds); } GHSkeletonAnimController* GHAMAnimFactoryGPU::createSkeletonAnim(GHTransformNode& skelTop) const { std::vector<GHTransformNode*> flattenedTree; skelTop.collectTree(flattenedTree); std::vector<GHTransformAnimData*> animData; animData.resize(flattenedTree.size()); for (size_t i = 0; i < animData.size(); ++i) { animData[i] = new GHTransformAnimData; } GHSkeletonAnimController* ret = new GHSkeletonAnimController(mTime); ret->setTarget(flattenedTree, animData); return ret; } void GHAMAnimFactoryGPU::modifyStreamDesc(const GHAM::MeshHeader& meshHeader, GHVBDescription::StreamDescription& streamDesc) const { streamDesc.mIsShared = true; streamDesc.mUsage = GHVBUsage::STATIC; // pos stream in skinned meshes needs to be unique if using cpu skinning if (meshHeader.mIsSkinned) { bool streamHasPos = false; for (size_t i = 0; i < streamDesc.mComps.size(); ++i) { if (streamDesc.mComps[i].mID == GHVertexComponentShaderID::SI_POS) { streamHasPos = true; } } if (streamHasPos) { streamDesc.mIsShared = false; streamDesc.mUsage = GHVBUsage::DYNAMIC; } } }
34.688312
131
0.697492
[ "vector" ]
9335ae836220d635a7b231bc496d2264ecd5ceda
11,829
cpp
C++
Source/Parser/Private/TlObject.cpp
ZaiKratz/TLParser
aa7bc8a01f92dbeeb9ea3a3f70ad633a56c18d30
[ "MIT" ]
2
2017-09-28T17:53:42.000Z
2018-09-28T09:36:06.000Z
Source/Parser/Private/TlObject.cpp
ZaiKratz/TLParser
aa7bc8a01f92dbeeb9ea3a3f70ad633a56c18d30
[ "MIT" ]
null
null
null
Source/Parser/Private/TlObject.cpp
ZaiKratz/TLParser
aa7bc8a01f92dbeeb9ea3a3f70ad633a56c18d30
[ "MIT" ]
null
null
null
#include "TlObject.h" #include "Regex.h" #include "Parse.h" #include <string> #include <regex> TLObject::TLObject() { _CORE_TYPES = { 0x1cb5c415, // vector#1cb5c415 {t:Type} # [ t ] = Vector t 0xbc799737, // boolFalse#bc799737 = Bool; 0x997275b5, // boolTrue#997275b5 = Bool; 0x3fedd339 // true#3fedd339 = True; }; } FString ToCamalCase(FString ClassName) { FRegexPattern Pattern( TEXT("((?i)[a-z]+\\d?)_*") ); FRegexMatcher Match(Pattern, ClassName); FString CamalClassName; while (Match.FindNext()) { FString tmp = Match.GetCaptureGroup(1); tmp[0] = toupper(tmp[0]); CamalClassName += tmp; } return CamalClassName; } TLObject::TLObject(FString FullName, FString ObjectId, TArray<TLArg> Args, FString Result, bool IsFunction) { _CORE_TYPES = { 0x1cb5c415, // vector#1cb5c415 {t:Type} # [ t ] = Vector t 0xbc799737, // boolFalse#bc799737 = Bool; 0x997275b5, // boolTrue#997275b5 = Bool; 0x3fedd339 // true#3fedd339 = True; }; if (FullName.Contains(TEXT("."))) { FullName.Split(TEXT("."), &this->_Namespace, &this->_Name); this->_Namespace = this->_Namespace.ToUpper(); if (_Name.Contains(TEXT("_"))) this->_Name = ToCamalCase(_Name); if (!_Name.IsEmpty()) this->_Name[0] = toupper(this->_Name[0]); } else { this->_Namespace = TEXT("COMMON"); if (FullName.Contains(TEXT("_"))) this->_Name = ToCamalCase(FullName); else this->_Name = FullName; if(!_Name.IsEmpty()) this->_Name[0] = toupper(this->_Name[0]); } this->_Args = Args; if (Result.Contains(TEXT("_"))) this->_Result = ToCamalCase(Result); else this->_Result = Result; if (_Result.Contains(TEXT("."))) { FString TMPName; FString TMPNamespace; _Result = _Result.Replace(TEXT("."), TEXT("::")); _Result.Split(TEXT("::"), &TMPNamespace, &TMPName); } if(!_Result.IsEmpty()) if (_Result != TEXT("bool") && !this->SystemTypes().Contains(_Result)) { _Result[0] = toupper(_Result[0]); } this->_IsFunction = IsFunction; if (ObjectId.IsEmpty()) this->_Id = InferID(FullName, ObjectId, Args, Result); else { ObjectId.InsertAt(0, "0x"); std::string StdString(TCHAR_TO_UTF8(*ObjectId)); uint32 x = strtoul(StdString.c_str(), NULL, 16); /*big endian*/ this->_Id = x; } } TLObject TLObject::FromTL(FString InStr, bool IsFunction) { FRegexPattern Pattern( TEXT("^([\\w.]+)(?:\\#([0-9a-f]+))?(?:\\s\\{?\\w+:[\\w\\d<>#.?!]+\\}?)*\\s=\\s([\\w\\d<>#.?]+);$") ); FRegexMatcher Match(Pattern, InStr); FString FullName; FString ObjectId; FString Result; if (Match.FindNext()) { FullName = Match.GetCaptureGroup(1); ObjectId = Match.GetCaptureGroup(2); Result = Match.GetCaptureGroup(3); } if (ObjectId == "bdf9653b") _LOG(""); FRegexPattern ArgsPattern( TEXT("(\\{)?(\\w+):([\\w\\d<>#.?!]+)(\\})?") ); FRegexMatcher ArgsMatch(ArgsPattern, InStr); TArray<TLArg> Args; while (ArgsMatch.FindNext()) { auto Braces = ArgsMatch.GetCaptureGroup(1); auto Name = ArgsMatch.GetCaptureGroup(2); auto Type = ArgsMatch.GetCaptureGroup(3); if (Braces.IsEmpty()) if (Type == TEXT("X") || Type == TEXT("!X")) { Type = TEXT("TLBaseObject"); Args.Add(TLArg(Name, Type)); } else Args.Add(TLArg(Name, Type)); } FRegexPattern VectorPattern(TEXT("[Vv]ector<(\\w+)>")); FRegexMatcher VectorMatch(VectorPattern, Result); if (VectorMatch.FindNext()) { Result = VectorMatch.GetCaptureGroup(1); if (Result == TEXT("int")) Result = TEXT("TArray<int32>"); else if (Result == TEXT("long")) Result = TEXT("TArray<unsigned long long>"); else if (Result == TEXT("int128")) Result = TEXT("TArray<TBigInt<128>>"); else if (Result == TEXT("int256")) Result = TEXT("TArray<TBigInt<256>>"); else if (Result == TEXT("string")) Result = TEXT("TArray<FString>"); else if (Result == TEXT("X")) Result = TEXT("TArray<TLBaseObject>"); else if (Result.Contains(TEXT("Bool"))) Result = TEXT("TArray<bool>"); else if (this->SystemTypes().Contains(Result)) Result = TEXT("TArray<") + Result + TEXT(">"); else Result = TEXT("TArray<") + Result + TEXT(">"); } else { if (Result == TEXT("int")) Result = TEXT("int32"); else if (Result == TEXT("long")) Result = TEXT("unsigned long long"); else if (Result == TEXT("int128")) Result = TEXT("TBigInt<128>"); else if (Result == TEXT("int256")) Result = TEXT("TBigInt<256>"); else if (Result == TEXT("string")) Result = TEXT("FString"); else if (Result == TEXT("X")) Result = TEXT("TLBaseObject"); else if (Result.Contains(TEXT("Bool"))) Result = TEXT("bool"); } return TLObject(FullName, ObjectId, Args, Result, IsFunction); } TArray<TLArg> TLObject::SortedArgs() { auto TmpArgs = this->_Args; // TmpArgs.Sort( // [&](const TLArg &Item ) { // return Item.IsFlag() || Item.CanBeInferred(); // } // ); return TmpArgs; } bool TLObject::IsCoreType() { return this->_CORE_TYPES.Contains(this->_Id); } uint32 TLObject::CRC32(const void * Data, int32 Size) { FCrc::Init(); return FCrc::MemCrc32(Data, Size); } FString TLObject::Repr(FString FullName, FString ObjectID, TArray<TLArg> Args, FString Result, bool IgnoreID /*= false*/) { FString HexID; if (ObjectID.IsEmpty() || IgnoreID) HexID = TEXT(""); else HexID = TEXT("#") + ObjectID; FString RealArgs; if (this->Args().Num()) { for (auto Arg : this->Args()) { RealArgs += TEXT(" "); RealArgs += Arg.Repr(); } } else RealArgs = TEXT(""); return FullName + HexID + RealArgs + TEXT(" = ") + Result; } uint32 TLObject::InferID(FString FullName, FString ObjectID, TArray<TLArg> Args, FString Result) { FString Representation = Repr(FullName, ObjectID, Args, Result); Representation = Representation.Replace(TEXT(":bytes"), TEXT(":string")). Replace(TEXT("?bytes"), TEXT("?string")). Replace(TEXT("<"), TEXT(" ")). Replace(TEXT(">"), TEXT("")). Replace(TEXT("{"), TEXT("")). Replace(TEXT("}"), TEXT("")); std::string StdString = TCHAR_TO_UTF8(*Representation); std::regex Pattern("\\w+:flags\\.\\d+?true"); Representation = UTF8_TO_TCHAR(std::regex_replace(StdString, Pattern, "").c_str()); return CRC32(TCHAR_TO_ANSI(*Representation), Representation.Len()); } TLArg::TLArg() { } TLArg::TLArg(FString Name, FString ArgType) { // Initializes a new .tl argument // :param Name: The name of the .tl argument // :param ArgType: The type of the .tl argument this->_Name = Name; this->_IsBytes = false; this->_IsVector = false; this->_IsFlag = false; this->_FlagIndex = -1; // # Special case: some types can be inferred, which makes it // # less annoying to type. Currently the only type that can // # be inferred is if the name is 'random_id', to which a // # random ID will be assigned if left as None (the default) this->_CanBeInferred = Name == TEXT("random_id"); // The type can be an indicator that other arguments will be flags if (ArgType == TEXT("#")) { this->_FlagIndicator = true; this->_Type = TEXT(""); this->_IsGeneric = false; } else { this->_FlagIndicator = false; this->_IsGeneric = ArgType.StartsWith(TEXT("!")); ArgType.RemoveFromStart(TEXT("!")); // Strip the exclamation mark always to have only the name _Type = ArgType; if (_Type == TEXT("int")) this->_Type = TEXT("int32"); else if (_Type == TEXT("long")) this->_Type = TEXT("unsigned long long"); else if (_Type == TEXT("int128")) this->_Type = TEXT("TBigInt<128>"); else if (_Type == TEXT("int256")) this->_Type = TEXT("TBigInt<256>"); else if (_Type == TEXT("bytes")) { this->_IsBytes = true; this->_Type = TEXT("uint8"); } else if(_Type == TEXT("string")) this->_Type = TEXT("FString"); } // # The type may be a flag (flags.IDX?REAL_TYPE) // # Note that 'flags' is NOT the flags name; this is determined by a previous argument // # However, we assume that the argument will always be called 'flags' FRegexPattern FlagPattern(TEXT("flags.(\\d+)\\?([\\w<>.]+)")); FRegexMatcher FlagMatch(FlagPattern, this->_Type); if (FlagMatch.FindNext()) { this->_IsFlag = true; this->_FlagIndex = FCString::Atoi(*FlagMatch.GetCaptureGroup(1)); // Update the type to match the exact type, not the "flagged" one this->_Type = FlagMatch.GetCaptureGroup(2); if (_Type == TEXT("int")) this->_Type = TEXT("int32"); else if (_Type == TEXT("long")) this->_Type = TEXT("unsigned long long"); else if (_Type == TEXT("int128")) this->_Type = TEXT("TBigInt<128>"); else if (_Type == TEXT("int256")) this->_Type = TEXT("TBigInt<256>"); else if (_Type == TEXT("bytes")) { this->_IsBytes = true; this->_Type = TEXT("uint8"); } else if (_Type == TEXT("string")) this->_Type = TEXT("FString"); } if (_Type.Contains(TEXT("."))) _Type = _Type.Replace(TEXT("."), TEXT("::")); // Then check if the type is a Vector<REAL_TYPE> FRegexPattern VectorPattern(TEXT("[Vv]ector<(\\w+)>")); FRegexMatcher VectorMatch(VectorPattern, this->_Type); if (VectorMatch.FindNext()) { this->_IsVector = true; this->_UseVectorID = this->_Type[0] == TEXT('V'); this->_Type = VectorMatch.GetCaptureGroup(1); if (_Type == TEXT("int")) this->_Type = TEXT("int32"); else if (_Type == TEXT("Bool")) _Type[0] = tolower(_Type[0]); else if (_Type == TEXT("string")) this->_Type = this->_Type.Replace(TEXT("string"), TEXT("FString")); else if (_Type == TEXT("long")) this->_Type = TEXT("unsigned long long"); else if (_Type == TEXT("int128")) this->_Type = TEXT("TBigInt<128>"); else if (_Type == TEXT("int256")) this->_Type = TEXT("TBigInt<256>"); } // # The name may contain "date" in it, if this is the case and the type is "int", // # we can safely assume that this should be treated as a "date" object. // # Note that this is not a valid Telegram object, but it's easier to work with FRegexPattern DatePattern(TEXT("(\\b|_)date\\b")); FRegexMatcher DateMatch(DatePattern, this->_Name); TArray<FString> AnonymousList = { TEXT("expires"), TEXT("expires_at"), TEXT("was_online") }; if (this->_Type == TEXT("int32") && (DateMatch.FindNext() || AnonymousList.Contains(this->_Name))) { this->_Type = TEXT("FDateTime"); } if (_Type.Contains(TEXT("_"))) _Type = ToCamalCase(_Type); } FString TLArg::Repr() { auto RealType = this->Type(); if (RealType == TEXT("int32")) RealType = TEXT("int"); else if (RealType == TEXT("bool")) RealType = TEXT("Bool"); else if (RealType == TEXT("FString")) RealType = RealType.Replace(TEXT("FString"), TEXT("string")); else if (RealType == TEXT("unsigned long long")) RealType = TEXT("long"); else if (RealType == TEXT("TBigInt<128>")) RealType = TEXT("int128"); else if (RealType == TEXT("TBigInt<256>")) RealType = TEXT("int256"); else if (RealType == TEXT("FDateTime")) RealType = TEXT("int"); if (this->IsFlagIndicator()) { RealType = TEXT("#"); } if (this->IsVector()) { if (this->IsUsingVectorID()) RealType = TEXT("Vector<") + RealType + TEXT(">"); else RealType = TEXT("vector<") + RealType + TEXT(">"); } if (this->IsGeneric()) RealType = TEXT("!") + RealType; if (this->IsFlag()) RealType = TEXT("flags.") + FString::FromInt(this->FlagIndex()) + TEXT("?") + RealType; return this->Name() + TEXT(":") + RealType; } bool TLArg::operator==(const TLArg &RHObject) { return _CanBeInferred == RHObject._CanBeInferred && _FlagIndex == RHObject._FlagIndex && _FlagIndicator == RHObject._FlagIndicator && _IsFlag == RHObject._IsFlag && _IsGeneric == RHObject._IsGeneric && _IsVector == RHObject._IsVector && _Name == RHObject._Name && _Type == RHObject._Type && _UseVectorID == RHObject._UseVectorID && _IsBytes == RHObject._IsBytes; } bool TLArg::operator!=(const TLArg &RHObject) { return !operator==(RHObject); }
24.289528
121
0.635134
[ "object", "vector" ]
933a63257a80d9a9b0d4fe6002360ae1345b31f4
35,983
cpp
C++
OrbitGl/CaptureWindow.cpp
beckerhe/orbitprofiler
dc528ac0b08af41d6ef4d28b97f6849c6bab63a7
[ "BSD-2-Clause" ]
2
2020-04-01T10:37:24.000Z
2021-12-26T06:44:50.000Z
OrbitGl/CaptureWindow.cpp
beckerhe/orbitprofiler
dc528ac0b08af41d6ef4d28b97f6849c6bab63a7
[ "BSD-2-Clause" ]
null
null
null
OrbitGl/CaptureWindow.cpp
beckerhe/orbitprofiler
dc528ac0b08af41d6ef4d28b97f6849c6bab63a7
[ "BSD-2-Clause" ]
null
null
null
//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include "CaptureWindow.h" #include "../OrbitPlugin/OrbitSDK.h" #include "App.h" #include "Capture.h" #include "EventTracer.h" #include "GlUtils.h" #include "PluginManager.h" #include "Serialization.h" #include "Systrace.h" #include "TcpClient.h" #include "TcpServer.h" #include "TimerManager.h" #include "absl/strings/str_format.h" #ifdef _WIN32 #include "SymbolUtils.h" #else #include <array> #include <cstdio> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include "LinuxUtils.h" #endif //----------------------------------------------------------------------------- CaptureWindow::CaptureWindow() { GCurrentTimeGraph = &m_TimeGraph; m_TimeGraph.SetTextRenderer(&m_TextRenderer); m_TimeGraph.SetPickingManager(&m_PickingManager); m_TimeGraph.SetCanvas(this); m_DrawUI = false; m_DrawHelp = false; m_DrawFilter = false; m_DrawMemTracker = false; m_FirstHelpDraw = true; m_DrawStats = false; m_Picking = false; m_WorldTopLeftX = 0; m_WorldTopLeftY = 0; m_WorldMaxY = 0; m_ProcessX = 0; GTimerManager->m_TimerAddedCallbacks.push_back( [=](Timer& a_Timer) { this->OnTimerAdded(a_Timer); }); GTimerManager->m_ContextSwitchAddedCallback = [=](const ContextSwitch& a_CS) { this->OnContextSwitchAdded(a_CS); }; m_HoverDelayMs = 300; m_CanHover = false; m_IsHovering = false; ResetHoverTimer(); m_Slider.SetCanvas(this); m_Slider.SetDragCallback([&](float a_Ratio) { this->OnDrag(a_Ratio); }); m_VerticalSlider.SetCanvas(this); m_VerticalSlider.SetVertical(); m_VerticalSlider.SetDragCallback( [&](float a_Ratio) { this->OnVerticalDrag(a_Ratio); }); GOrbitApp->RegisterCaptureWindow(this); } //----------------------------------------------------------------------------- CaptureWindow::~CaptureWindow() { if (GCurrentTimeGraph == &m_TimeGraph) GCurrentTimeGraph = nullptr; } //----------------------------------------------------------------------------- void CaptureWindow::OnTimer() { GlCanvas::OnTimer(); } //----------------------------------------------------------------------------- void CaptureWindow::ZoomAll() { m_TimeGraph.ZoomAll(); m_WorldTopLeftY = m_WorldMaxY; ResetHoverTimer(); NeedsUpdate(); } //----------------------------------------------------------------------------- void CaptureWindow::UpdateWheelMomentum(float a_DeltaTime) { GlCanvas::UpdateWheelMomentum(a_DeltaTime); bool zoomWidth = true; // TODO: !wxGetKeyState(WXK_CONTROL); if (zoomWidth && m_WheelMomentum != 0.f) { m_TimeGraph.ZoomTime(m_WheelMomentum, m_MouseRatio); } } //----------------------------------------------------------------------------- void CaptureWindow::MouseMoved(int a_X, int a_Y, bool a_Left, bool /*a_Right*/, bool /*a_Middle*/) { int mousex = a_X; int mousey = a_Y; float worldx, worldy; ScreenToWorld(a_X, a_Y, worldx, worldy); m_MouseX = worldx; m_MouseY = worldy; m_MousePosX = mousex; m_MousePosY = mousey; // Pan if (a_Left && !m_ImguiActive && !m_PickingManager.IsDragging() && !Capture::IsCapturing()) { float worldMin; float worldMax; m_TimeGraph.GetWorldMinMax(worldMin, worldMax); m_WorldTopLeftX = m_WorldClickX - (float)mousex / (float)getWidth() * m_WorldWidth; m_WorldTopLeftY = m_WorldClickY + (float)mousey / (float)getHeight() * m_WorldHeight; m_WorldTopLeftX = clamp(m_WorldTopLeftX, worldMin, worldMax - m_WorldWidth); m_WorldTopLeftY = clamp(m_WorldTopLeftY, m_WorldHeight - m_TimeGraph.GetThreadTotalHeight(), m_WorldMaxY); UpdateSceneBox(); m_TimeGraph.PanTime(m_ScreenClickX, a_X, getWidth(), (double)m_RefTimeClick); UpdateVerticalSlider(); NeedsUpdate(); } if (m_IsSelecting) { m_SelectStop = Vec2(worldx, worldy); m_TimeStop = m_TimeGraph.GetTickFromWorld(worldx); } if (a_Left) { m_PickingManager.Drag(a_X, a_Y); } ResetHoverTimer(); NeedsRedraw(); } //----------------------------------------------------------------------------- void CaptureWindow::LeftDown(int a_X, int a_Y) { // Store world clicked pos for panning ScreenToWorld(a_X, a_Y, m_WorldClickX, m_WorldClickY); m_ScreenClickX = a_X; m_ScreenClickY = a_Y; m_RefTimeClick = (TickType)m_TimeGraph.GetTime((double)a_X / (double)getWidth()); m_IsSelecting = false; Orbit_ImGui_MouseButtonCallback(this, 0, true); m_Picking = true; NeedsRedraw(); } //----------------------------------------------------------------------------- void CaptureWindow::LeftUp() { GlCanvas::LeftUp(); NeedsRedraw(); } //----------------------------------------------------------------------------- void CaptureWindow::LeftDoubleClick() { GlCanvas::LeftDoubleClick(); m_DoubleClicking = true; m_Picking = true; } //----------------------------------------------------------------------------- void CaptureWindow::Pick() { m_Picking = true; NeedsRedraw(); } //----------------------------------------------------------------------------- void CaptureWindow::Pick(int a_X, int a_Y) { // 4 bytes per pixel (RGBA), 1x1 bitmap std::vector<unsigned char> pixels(1 * 1 * 4); glReadPixels(a_X, m_MainWindowHeight - a_Y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[0]); PickingID pickId = PickingID::Get(*((uint32_t*)(&pixels[0]))); Capture::GSelectedTextBox = nullptr; Capture::GSelectedThreadId = 0; Pick(pickId, a_X, a_Y); NeedsUpdate(); } //----------------------------------------------------------------------------- void CaptureWindow::Pick(PickingID a_PickingID, int a_X, int a_Y) { uint32_t type = a_PickingID.m_Type; uint32_t id = a_PickingID.m_Id; switch (type) { case PickingID::BOX: { void** textBoxPtr = m_TimeGraph.GetBatcher().GetBoxBuffer().m_UserData.SlowAt(id); if (textBoxPtr) { TextBox* textBox = (TextBox*)*textBoxPtr; SelectTextBox(textBox); } break; } case PickingID::LINE: { void** textBoxPtr = m_TimeGraph.GetBatcher().GetLineBuffer().m_UserData.SlowAt(id); if (textBoxPtr) { TextBox* textBox = (TextBox*)*textBoxPtr; SelectTextBox(textBox); } break; } case PickingID::PICKABLE: m_PickingManager.Pick(a_PickingID.m_Id, a_X, a_Y); break; } } //----------------------------------------------------------------------------- void CaptureWindow::SelectTextBox(class TextBox* a_TextBox) { Capture::GSelectedTextBox = a_TextBox; Capture::GSelectedThreadId = a_TextBox->GetTimer().m_TID; Capture::GSelectedCallstack = Capture::GetCallstack(a_TextBox->GetTimer().m_CallstackHash); GOrbitApp->SetCallStack(Capture::GSelectedCallstack); const Timer& a_Timer = a_TextBox->GetTimer(); DWORD64 address = a_Timer.m_FunctionAddress; if (a_Timer.IsType(Timer::ZONE)) { std::shared_ptr<CallStack> callStack = Capture::GetCallstack(a_Timer.m_CallstackHash); if (callStack && callStack->m_Depth > 1) { address = callStack->m_Data[1]; } } FindCode(address); if (m_DoubleClicking && a_TextBox) { m_TimeGraph.Zoom(a_TextBox); } } //----------------------------------------------------------------------------- void CaptureWindow::Hover(int a_X, int a_Y) { // 4 bytes per pixel (RGBA), 1x1 bitmap std::vector<unsigned char> pixels(1 * 1 * 4); glReadPixels(a_X, m_MainWindowHeight - a_Y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[0]); PickingID pickId = *((PickingID*)(&pixels[0])); TextBox* textBox = m_TimeGraph.GetBatcher().GetTextBox(pickId); if (textBox) { if (!textBox->GetTimer().IsType(Timer::CORE_ACTIVITY)) { Function* func = Capture::GSelectedFunctionsMap[textBox->GetTimer().m_FunctionAddress]; m_ToolTip = s2ws(absl::StrFormat("%s %s", func ? func->PrettyName().c_str() : "", textBox->GetText().c_str())); GOrbitApp->SendToUiAsync(L"tooltip:" + m_ToolTip); NeedsRedraw(); } } } //----------------------------------------------------------------------------- void CaptureWindow::FindCode(DWORD64 address) { #ifdef _WIN32 SCOPE_TIMER_LOG("FindCode"); LineInfo lineInfo; if (SymUtils::GetLineInfo(address, lineInfo) || (Capture::GSamplingProfiler && Capture::GSamplingProfiler->GetLineInfo(address, lineInfo))) { --lineInfo.m_Line; // File mapping const std::map<std::wstring, std::wstring>& fileMap = GOrbitApp->GetFileMapping(); for (const auto& pair : fileMap) { ReplaceStringInPlace(lineInfo.m_File, pair.first, pair.second); } if (lineInfo.m_Address != 0) { GOrbitApp->SendToUiAsync( Format(L"code^%s^%i", lineInfo.m_File.c_str(), lineInfo.m_Line)); } } #else UNUSED(address); #endif } //----------------------------------------------------------------------------- void CaptureWindow::PreRender() { if (m_CanHover && m_HoverTimer.QueryMillis() > m_HoverDelayMs) { m_IsHovering = true; m_Picking = true; NeedsRedraw(); } m_NeedsRedraw = m_NeedsRedraw || m_TimeGraph.IsRedrawNeeded(); } //----------------------------------------------------------------------------- void CaptureWindow::PostRender() { if (m_IsHovering) { m_IsHovering = false; m_CanHover = false; m_Picking = false; m_HoverTimer.Reset(); Hover(m_MousePosX, m_MousePosY); NeedsUpdate(); GlCanvas::Render(m_Width, m_Height); m_HoverTimer.Reset(); } if (m_Picking) { m_Picking = false; Pick(m_ScreenClickX, m_ScreenClickY); NeedsRedraw(); GlCanvas::Render(m_Width, m_Height); } } //----------------------------------------------------------------------------- void CaptureWindow::Resize(int a_Width, int a_Height) { m_Width = a_Width; m_Height = a_Height; NeedsUpdate(); } //----------------------------------------------------------------------------- void CaptureWindow::RightDown(int a_X, int a_Y) { ScreenToWorld(a_X, a_Y, m_WorldClickX, m_WorldClickY); m_ScreenClickX = a_X; m_ScreenClickY = a_Y; Pick(); m_IsSelecting = true; m_SelectStart = Vec2(m_WorldClickX, m_WorldClickY); m_SelectStop = m_SelectStart; m_TimeStart = m_TimeGraph.GetTickFromWorld(m_WorldClickX); m_TimeStop = m_TimeStart; } //----------------------------------------------------------------------------- bool CaptureWindow::RightUp() { if (m_IsSelecting && (m_SelectStart[0] != m_SelectStop[0]) && ControlPressed()) { float minWorld = std::min(m_SelectStop[0], m_SelectStart[0]); float maxWorld = std::max(m_SelectStop[0], m_SelectStart[0]); double newMin = m_TimeGraph.GetTime((minWorld - m_WorldTopLeftX) / m_WorldWidth); double newMax = m_TimeGraph.GetTime((maxWorld - m_WorldTopLeftX) / m_WorldWidth); m_TimeGraph.SetMinMax(newMin, newMax); m_SelectStart = m_SelectStop; } bool showContextMenu = m_SelectStart[0] == m_SelectStop[0]; m_IsSelecting = false; NeedsRedraw(); return showContextMenu; } //----------------------------------------------------------------------------- void CaptureWindow::MiddleDown(int a_X, int a_Y) { float worldx, worldy; ScreenToWorld(a_X, a_Y, worldx, worldy); m_IsSelecting = true; m_SelectStart = Vec2(worldx, worldy); m_SelectStop = m_SelectStart; } //----------------------------------------------------------------------------- void CaptureWindow::MiddleUp(int a_X, int a_Y) { float worldx, worldy; ScreenToWorld(a_X, a_Y, worldx, worldy); m_IsSelecting = false; m_SelectStop = Vec2(worldx, worldy); // m_TimeGraph.SelectEvents( m_SelectStart[0], m_SelectStop[0], -1 ); NeedsRedraw(); } //----------------------------------------------------------------------------- void CaptureWindow::Zoom(int a_Delta) { if (a_Delta == 0) return; a_Delta = -a_Delta; float worldx; float worldy; ScreenToWorld(m_MousePosX, m_MousePosY, worldx, worldy); m_MouseRatio = (double)m_MousePosX / (double)getWidth(); m_TimeGraph.ZoomTime((float)a_Delta, m_MouseRatio); m_WheelMomentum = a_Delta * m_WheelMomentum < 0 ? 0.f : m_WheelMomentum + (float)a_Delta; NeedsUpdate(); } //----------------------------------------------------------------------------- void CaptureWindow::Pan(float a_Ratio) { double refTime = (TickType)m_TimeGraph.GetTime((double)m_MousePosX / (double)getWidth()); m_TimeGraph.PanTime(m_MousePosX, m_MousePosX + static_cast<int>(a_Ratio * getWidth()), getWidth(), refTime); UpdateSceneBox(); NeedsUpdate(); } //----------------------------------------------------------------------------- void CaptureWindow::MouseWheelMoved(int a_X, int a_Y, int a_Delta, bool a_Ctrl) { if (a_Delta == 0) return; // Zoom int delta = -a_Delta / abs(a_Delta); if (delta < m_MinWheelDelta) m_MinWheelDelta = delta; if (delta > m_MaxWheelDelta) m_MaxWheelDelta = delta; float mousex = (float)a_X; float worldx; float worldy; ScreenToWorld(a_X, a_Y, worldx, worldy); m_MouseRatio = (double)mousex / (double)getWidth(); static float zoomRatio = 0.1f; bool zoomWidth = !a_Ctrl; if (zoomWidth) { m_TimeGraph.ZoomTime((float)delta, m_MouseRatio); m_WheelMomentum = delta * m_WheelMomentum < 0 ? 0.f : m_WheelMomentum + (float)delta; } else { float zoomInc = zoomRatio * m_DesiredWorldHeight; m_DesiredWorldHeight += delta * zoomInc; float worldMin, worldMax; m_TimeGraph.GetWorldMinMax(worldMin, worldMax); m_WorldTopLeftX = clamp(m_WorldTopLeftX, worldMin, worldMax - m_WorldWidth); m_WorldTopLeftY = clamp(m_WorldTopLeftY, -FLT_MAX, m_WorldMaxY); UpdateSceneBox(); } Orbit_ImGui_ScrollCallback(this, -delta); m_CanHover = true; NeedsUpdate(); } //----------------------------------------------------------------------------- void CaptureWindow::KeyPressed(unsigned int a_KeyCode, bool a_Ctrl, bool a_Shift, bool a_Alt) { UpdateSpecialKeys(a_Ctrl, a_Shift, a_Alt); ScopeImguiContext state(m_ImGuiContext); if (!m_ImguiActive) { switch (a_KeyCode) { case ' ': ZoomAll(); break; case 'C': #ifdef __linux__ LinuxUtils::DumpClocks(); #endif break; case 'A': Pan(0.1f); break; case 'D': Pan(-0.1f); break; case 'W': Zoom(1); break; case 'S': Zoom(-1); break; case 'F': m_DrawFilter = !m_DrawFilter; break; case 'I': m_DrawStats = !m_DrawStats; break; case 'H': m_DrawHelp = !m_DrawHelp; break; case 'X': GOrbitApp->ToggleCapture(); #ifdef __linux__ ZoomAll(); #endif break; case 'O': if (a_Ctrl) { m_TextRenderer.ToggleDrawOutline(); } break; case 'P': #ifdef _WIN32 GOrbitApp->LoadSystrace( "C:/Users/pierr/Downloads/perf_traces/systrace_tutorial.html"); #else GOrbitApp->LoadSystrace( "/home/pierric/perf_traces/systrace_tutorial.html"); #endif break; case 'M': m_DrawMemTracker = !m_DrawMemTracker; break; case 'K': SendProcess(); break; case 18: // Left m_TimeGraph.OnLeft(); break; case 20: // Right m_TimeGraph.OnRight(); break; case 19: // Up m_TimeGraph.OnUp(); break; case 21: // Down m_TimeGraph.OnDown(); break; } } ImGuiIO& io = ImGui::GetIO(); io.KeyCtrl = a_Ctrl; io.KeyShift = a_Shift; io.KeyAlt = a_Alt; Orbit_ImGui_KeyCallback(this, a_KeyCode, true); NeedsRedraw(); } //----------------------------------------------------------------------------- std::wstring GOTO_CALLSTACK = L"Go to Callstack"; std::wstring GOTO_SOURCE = L"Go to Source"; //----------------------------------------------------------------------------- std::vector<std::wstring> CaptureWindow::GetContextMenu() { static std::vector<std::wstring> menu = {GOTO_CALLSTACK, GOTO_SOURCE}; static std::vector<std::wstring> emptyMenu; TextBox* selection = Capture::GSelectedTextBox; return selection && !selection->GetTimer().IsCoreActivity() ? menu : emptyMenu; } //----------------------------------------------------------------------------- void CaptureWindow::OnContextMenu(const std::wstring& a_Action, int /*a_MenuIndex*/) { if (Capture::GSelectedTextBox) { if (a_Action == GOTO_SOURCE) { GOrbitApp->GoToCode( Capture::GSelectedTextBox->GetTimer().m_FunctionAddress); } else if (a_Action == GOTO_CALLSTACK) { GOrbitApp->GoToCallstack(); } } } //----------------------------------------------------------------------------- void CaptureWindow::ToggleSampling() { if (Capture::GIsSampling) { Capture::StopSampling(); } else if (!GTimerManager->m_IsRecording) { Capture::StartSampling(); } } //----------------------------------------------------------------------------- void CaptureWindow::OnCaptureStarted() { m_DesiredWorldWidth = (float)m_Width; m_DesiredWorldHeight = (float)m_Height; m_TimeGraph.ZoomAll(); NeedsRedraw(); } //----------------------------------------------------------------------------- void CaptureWindow::ResetHoverTimer() { m_HoverTimer.Reset(); m_CanHover = true; } //----------------------------------------------------------------------------- void CaptureWindow::Draw() { m_WorldMaxY = 1.5f * ScreenToWorldHeight((int)m_Slider.GetPixelHeight()); if (Capture::IsCapturing()) { ZoomAll(); } m_TimeGraph.Draw(m_Picking); if (m_SelectStart[0] != m_SelectStop[0]) { TickType minTime = std::min(m_TimeStart, m_TimeStop); TickType maxTime = std::max(m_TimeStart, m_TimeStop); float from = m_TimeGraph.GetWorldFromTick(minTime); float to = m_TimeGraph.GetWorldFromTick(maxTime); double micros = MicroSecondsFromTicks(minTime, maxTime); float sizex = to - from; Vec2 pos(from, m_WorldTopLeftY - m_WorldHeight); Vec2 size(sizex, m_WorldHeight); std::string time = GetPrettyTime(micros * 0.001); TextBox box(pos, size, time, Color(0, 128, 0, 128)); box.SetTextY(m_SelectStop[1]); box.Draw(m_TextRenderer, -FLT_MAX, true, true); } if (!m_Picking && !m_IsHovering) { DrawStatus(); RenderTimeBar(); // Vertical line glColor4f(0, 1, 0, 0.5f); glBegin(GL_LINES); glVertex3f(m_MouseX, m_WorldTopLeftY, Z_VALUE_TEXT); glVertex3f(m_MouseX, m_WorldTopLeftY - m_WorldHeight, Z_VALUE_TEXT); glEnd(); } } //----------------------------------------------------------------------------- void CaptureWindow::DrawScreenSpace() { double timeSpan = m_TimeGraph.GetSessionTimeSpanUs(); Color col = m_Slider.GetBarColor(); float height = m_Slider.GetPixelHeight(); float canvasHeight = (float)getHeight(); float z = GlCanvas::Z_VALUE_TEXT_UI_BG; // Top bar glColor4ubv(&col[0]); glBegin(GL_QUADS); glVertex3f(0, canvasHeight, z); glVertex3f((float)getWidth(), canvasHeight, z); glVertex3f((float)getWidth(), canvasHeight - height, z); glVertex3f(0, canvasHeight - height, z); glEnd(); // Time bar if (m_TimeGraph.GetSessionTimeSpanUs() > 0) { glColor4ub(70, 70, 70, 200); glBegin(GL_QUADS); glVertex3f(0, height, z); glVertex3f((float)getWidth(), height, z); glVertex3f((float)getWidth(), 2 * height, z); glVertex3f(0, 2 * height, z); glEnd(); } if (timeSpan > 0) { double start = m_TimeGraph.GetMinTimeUs(); double stop = m_TimeGraph.GetMaxTimeUs(); double width = stop - start; double maxStart = timeSpan - width; double ratio = Capture::IsCapturing() ? 1 : (maxStart != 0 ? start / maxStart : 0); m_Slider.SetSliderRatio((float)ratio); m_Slider.SetSliderWidthRatio(float(width / timeSpan)); m_Slider.Draw(this, m_Picking); float verticalRatio = m_WorldHeight / m_TimeGraph.GetThreadTotalHeight(); if (verticalRatio < 1.f) { m_VerticalSlider.SetSliderWidthRatio(verticalRatio); m_VerticalSlider.Draw(this, m_Picking); } } } //----------------------------------------------------------------------------- void CaptureWindow::OnDrag(float a_Ratio) { m_TimeGraph.OnDrag(a_Ratio); NeedsUpdate(); } //----------------------------------------------------------------------------- void CaptureWindow::OnVerticalDrag(float a_Ratio) { float min = m_WorldMaxY; float max = m_WorldHeight - m_TimeGraph.GetThreadTotalHeight(); float range = max - min; m_WorldTopLeftY = min + a_Ratio * range; NeedsUpdate(); } //----------------------------------------------------------------------------- void CaptureWindow::UpdateVerticalSlider() { float min = m_WorldMaxY; float max = m_WorldHeight - m_TimeGraph.GetThreadTotalHeight(); float ratio = (m_WorldTopLeftY - min) / (max - min); m_VerticalSlider.SetSliderRatio(ratio); } //----------------------------------------------------------------------------- void CaptureWindow::NeedsUpdate() { m_TimeGraph.NeedsUpdate(); m_NeedsRedraw = true; } //----------------------------------------------------------------------------- float CaptureWindow::GetTopBarTextY() { return m_Slider.GetPixelHeight() * 0.5f + (float)m_TextRenderer.GetStringHeight("FpjT_H") * 0.5f; } //----------------------------------------------------------------------------- void CaptureWindow::DrawStatus() { float iconSize = m_Slider.GetPixelHeight(); int s_PosX = (int)iconSize; float s_PosY = GetTopBarTextY(); static int s_IncY = 20; static Color s_Color(255, 255, 255, 255); int PosX = getWidth() - s_PosX; int PosY = (int)s_PosY; int LeftY = (int)s_PosY; m_TextRenderer.AddText2D(" press 'H'", s_PosX, LeftY, Z_VALUE_TEXT_UI, s_Color); LeftY += s_IncY; if (Capture::GInjected) { std::string injectStr = absl::StrFormat(" %s", Capture::GInjectedProcess.c_str()); m_ProcessX = m_TextRenderer.AddText2D(injectStr.c_str(), PosX, PosY, Z_VALUE_TEXT_UI, s_Color, -1, true); PosY += s_IncY; } if (Capture::GIsTesting) { m_TextRenderer.AddText2D("TESTING", PosX, PosY, Z_VALUE_TEXT_UI, s_Color, -1, true); PosY += s_IncY; } } //----------------------------------------------------------------------------- void CaptureWindow::RenderUI() { ScopeImguiContext state(m_ImGuiContext); Orbit_ImGui_NewFrame(this); if (m_DrawStats) { m_StatsWindow.Clear(); m_StatsWindow.AddLine(VAR_TO_ANSI(m_Width)); m_StatsWindow.AddLine(VAR_TO_ANSI(m_Height)); m_StatsWindow.AddLine(VAR_TO_ANSI(m_DesiredWorldHeight)); m_StatsWindow.AddLine(VAR_TO_ANSI(m_DesiredWorldWidth)); m_StatsWindow.AddLine(VAR_TO_ANSI(m_WorldHeight)); m_StatsWindow.AddLine(VAR_TO_ANSI(m_WorldWidth)); m_StatsWindow.AddLine(VAR_TO_ANSI(m_WorldTopLeftX)); m_StatsWindow.AddLine(VAR_TO_ANSI(m_WorldTopLeftY)); m_StatsWindow.AddLine(VAR_TO_ANSI(m_WorldMinWidth)); /* m_StatsWindow.AddLog( VAR_TO_CHAR( GTimerManager->m_NumTimersFromPreviousSession ) ); m_StatsWindow.AddLog( VAR_TO_CHAR( GTimerManager->m_NumFlushedTimers ) ); m_StatsWindow.AddLog( VAR_TO_CHAR( Capture::GNumMessagesFromPreviousSession ) ); m_StatsWindow.AddLog( VAR_TO_CHAR( Capture::GNumTargetFlushedEntries ) ); m_StatsWindow.AddLog( VAR_TO_CHAR( Capture::GNumTargetFlushedTcpPackets ) ); m_StatsWindow.AddLog( VAR_TO_CHAR( GTimerManager->m_NumQueuedEntries ) ); m_StatsWindow.AddLog( VAR_TO_CHAR( GTimerManager->m_NumQueuedMessages) ); m_StatsWindow.AddLog( VAR_TO_CHAR( GTimerManager->m_NumQueuedTimers) ); m_StatsWindow.AddLog( VAR_TO_CHAR( m_SelectStart[0] ) ); m_StatsWindow.AddLog( VAR_TO_CHAR( m_SelectStop[0] ) ); m_StatsWindow.AddLog( VAR_TO_CHAR( m_TimeGraph.m_CurrentTimeWindow ) ); m_StatsWindow.AddLog( VAR_TO_CHAR( Capture::GMaxTimersAtOnce ) ); m_StatsWindow.AddLog( VAR_TO_CHAR( Capture::GNumTimersAtOnce ) ); m_StatsWindow.AddLog( VAR_TO_CHAR( Capture::GNumTargetQueuedEntries ) ); m_StatsWindow.AddLog( VAR_TO_CHAR( m_MousePosX ) ); m_StatsWindow.AddLog( VAR_TO_CHAR( m_MousePosY ) );*/ m_StatsWindow.AddLine(VAR_TO_ANSI(Capture::GNumContextSwitches)); m_StatsWindow.AddLine(VAR_TO_ANSI(Capture::GNumLinuxEvents)); m_StatsWindow.AddLine(VAR_TO_ANSI(Capture::GNumProfileEvents)); m_StatsWindow.AddLine(VAR_TO_ANSI(Capture::GNumInstalledHooks)); m_StatsWindow.AddLine(VAR_TO_ANSI(Capture::GSelectedFunctionsMap.size())); m_StatsWindow.AddLine(VAR_TO_ANSI(Capture::GVisibleFunctionsMap.size())); m_StatsWindow.AddLine(VAR_TO_ANSI(m_TimeGraph.GetNumDrawnTextBoxes())); m_StatsWindow.AddLine(VAR_TO_ANSI(m_TimeGraph.GetNumTimers())); m_StatsWindow.AddLine(VAR_TO_ANSI(m_TimeGraph.GetThreadTotalHeight())); #ifdef WIN32 for (std::string& line : GTcpServer->GetStats()) { m_StatsWindow.AddLine(line); } bool hasConnection = GTcpServer->HasConnection(); m_StatsWindow.AddLine(VAR_TO_ANSI(hasConnection)); #else m_StatsWindow.AddLine( VAR_TO_ANSI(GEventTracer.GetEventBuffer().GetCallstacks().size())); m_StatsWindow.AddLine( VAR_TO_ANSI(GEventTracer.GetEventBuffer().GetNumEvents())); #endif m_StatsWindow.Draw("Capture Stats", &m_DrawStats); } if (m_DrawHelp) { RenderHelpUi(); if (m_FirstHelpDraw) { // Redraw so that Imgui resizes the // window properly on first draw NeedsRedraw(); m_FirstHelpDraw = false; } } if (m_DrawFilter) { RenderThreadFilterUi(); } if (m_DrawMemTracker && !m_DrawHelp) { RenderMemTracker(); } // Rendering glViewport(0, 0, getWidth(), getHeight()); ImGui::Render(); RenderBar(); } //----------------------------------------------------------------------------- void CaptureWindow::RenderText() { if (!m_Picking) { m_TimeGraph.DrawText(); } } //----------------------------------------------------------------------------- void ColorToFloat(Color a_Color, float* o_Float) { for (int i = 0; i < 4; ++i) { o_Float[i] = (float)a_Color[i] / 255.f; } } //----------------------------------------------------------------------------- void CaptureWindow::RenderHelpUi() { float barHeight = m_Slider.GetPixelHeight(); ImGui::SetNextWindowPos(ImVec2(0, barHeight * 1.5f)); ImVec4 color(1.f, 0, 0, 1.f); ColorToFloat(m_Slider.GetBarColor(), &color.x); ImGui::PushStyleColor(ImGuiCol_WindowBg, color); if (!ImGui::Begin("Help Overlay", &m_DrawHelp, ImVec2(0, 0), 1.f, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings)) { ImGui::PopStyleColor(); ImGui::End(); return; } ImGui::Text("Start/Stop capture: 'X'"); ImGui::Text("Time zoom: scroll or CTRL+right-click/drag"); ImGui::Text("Y axis zoom: CTRL+scroll"); ImGui::Text("Zoom last 2 seconds: 'A'"); ImGui::Separator(); ImGui::Text("Icons:"); extern GLuint GTextureInjected; extern GLuint GTextureTimer; extern GLuint GTextureHelp; extern GLuint GTextureRecord; float size = m_Slider.GetPixelHeight(); ImGui::Image((void*)(DWORD64)GTextureInjected, ImVec2(size, size), ImVec2(0, 0), ImVec2(1, 1), ImColor(255, 255, 255, 255), ImColor(255, 255, 255, 128)); ImGui::SameLine(); ImGui::Text("Injected in process"); ImGui::Image((void*)(DWORD64)GTextureTimer, ImVec2(size, size), ImVec2(0, 0), ImVec2(1, 1), ImColor(255, 255, 255, 255), ImColor(255, 255, 255, 128)); ImGui::SameLine(); ImGui::Text("Capture time"); ImGui::Image((void*)(DWORD64)GTextureRecord, ImVec2(size, size), ImVec2(0, 0), ImVec2(1, 1), ImColor(255, 255, 255, 255), ImColor(255, 255, 255, 128)); ImGui::SameLine(); ImGui::Text("Recording"); ImGui::Image((void*)(DWORD64)GTextureHelp, ImVec2(size, size), ImVec2(0, 0), ImVec2(1, 1), ImColor(255, 255, 255, 255), ImColor(255, 255, 255, 128)); ImGui::SameLine(); ImGui::Text("Help"); ImGui::End(); ImGui::PopStyleColor(); } //----------------------------------------------------------------------------- void CaptureWindow::RenderThreadFilterUi() { float barHeight = m_Slider.GetPixelHeight(); ImGui::SetNextWindowPos(ImVec2(0, barHeight * 1.5f)); ImGui::SetNextWindowSize(ImVec2(barHeight * 50.f, barHeight * 3.f)); ImVec4 color(1.f, 0, 0, 1.f); ColorToFloat(m_Slider.GetBarColor(), &color.x); ImGui::PushStyleColor(ImGuiCol_WindowBg, color); if (!ImGui::Begin("Thread Filter", &m_DrawHelp, ImVec2(0, 0), 1.f, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings)) { ImGui::PopStyleColor(); ImGui::End(); return; } static char filter[128] = ""; ImGui::Text("Thread Filter"); ImGui::InputText("", filter, IM_ARRAYSIZE(filter)); GCurrentTimeGraph->SetThreadFilter(filter); ImGui::End(); ImGui::PopStyleColor(); } //----------------------------------------------------------------------------- void CaptureWindow::RenderMemTracker() { float barHeight = m_Slider.GetPixelHeight(); ImGui::SetNextWindowPos(ImVec2(0, barHeight * 1.5f)); ImVec4 color(1.f, 0, 0, 1.f); ColorToFloat(m_Slider.GetBarColor(), &color.x); ImGui::PushStyleColor(ImGuiCol_WindowBg, color); bool dummy = true; if (!ImGui::Begin( "MemTracker Overlay", &dummy, ImVec2(0, 0), 1.f, ImGuiWindowFlags_NoTitleBar /*| ImGuiWindowFlags_NoResize*/ | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings)) { ImGui::PopStyleColor(); ImGui::End(); return; } ImGui::Text("=== Memory Tracker ==="); const MemoryTracker& memTracker = m_TimeGraph.GetMemoryTracker(); if (memTracker.NumAllocatedBytes() == 0) { std::string str = VAR_TO_ANSI(memTracker.NumAllocatedBytes()) + std::string(" "); ImGui::Text("%s", str.c_str()); ImGui::Text("%s", VAR_TO_ANSI(memTracker.NumFreedBytes())); ImGui::Text("%s", VAR_TO_ANSI(memTracker.NumLiveBytes())); } else { ImGui::Text("%s", VAR_TO_ANSI(memTracker.NumAllocatedBytes())); ImGui::Text("%s", VAR_TO_ANSI(memTracker.NumFreedBytes())); ImGui::Text("%s", VAR_TO_ANSI(memTracker.NumLiveBytes())); } ImGui::End(); ImGui::PopStyleColor(); } //----------------------------------------------------------------------------- void DrawTexturedSquare(GLuint a_TextureId, float a_Size, float a_X, float a_Y) { glUseProgram(0); glColor4ub(255, 255, 255, 255); glEnable(GL_TEXTURE_2D); glDisable(GL_COLOR_MATERIAL); glBindTexture(GL_TEXTURE_2D, a_TextureId); glBegin(GL_QUADS); glTexCoord2f(0.f, 1.f); glVertex3f(a_X, a_Y, 0.f); glTexCoord2f(0.f, 0.f); glVertex3f(a_X, a_Y + a_Size, 0.f); glTexCoord2f(1.f, 0.f); glVertex3f(a_X + a_Size, a_Y + a_Size, 0.f); glTexCoord2f(1.f, 1.f); glVertex3f(a_X + a_Size, a_Y, 0.f); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); } //----------------------------------------------------------------------------- void CaptureWindow::RenderBar() { extern GLuint GTextureInjected; extern GLuint GTextureTimer; extern GLuint GTextureHelp; extern GLuint GTextureRecord; float barHeight = m_Slider.GetPixelHeight(); float size = barHeight; float h = (float)getHeight(); float y = h - barHeight; float timerX = getWidth() / 2.f; DrawTexturedSquare(GTextureInjected, size, m_ProcessX - size, y); DrawTexturedSquare(GTextureTimer, size, timerX, y); DrawTexturedSquare(GTextureHelp, size, 0, y); if (Capture::IsCapturing()) { DrawTexturedSquare(GTextureRecord, size, timerX - size, y); } double timeSpan = m_TimeGraph.GetSessionTimeSpanUs(); timerX += size; m_TextRenderer.AddText2D( absl::StrFormat("%s", GetPrettyTime(timeSpan * 0.001).c_str()).c_str(), (int)timerX, (int)GetTopBarTextY(), GlCanvas::Z_VALUE_TEXT_UI, Color(255, 255, 255, 255)); /*m_TextRenderer.AddText2D(Format("%s", GetPrettyTime(m_TimeGraph.GetCurrentTimeSpanUs()*0.001).c_str()).c_str() , timerX , 100 , GlCanvas::Z_VALUE_TEXT_UI , Color(255, 255, 255, 255));*/ } //----------------------------------------------------------------------------- inline double GetIncrementMs(double a_MilliSeconds) { const double Day = 24 * 60 * 60 * 1000; const double Hour = 60 * 60 * 1000; const double Minute = 60 * 1000; const double Second = 1000; const double Milli = 1; const double Micro = 0.001; const double Nano = 0.000001; std::string res; if (a_MilliSeconds < Micro) return Nano; else if (a_MilliSeconds < Milli) return Micro; else if (a_MilliSeconds < Second) return Milli; else if (a_MilliSeconds < Minute) return Second; else if (a_MilliSeconds < Hour) return Minute; else if (a_MilliSeconds < Day) return Hour; else return Day; } //----------------------------------------------------------------------------- void CaptureWindow::RenderTimeBar() { static int numTimePoints = 10; if (m_TimeGraph.GetSessionTimeSpanUs() > 0) { double millis = m_TimeGraph.GetCurrentTimeSpanUs() * 0.001; double incr = millis / float(numTimePoints - 1); double unit = GetIncrementMs(incr); double normInc = (double((int)((incr + unit) / unit))) * unit; double startMs = m_TimeGraph.GetMinTimeUs() * 0.001; double normStartUs = 1000.0 * (double(int(startMs / normInc))) * normInc; static int pixelMargin = 2; int screenY = getHeight() - (int)m_Slider.GetPixelHeight() - pixelMargin; float dummy, worldY; ScreenToWorld(0, screenY, dummy, worldY); float height = ScreenToWorldHeight((int)GParams.m_FontSize + pixelMargin); float xMargin = ScreenToworldWidth(4); for (int i = 0; i < numTimePoints; ++i) { double currentMicros = normStartUs + double(i) * 1000 * normInc; if (currentMicros < 0) continue; double currentMillis = currentMicros * 0.001; std::string text = GetPrettyTime(currentMillis); float worldX = m_TimeGraph.GetWorldFromUs(currentMicros); m_TextRenderer.AddText(text.c_str(), worldX + xMargin, worldY, GlCanvas::Z_VALUE_TEXT_UI, Color(255, 255, 255, 255)); glColor4f(1.f, 1.f, 1.f, 1.f); glBegin(GL_LINES); glVertex3f(worldX, worldY, Z_VALUE_UI); glVertex3f(worldX, worldY + height, Z_VALUE_UI); glEnd(); } } } //----------------------------------------------------------------------------- void CaptureWindow::OnTimerAdded(Timer& a_Timer) { m_TimeGraph.ProcessTimer(a_Timer); } //----------------------------------------------------------------------------- void CaptureWindow::OnContextSwitchAdded(const ContextSwitch& a_CS) { m_TimeGraph.AddContextSwitch(a_CS); } //----------------------------------------------------------------------------- void CaptureWindow::SendProcess() { if (Capture::GTargetProcess) { std::string processData = SerializeObjectHumanReadable(*Capture::GTargetProcess); PRINT_VAR(processData); GTcpClient->Send(Msg_RemoteProcess, (void*)processData.data(), processData.size()); } }
31.127163
80
0.588083
[ "render", "vector" ]
93437c26adab983f06aec64e4d0d2bd6990ebc91
1,095
cpp
C++
source/FAST/Examples/DataImport/importLineMeshFromFile.cpp
andreped/FAST
361819190ea0ae5a2f068e7bd808a1c70af5a171
[ "BSD-2-Clause" ]
null
null
null
source/FAST/Examples/DataImport/importLineMeshFromFile.cpp
andreped/FAST
361819190ea0ae5a2f068e7bd808a1c70af5a171
[ "BSD-2-Clause" ]
null
null
null
source/FAST/Examples/DataImport/importLineMeshFromFile.cpp
andreped/FAST
361819190ea0ae5a2f068e7bd808a1c70af5a171
[ "BSD-2-Clause" ]
null
null
null
/** * @example importLineMeshFromFile.cpp * An example of importing and visualizing a mesh containing lines from a file using the VTKMeshFileImporter */ #include <FAST/Tools/CommandLineParser.hpp> #include "FAST/Importers/VTKMeshFileImporter.hpp" #include "FAST/Visualization/LineRenderer/LineRenderer.hpp" #include "FAST/Visualization/SimpleWindow.hpp" using namespace fast; int main(int argc, char** argv) { CommandLineParser parser("Import line set from file"); parser.addPositionVariable(1, "filename", Config::getTestDataPath() + "centerline.vtk"); parser.parse(argc, argv); // Import line set from vtk file auto importer = VTKMeshFileImporter::create(parser.get("filename")); // Renderer auto renderer = LineRenderer::create()->connect(importer); // Setup window auto window = SimpleWindow3D::create()->connect(renderer); #ifdef FAST_CONTINUOUS_INTEGRATION // This will automatically close the window after 5 seconds, used for CI testing window->setTimeout(5*1000); #endif // Run entire pipeline and display window window->run(); }
34.21875
108
0.741553
[ "mesh" ]
93497e8bd6a2930bc1b3bec1ca974a75a85e39b9
930
cpp
C++
agario_info/src/imageFromDisplay.cpp
albertpumarola/QLearning-NAO_plays_Agario
7bb556fc65c8e4e24b1a372268932cc97bd08be0
[ "MIT" ]
22
2016-11-15T08:51:38.000Z
2021-12-30T03:26:48.000Z
agario_info/src/imageFromDisplay.cpp
albertpumarola/QLearning-NAO_plays_Agario
7bb556fc65c8e4e24b1a372268932cc97bd08be0
[ "MIT" ]
2
2016-11-29T08:43:38.000Z
2018-04-15T14:09:39.000Z
agario_info/src/imageFromDisplay.cpp
albertpumarola/QLearning-NAO_plays_Agario
7bb556fc65c8e4e24b1a372268932cc97bd08be0
[ "MIT" ]
3
2017-04-27T16:13:37.000Z
2020-01-24T19:12:54.000Z
#include "imageFromDisplay.h" ImageFromDisplay::ImageFromDisplay() {} cv::Mat ImageFromDisplay::getImage() { std::vector<std::uint8_t> pixels; int height, width, bpp; height = width = bpp = 0; captureImage(pixels, width, height); if (width && height) return cv::Mat(height, width, CV_8UC4, &pixels[0]); else return cv::Mat(); } void ImageFromDisplay::captureImage(std::vector<uint8_t>& pixels, int& width, int& height) { Display* display = XOpenDisplay(nullptr); Window root = DefaultRootWindow(display); XWindowAttributes attributes = {0}; XGetWindowAttributes(display, root, &attributes); width = attributes.width; height = attributes.height; XImage* img = XGetImage(display, root, 0, 0, width, height, AllPlanes, ZPixmap); pixels.resize(width * height * 4); memcpy(&pixels[0], img->data, pixels.size()); XFree(img); XCloseDisplay(display); }
25.833333
77
0.670968
[ "vector" ]
93524e9c211cc465667580290903ec647e5ba308
45,919
cxx
C++
Modules/Core/Metadata/src/otbFormosatImageMetadataInterface.cxx
yyxgiser/OTB
2782a5838a55890769cdc6bc3bd900b2e9f6c5cb
[ "Apache-2.0" ]
null
null
null
Modules/Core/Metadata/src/otbFormosatImageMetadataInterface.cxx
yyxgiser/OTB
2782a5838a55890769cdc6bc3bd900b2e9f6c5cb
[ "Apache-2.0" ]
null
null
null
Modules/Core/Metadata/src/otbFormosatImageMetadataInterface.cxx
yyxgiser/OTB
2782a5838a55890769cdc6bc3bd900b2e9f6c5cb
[ "Apache-2.0" ]
1
2020-10-15T09:37:30.000Z
2020-10-15T09:37:30.000Z
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbFormosatImageMetadataInterface.h" #include "otbMacro.h" #include "otbMath.h" #include "itkMetaDataObject.h" #include "otbImageKeywordlist.h" #include "otbStringUtils.h" namespace otb { FormosatImageMetadataInterface::FormosatImageMetadataInterface() { } bool FormosatImageMetadataInterface::CanRead() const { std::string sensorID = GetSensorID(); if (sensorID.find("Formosat") != std::string::npos) return true; else return false; } std::string FormosatImageMetadataInterface::GetInstrument() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (imageKeywordlist.HasKey("support_data.instrument")) { std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.instrument"); return valueString; } return ""; } unsigned int FormosatImageMetadataInterface::GetInstrumentIndex() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (imageKeywordlist.HasKey("support_data.instrument_index")) { std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.instrument_index"); unsigned int value = atoi(valueString.c_str()); return value; } return -1; // Invalid value } FormosatImageMetadataInterface::VariableLengthVectorType FormosatImageMetadataInterface::GetSolarIrradiance() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } std::vector<double> outputValues; if (imageKeywordlist.HasKey("support_data.solar_irradiance")) { std::vector<std::string> outputValuesString; std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.solar_irradiance"); boost::trim(valueString); boost::split(outputValuesString, valueString, boost::is_any_of(" ")); for (unsigned int i = 0; i < outputValuesString.size(); ++i) { outputValues.push_back(atof(outputValuesString[i].c_str())); } } VariableLengthVectorType outputValuesVariableLengthVector; outputValuesVariableLengthVector.SetSize(outputValues.size()); outputValuesVariableLengthVector.Fill(0); // In the case of SPOT, the bands are in a different order: // XS3, XS2. XS1, SWIR in the tif file. if (outputValues.size() == 1) { // this is a PAN image outputValuesVariableLengthVector[0] = outputValues[0]; } else if (outputValues.size() == 4) { outputValuesVariableLengthVector[0] = outputValues[2]; outputValuesVariableLengthVector[1] = outputValues[1]; outputValuesVariableLengthVector[2] = outputValues[0]; outputValuesVariableLengthVector[3] = outputValues[3]; } else { itkExceptionMacro("Invalid Solar Irradiance"); } return outputValuesVariableLengthVector; } int FormosatImageMetadataInterface::GetDay() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.image_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.image_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-")); if (outputValues.size() <= 2) itkExceptionMacro(<< "Invalid Day"); int value = atoi(outputValues[2].c_str()); return value; } int FormosatImageMetadataInterface::GetMonth() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.image_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.image_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-")); if (outputValues.size() <= 2) itkExceptionMacro(<< "Invalid Month"); int value = atoi(outputValues[1].c_str()); return value; } int FormosatImageMetadataInterface::GetYear() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.image_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.image_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-")); if (outputValues.size() <= 2) itkExceptionMacro(<< "Invalid Year"); int value = atoi(outputValues[0].c_str()); return value; } int FormosatImageMetadataInterface::GetHour() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.image_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.image_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-")); if (outputValues.size() < 4) itkExceptionMacro(<< "Invalid Hour"); int value = atoi(outputValues[3].c_str()); return value; } int FormosatImageMetadataInterface::GetMinute() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.image_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.image_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-")); if (outputValues.size() < 5) itkExceptionMacro(<< "Invalid Minute"); int value = atoi(outputValues[4].c_str()); return value; } int FormosatImageMetadataInterface::GetProductionDay() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.production_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.production_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-")); if (outputValues.size() <= 2) itkExceptionMacro(<< "Invalid Day"); int value = atoi(outputValues[2].c_str()); return value; } int FormosatImageMetadataInterface::GetProductionMonth() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.production_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.production_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-")); if (outputValues.size() <= 2) itkExceptionMacro(<< "Invalid Month"); int value = atoi(outputValues[1].c_str()); return value; } int FormosatImageMetadataInterface::GetProductionYear() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.production_date")) { return -1; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.production_date"); std::vector<std::string> outputValues; boost::split(outputValues, valueString, boost::is_any_of(" T:-")); if (outputValues.size() <= 2) itkExceptionMacro(<< "Invalid Year"); int value = atoi(outputValues[0].c_str()); return value; } FormosatImageMetadataInterface::VariableLengthVectorType FormosatImageMetadataInterface::GetPhysicalBias() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } std::vector<double> outputValues; if (imageKeywordlist.HasKey("support_data.physical_bias")) { std::vector<std::string> outputValuesString; std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.physical_bias"); boost::trim(valueString); boost::split(outputValuesString, valueString, boost::is_any_of(" ")); for (unsigned int i = 0; i < outputValuesString.size(); ++i) { outputValues.push_back(atof(outputValuesString[i].c_str())); } } VariableLengthVectorType outputValuesVariableLengthVector; outputValuesVariableLengthVector.SetSize(outputValues.size()); outputValuesVariableLengthVector.Fill(0); // In the case of FORMOSAT-2, the bands are in a different order: // XS3, XS2. XS1, SWIR in the tif file. if (outputValues.size() == 1) { // this is a PAN image outputValuesVariableLengthVector[0] = outputValues[0]; } else if (outputValues.size() == 4) { outputValuesVariableLengthVector[0] = outputValues[2]; outputValuesVariableLengthVector[1] = outputValues[1]; outputValuesVariableLengthVector[2] = outputValues[0]; outputValuesVariableLengthVector[3] = outputValues[3]; } else { itkExceptionMacro("Invalid Physical Bias"); } return outputValuesVariableLengthVector; } FormosatImageMetadataInterface::VariableLengthVectorType FormosatImageMetadataInterface::GetPhysicalGain() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } std::vector<double> outputValues; if (imageKeywordlist.HasKey("support_data.physical_gain")) { std::vector<std::string> outputValuesString; std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.physical_gain"); boost::trim(valueString); boost::split(outputValuesString, valueString, boost::is_any_of(" ")); for (unsigned int i = 0; i < outputValuesString.size(); ++i) { outputValues.push_back(atof(outputValuesString[i].c_str())); } } VariableLengthVectorType outputValuesVariableLengthVector; outputValuesVariableLengthVector.SetSize(outputValues.size()); outputValuesVariableLengthVector.Fill(0); // In the case of SPOT, the bands are in a different order: // XS3, XS2. XS1, SWIR in the tif file. if (outputValues.size() == 1) { // this is a PAN image outputValuesVariableLengthVector[0] = outputValues[0]; } else if (outputValues.size() == 4) { outputValuesVariableLengthVector[0] = outputValues[2]; outputValuesVariableLengthVector[1] = outputValues[1]; outputValuesVariableLengthVector[2] = outputValues[0]; outputValuesVariableLengthVector[3] = outputValues[3]; } else { itkExceptionMacro("Invalid Physical Gain"); } return outputValuesVariableLengthVector; } double FormosatImageMetadataInterface::GetSatElevation() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.incident_angle")) { return 0; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.incident_angle"); double value = 90 - atof(valueString.c_str()); return value; } double FormosatImageMetadataInterface::GetSatAzimuth() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } if (!imageKeywordlist.HasKey("support_data.incident_angle")) { return 0; } std::string valueString = imageKeywordlist.GetMetadataByKey("support_data.sat_azimuth_angle"); double satAz = atof(valueString.c_str()); // In some software version, a bug exists. // We have to check the version t correct the satellite azimuth angle contained in the metadata std::string softVersion = imageKeywordlist.GetMetadataByKey("support_data.software_version"); if ((softVersion == "R2P_02.03.P1") || (softVersion == "R2P_02.02") || (softVersion == "R2P_02.03")) { if (!imageKeywordlist.HasKey("support_data.viewing_angle_across_track")) { return 0; } if (!imageKeywordlist.HasKey("support_data.viewing_angle_along_track")) { return 0; } if (!imageKeywordlist.HasKey("support_data.scene_orientation")) { return 0; } valueString = imageKeywordlist.GetMetadataByKey("support_data.viewing_angle_across_track"); double viewingAngleAcrossTrack(atof(valueString.c_str())); valueString = imageKeywordlist.GetMetadataByKey("support_data.viewing_angle_along_track"); double viewingAngleAlongTrack(atof(valueString.c_str())); valueString = imageKeywordlist.GetMetadataByKey("support_data.scene_orientation"); double sceneOrientation(atof(valueString.c_str())); double alpha = std::atan(std::tan(viewingAngleAcrossTrack * CONST_PI_180) / std::tan(viewingAngleAlongTrack * CONST_PI_180)) * CONST_180_PI; if (viewingAngleAlongTrack < 0) { if (alpha > 0) { alpha = alpha - 180; } else { alpha = alpha + 180; } } alpha -= sceneOrientation; if (alpha > 0) { satAz += 180; } else { satAz = 180 - satAz; } } return satAz; } FormosatImageMetadataInterface::VariableLengthVectorType FormosatImageMetadataInterface::GetFirstWavelengths() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid metadata, no Formosat2 Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } VariableLengthVectorType wavel(1); wavel.Fill(0.); int nbBands = this->GetNumberOfBands(); std::string sensorId = this->GetSensorID(); // Panchromatic case if (nbBands == 1) { wavel.SetSize(1); // FIXME that's definitely NOT correct in a formosat file!!! if (sensorId == "SPOT4") wavel.Fill(0.610); else if (sensorId == "SPOT5") wavel.Fill(0.480); else itkExceptionMacro(<< "Invalid Formosat2 Sensor ID"); } else if (nbBands > 1 && nbBands < 5) { wavel.SetSize(4); // FIXME is that supposed to correspond to the bands in the files? wavel[0] = 0.500; wavel[1] = 0.610; wavel[2] = 0.780; wavel[3] = 1.580; } else itkExceptionMacro(<< "Invalid number of bands..."); return wavel; } FormosatImageMetadataInterface::VariableLengthVectorType FormosatImageMetadataInterface::GetLastWavelengths() const { const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid metadata, no Formosat2 Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } VariableLengthVectorType wavel(1); wavel.Fill(0.); int nbBands = this->GetNumberOfBands(); std::string sensorId = this->GetSensorID(); // Panchromatic case if (nbBands == 1) { wavel.SetSize(1); if (sensorId == "SPOT4") wavel.Fill(0.680); else if (sensorId == "SPOT5") wavel.Fill(0.710); else itkExceptionMacro(<< "Invalid Formosat2 Sensor ID"); } else if (nbBands > 1 && nbBands < 5) { // FIXME is that supposed to correspond to the bands in the files? wavel.SetSize(4); wavel[0] = 0.590; wavel[1] = 0.680; wavel[2] = 0.890; wavel[3] = 1.750; } else itkExceptionMacro(<< "Invalid number of bands..."); return wavel; } unsigned int FormosatImageMetadataInterface::BandIndexToWavelengthPosition(unsigned int i) const { otbMsgDevMacro(<< "Formosat2 detected: band 0 and 2 inverted"); if (i == 0) return 2; if (i == 2) return 0; return i; } std::vector<unsigned int> FormosatImageMetadataInterface::GetDefaultDisplay() const { std::vector<unsigned int> rgb(3); rgb[0] = 0; rgb[1] = 1; rgb[2] = 2; return rgb; } FormosatImageMetadataInterface::WavelengthSpectralBandVectorType FormosatImageMetadataInterface::GetSpectralSensitivity() const { WavelengthSpectralBandVectorType wavelengthSpectralBand = InternalWavelengthSpectralBandVectorType::New(); std::list<std::vector<float>> tmpSpectralBandList; const MetaDataDictionaryType& dict = this->GetMetaDataDictionary(); if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, no Formosat Image"); } ImageKeywordlistType imageKeywordlist; if (dict.HasKey(MetaDataKey::OSSIMKeywordlistKey)) { itk::ExposeMetaData<ImageKeywordlistType>(dict, MetaDataKey::OSSIMKeywordlistKey, imageKeywordlist); } int nbBands = this->GetNumberOfBands(); std::string sensorId = this->GetSensorID(); // Panchromatic case if (nbBands == 1) { const float b0[281] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.000219376f, 0.000219425f, 0.000231534f, 0.000284519f, 0.000550079f, 0.001f, 0.003f, 0.006f, 0.012f, 0.0235f, 0.035f, 0.043f, 0.0503893f, 0.0525f, 0.055f, 0.0565f, 0.058f, 0.059f, 0.059f, 0.0608594f, 0.061f, 0.0615f, 0.062f, 0.063f, 0.063f, 0.064f, 0.063f, 0.064f, 0.065f, 0.066f, 0.066f, 0.066f, 0.066f, 0.0675f, 0.069f, 0.0708104f, 0.0709615f, 0.0709001f, 0.071f, 0.0715f, 0.073f, 0.074f, 0.074f, 0.073f, 0.073f, 0.0735f, 0.075f, 0.0765f, 0.078f, 0.078f, 0.078f, 0.0785f, 0.0800145f, 0.0815f, 0.083f, 0.083f, 0.083f, 0.083f, 0.083f, 0.0835f, 0.085f, 0.0865f, 0.087f, 0.088f, 0.087f, 0.087f, 0.088f, 0.0885f, 0.0907023f, 0.0915f, 0.092f, 0.092f, 0.092f, 0.092f, 0.093f, 0.094f, 0.095f, 0.096f, 0.096f, 0.096f, 0.095f, 0.095f, 0.095f, 0.095f, 0.096f, 0.0975f, 0.098f, 0.099f, 0.099f, 0.098f, 0.098f, 0.0965f, 0.096f, 0.0965f, 0.098f, 0.0985f, 0.099f, 0.0995f, 0.099f, 0.0975f, 0.097f, 0.0955f, 0.095f, 0.095f, 0.095f, 0.0965f, 0.097f, 0.098f, 0.098f, 0.0975f, 0.097f, 0.096f, 0.095f, 0.095f, 0.094f, 0.094f, 0.095f, 0.0955f, 0.096f, 0.097f, 0.097f, 0.097f, 0.097f, 0.097f, 0.097f, 0.096f, 0.097f, 0.097f, 0.097f, 0.098f, 0.098f, 0.096f, 0.095f, 0.094f, 0.093f, 0.092f, 0.091f, 0.0905658f, 0.089f, 0.089f, 0.089f, 0.088f, 0.088f, 0.0875f, 0.087f, 0.086f, 0.085f, 0.084f, 0.083f, 0.0825f, 0.082f, 0.081f, 0.081f, 0.0804051f, 0.079f, 0.078f, 0.077f, 0.077f, 0.076f, 0.075f, 0.074f, 0.0735f, 0.073f, 0.0725f, 0.072f, 0.071f, 0.071f, 0.0704136f, 0.069f, 0.0685f, 0.068f, 0.067f, 0.066f, 0.0645f, 0.063f, 0.062f, 0.0607892f, 0.059f, 0.058f, 0.057f, 0.056f, 0.0545f, 0.052f, 0.0455f, 0.038f, 0.0286994f, 0.0202138f, 0.0125f, 0.007f, 0.004f, 0.002f, 0.001f, 0.000909856f, 0.000512159f, 0.000357051f, 0.00029112f, 0.000215752f, 0.000187213f, 0.000171918f, 0.000169724f, 0.000166392f, 0.000163058f, 0.000159726f, 0.000156393f, 0.000153061f, 0.000149728f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; // add panchromatic band to the temporary list const std::vector<float> vb0(b0, b0 + sizeof(b0) / sizeof(float)); tmpSpectralBandList.push_back(vb0); } else if (nbBands > 1 && nbBands < 5) { const float b1[281] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.000354959f, 0.000354603f, 0.000376745f, 0.000478212f, 0.0009718f, 0.002f, 0.005f, 0.0124297f, 0.024f, 0.0415f, 0.057f, 0.0685f, 0.074f, 0.074f, 0.076f, 0.0795695f, 0.082f, 0.084f, 0.083f, 0.0825f, 0.086f, 0.0910953f, 0.094f, 0.096f, 0.096f, 0.094f, 0.094f, 0.096f, 0.099f, 0.0995f, 0.099f, 0.098f, 0.095f, 0.092f, 0.095f, 0.0985f, 0.092f, 0.0695f, 0.037f, 0.025f, 0.009f, 0.0025f, 0.001f, 0.000847053f, 0.000588401f, 0.00051966f, 0.00050602f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}; const float b2[281] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.000324677f, 0.000326475f, 0.000331943f, 0.000386303f, 0.000447683f, 0.001f, 0.003f, 0.0045f, 0.012f, 0.0205f, 0.036f, 0.0615f, 0.075f, 0.081f, 0.082f, 0.0845f, 0.087f, 0.0885f, 0.088f, 0.087f, 0.086f, 0.0875f, 0.0908484f, 0.0925f, 0.094f, 0.094f, 0.093f, 0.0925f, 0.093f, 0.0955f, 0.097f, 0.098f, 0.099f, 0.099f, 0.099f, 0.099f, 0.099f, 0.099f, 0.095f, 0.0815f, 0.057f, 0.032f, 0.018f, 0.0112534f, 0.005f, 0.0015f, 0.000758484f, 0.000604297f, 0.000512471f, 0.000475316f, 0.000453283f, 0.00044559f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}; const float b3[281] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.000461752f, 0.001f, 0.001f, 0.003f, 0.006f, 0.013f, 0.0335f, 0.063f, 0.089f, 0.098f, 0.099f, 0.099f, 0.099f, 0.099f, 0.0985f, 0.097f, 0.0945f, 0.092f, 0.0906796f, 0.089f, 0.0907659f, 0.093f, 0.0965f, 0.1f, 0.097f, 0.091f, 0.0865f, 0.086f, 0.0910438f, 0.094f, 0.092f, 0.093f, 0.088f, 0.064f, 0.034f, 0.015f, 0.0075f, 0.006f, 0.0045f, 0.003f, 0.001f, 0.000607601f, 0.000202927f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}; const float b4[281] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.000481456f, 0.00071923f, 0.00098303f, 0.001f, 0.000947915f, 0.00090899f, 0.000887367f, 0.000576847f, 0.000470858f, 0.00052246f, 0.000713811f, 0.001f, 0.0015f, 0.003f, 0.005f, 0.008f, 0.0145f, 0.022f, 0.035f, 0.049f, 0.0595f, 0.075f, 0.0905f, 0.098f, 0.0995f, 0.097f, 0.093f, 0.091f, 0.0925f, 0.094f, 0.096f, 0.096f, 0.0955f, 0.094f, 0.092f, 0.0907811f, 0.089f, 0.088f, 0.088f, 0.088f, 0.088f, 0.088f, 0.0875f, 0.087f, 0.086f, 0.085f, 0.084f, 0.083f, 0.083f, 0.082f, 0.081f, 0.0806396f, 0.079f, 0.078f, 0.077f, 0.076f, 0.075f, 0.074f, 0.073f, 0.072f, 0.071f, 0.0700369f, 0.0685f, 0.067f, 0.0655f, 0.064f, 0.063f, 0.063f, 0.062f, 0.059f, 0.054f, 0.043f, 0.034f, 0.025f, 0.016f, 0.009f, 0.0055f, 0.003f, 0.0015f, 0.001f, 0.000691333f, 0.000432126f, 0.000356974f, 0.000265441f, 0.000219773f, 0.000195346f, 0.000192716f, 0.000188932f, 0.000185148f, 0.000181364f, 0.00017758f, 0.000173796f, 0.000170011f, 0.000166227f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}; // Add multispectral bands to the temporary list const std::vector<float> vb1(b1, b1 + sizeof(b1) / sizeof(float)); tmpSpectralBandList.push_back(vb1); const std::vector<float> vb2(b2, b2 + sizeof(b2) / sizeof(float)); tmpSpectralBandList.push_back(vb2); const std::vector<float> vb3(b3, b3 + sizeof(b3) / sizeof(float)); tmpSpectralBandList.push_back(vb3); const std::vector<float> vb4(b4, b4 + sizeof(b4) / sizeof(float)); tmpSpectralBandList.push_back(vb4); unsigned int j = 0; for (std::list<std::vector<float>>::const_iterator it = tmpSpectralBandList.begin(); it != tmpSpectralBandList.end(); ++it) { wavelengthSpectralBand->PushBack(FilterFunctionValues::New()); wavelengthSpectralBand->GetNthElement(j)->SetFilterFunctionValues(*it); wavelengthSpectralBand->GetNthElement(j)->SetMinSpectralValue(0.300); wavelengthSpectralBand->GetNthElement(j)->SetMaxSpectralValue(1.0); wavelengthSpectralBand->GetNthElement(j)->SetUserStep(0.0025); ++j; } } return wavelengthSpectralBand; } } // end namespace otb
39.6195
160
0.482567
[ "vector" ]
93563ae3980f967a34a17a4a5f9fd9f2a26adea7
20,479
cpp
C++
libcapgen/src/genetic.cpp
CaptorAB/filiphallqvistexjobb
31a270b1225ea6f3ab26da33b42dfa068ba9076f
[ "MIT" ]
2
2019-02-06T12:48:25.000Z
2019-02-06T19:47:48.000Z
libcapgen/src/genetic.cpp
CaptorAB/filiphallqvistexjobb
31a270b1225ea6f3ab26da33b42dfa068ba9076f
[ "MIT" ]
25
2019-04-17T11:59:42.000Z
2019-05-09T07:25:23.000Z
libcapgen/src/genetic.cpp
CaptorAB/filiphallqvistexjobb
31a270b1225ea6f3ab26da33b42dfa068ba9076f
[ "MIT" ]
null
null
null
#include <vector> #include <tuple> #include <cmath> #include <lib/random.h> #include <include/constants.h> #include <include/genetic.h> #include <include/normal.h> using Random = effolkronium::random_static; std::vector<double> parse_instrument_constraints( InstrumentConstraints instrument_constraints) { return std::vector<double>({instrument_constraints.domestic_equity_min, instrument_constraints.global_equity_min, instrument_constraints.real_estate_min, instrument_constraints.alternative_min, instrument_constraints.credit_min, instrument_constraints.bonds_2y_min, instrument_constraints.bonds_5y_min, instrument_constraints.cash_min, instrument_constraints.fta_min, instrument_constraints.domestic_equity_future_min, instrument_constraints.interest_rate_swap_2y_min, instrument_constraints.interest_rate_swap_5y_min, instrument_constraints.interest_rate_swap_20y_min, instrument_constraints.domestic_equity_max, instrument_constraints.global_equity_max, instrument_constraints.real_estate_max, instrument_constraints.alternative_max, instrument_constraints.credit_max, instrument_constraints.bonds_2y_max, instrument_constraints.bonds_5y_max, instrument_constraints.cash_max, instrument_constraints.fta_max, instrument_constraints.domestic_equity_future_max, instrument_constraints.interest_rate_swap_2y_max, instrument_constraints.interest_rate_swap_5y_max, instrument_constraints.interest_rate_swap_20y_max}); } std::vector<double> parse_margin_constraints( MarginConstraints margin_constraints) { return std::vector<double>({margin_constraints.domestic_equity_future, margin_constraints.interest_rate_swap_2y, margin_constraints.interest_rate_swap_5y, margin_constraints.interest_rate_swap_20y}); } void normalize_individuals( std::vector<double> &individuals, const int n_individuals, const int n_instruments, const int n_derivatives, const int n_scenarios) { const int n_non_derivatives = n_instruments - n_derivatives; const int n_genes = n_instruments * n_scenarios; for (int i = 0; i < n_individuals; ++i) { int ix = i * n_genes; for (int s = 0; s < n_scenarios; ++s) { double total = 0.0; int sx = ix + (s * n_instruments); for (int j = 0; j < n_non_derivatives; ++j) { int jx = sx + j; total += individuals[jx]; } if (total == 0.0) { for (int j = 0; j < n_non_derivatives; ++j) { int jx = sx + j; individuals[jx] = 1.0 / n_instruments; } } else { for (int j = 0; j < n_non_derivatives; ++j) { int jx = sx + j; individuals[jx] = individuals[jx] / total; } } } // Scenarios } // Individuals } std::vector<double> initialize_individuals( const int n_individuals, const int n_instruments, const int n_scenarios) { const int n_genes = n_instruments * n_scenarios; const int size = n_individuals * n_genes; std::vector<double> individuals(size); // Generate genes int ix = 0; for (int i = 0; i < n_individuals; i++) { for (int j = 0; j < (n_instruments * n_scenarios); j++) { ix = (i * n_genes) + j; individuals[ix] = Random::get<std::uniform_real_distribution<>>(); } } return individuals; } std::tuple<int, int> select_roulette(std::vector<double> &fitnesses) { { int i1 = Random::get<std::discrete_distribution<>>( fitnesses.begin(), fitnesses.end()); int i2 = Random::get<std::discrete_distribution<>>( fitnesses.begin(), fitnesses.end()); return std::make_tuple(i1, i2); } } double compute_wealth( std::vector<double> &current_weights, std::vector<double> &next_weights, std::vector<double> &instrument_changes, std::vector<double> &transaction_costs, const double initial_wealth, const int n_instruments, const int n_derivatives) { const int n_non_derivatives = n_instruments - n_derivatives; double holdings = 0.0; double reallocations = 0.0; // Compute wealth from price changes for (int i = 0; i < n_instruments; ++i) { double result = 0.0; if (i < n_non_derivatives) { result = initial_wealth * current_weights[i] * (1.0 + instrument_changes[i]); } else { result = (initial_wealth * current_weights[i] * (1.0 + instrument_changes[i])) - (initial_wealth * current_weights[i]); } holdings += result; } // Deduct transation costs for (int i = 0; i < current_weights.size(); ++i) { const double diff = fabs(current_weights[i] - next_weights[i]); reallocations += holdings * diff * transaction_costs[i]; } const double wealth = holdings - reallocations; return wealth; } std::tuple<std::vector<double>, std::vector<double>> compute_wealths( std::vector<double> &individual, std::vector<double> &instrument_changes, std::vector<double> &transaction_costs, const int n_instruments, const int n_derivatives, const int n_scenarios) { std::vector<double> intermediate_wealths(n_scenarios); intermediate_wealths[0] = 1.0; std::vector<double> final_wealths(n_scenarios / 2 + 1); int final_index = 0; // Iterate through scenarios for (int i = 0; i < n_scenarios; ++i) { int current = i; int left = 2 * current + 1; int right = 2 * current + 2; // Index of current node const int cx = current * n_instruments; const double current_wealth = intermediate_wealths[current]; std::vector<double> current_changes = std::vector<double>( instrument_changes.begin() + cx, instrument_changes.begin() + cx + n_instruments); std::vector<double> current_weights = std::vector<double>( individual.begin() + cx, individual.begin() + cx + n_instruments); if (left < n_scenarios && right < n_scenarios) { const int lx = left * n_instruments; const int rx = right * n_instruments; std::vector<double> left_weights = std::vector<double>( individual.begin() + lx, individual.begin() + lx + n_instruments); std::vector<double> right_weights = std::vector<double>( individual.begin() + rx, individual.begin() + rx + n_instruments); // Evaluate left child intermediate_wealths[left] = compute_wealth( current_weights, left_weights, current_changes, transaction_costs, current_wealth, n_instruments, n_derivatives); // Evaluate right child intermediate_wealths[right] = compute_wealth( current_weights, right_weights, current_changes, transaction_costs, current_wealth, n_instruments, n_derivatives); } else { // We are at the leaf nodes of the scenario tree, // so compute the final wealth. final_wealths[final_index] = compute_wealth( current_weights, current_weights, current_changes, transaction_costs, current_wealth, n_instruments, n_derivatives); final_index++; } } return std::make_tuple(intermediate_wealths, final_wealths); } double compute_expected_wealth(std::vector<double> &final_wealths) { double expected_wealth = 0.0; for (double wealth : final_wealths) { expected_wealth += wealth; } expected_wealth = expected_wealth / final_wealths.size(); return expected_wealth; } double compute_expected_risk( std::vector<double> &intermediate_wealths, std::vector<double> &goals) { double risk = 0.0; for (int i = 0; i < intermediate_wealths.size(); ++i) { const double step = floor(std::log2(i + 1)); const double nodes_in_step = pow(2.0, step); risk += pow(std::min(0.0, intermediate_wealths[i] - goals[i]), 2.0) / nodes_in_step; } return risk; } double compute_fitness( std::vector<double> &individual, std::vector<double> &intermediate_wealths, std::vector<double> &final_wealths, std::vector<double> &intermediate_goals, std::vector<double> &final_goals, std::vector<double> &instrument_constraints, std::vector<double> &margin_constraints, const int n_instruments, const int n_derivatives, const int n_scenarios) { const double wealth = compute_expected_wealth(final_wealths); const double penalty = compute_penalty( individual, instrument_constraints, margin_constraints, intermediate_wealths, final_wealths, intermediate_goals, final_goals, n_instruments, n_derivatives, n_scenarios); return std::max(0.0, wealth - 1.0 - penalty); } double compute_penalty( std::vector<double> &individual, std::vector<double> &instrument_constraints, std::vector<double> &margin_constraints, std::vector<double> &intermediate_wealths, std::vector<double> &final_wealths, std::vector<double> &intermediate_goals, std::vector<double> &final_goals, const int n_instruments, const int n_derivatives, const int n_scenarios) { const int n_non_derivatives = n_instruments - n_derivatives; double penalty = 0.0; // Check instrument allocation constraints for (int j = 0; j < n_scenarios; ++j) { const int jx = j * n_instruments; // Allocation constraints for (int k = 0; k < n_instruments; ++k) { // Minimum penalty += pow( std::max(0.0, instrument_constraints[k] - individual[jx + k]), 2.0); // Maximum penalty += pow( std::max(0.0, individual[jx + k] - instrument_constraints[k + n_instruments]), 2.0); } // Margin constraints double remaining_margin = individual[jx + CASH_INDEX] + individual[jx + FTA_INDEX]; for (int k = 0; k < n_derivatives; ++k) { const int kx = n_non_derivatives + k; const double required_margin = margin_constraints[k] * individual[jx + kx]; remaining_margin -= required_margin; } penalty += pow(std::min(0.0, remaining_margin), 2.0); } for (int i = 0; i < intermediate_wealths.size(); ++i) { const double step = floor(std::log2(i + 1)); const double nodes_in_step = pow(2.0, step); penalty += pow(std::min(0.0, intermediate_wealths[i] - intermediate_goals[i]), 2.0) / nodes_in_step; } for (int i = 0; i < final_wealths.size(); ++i) { penalty += pow(std::min(0.0, final_wealths[i] - final_goals[i]), 2.0) / final_wealths.size(); } // Risk constraints return penalty; } std::vector<double> compute_fitnesses( std::vector<double> &individuals, std::vector<double> &instrument_changes, std::vector<double> &transaction_costs, std::vector<double> &intermediate_goals, std::vector<double> &final_goals, std::vector<double> &instrument_constraints, std::vector<double> &margin_constraints, const int n_individuals, const int n_instruments, const int n_derivatives, const int n_scenarios) { const int n_genes = n_instruments * n_scenarios; std::vector<double> fitnesses(n_individuals); for (int i = 0; i < n_individuals; ++i) { const int ix = i * n_genes; std::vector<double> individual = std::vector<double>( individuals.begin() + ix, individuals.begin() + ix + n_genes); std::tuple<std::vector<double>, std::vector<double>> wealths = compute_wealths( individual, instrument_changes, transaction_costs, n_instruments, n_derivatives, n_scenarios); std::vector<double> intermediate_wealths = std::get<0>(wealths); std::vector<double> final_wealths = std::get<1>(wealths); fitnesses[i] = compute_fitness( individual, intermediate_wealths, final_wealths, intermediate_goals, final_goals, instrument_constraints, margin_constraints, n_instruments, n_derivatives, n_scenarios); } return fitnesses; } void mutate_individuals(std::vector<double> &selected, const double mutation_rate) { for (int j = 0; j < selected.size(); ++j) { const double random = Random::get(0.0, 1.0); if (random < mutation_rate) { const double d = ((double)j + 1.0) / ((double)j + 3.0); const double mutation = d * Random::get(-1.0, 1.0); selected[j] = std::min(1.0, std::max(0.0, selected[j] + mutation)); } } } void crossover_individuals_scenario( std::vector<double> &selected, const int n_instruments, const int n_scenarios, const double crossover_rate) { const int n_genes = n_instruments * n_scenarios; const double r = Random::get(0.0, 1.0); if (r < crossover_rate) { const int scenario = Random::get(0, n_scenarios - 1); const int ix = scenario * n_instruments; for (int j = 0; j < n_genes; ++j) { const double temp = selected[j]; selected[j] = selected[j + n_genes]; selected[j + n_genes] = temp; } } } void crossover_individuals( std::vector<double> &selected, const double crossover_rate) { const double r1 = Random::get(0.0, 1.0); if (r1 < crossover_rate) { const int n_genes = selected.size() / 2; std::vector<double> temp(selected); // Construct first individual for (int j = 0; j < n_genes; ++j) { const double r2 = Random::get(0.0, 1.0); if (r2 < 0.5) selected[j] = temp[j]; else selected[j] = temp[j + n_genes]; } // Construct Second individual for (int j = 0; j < n_genes; ++j) { const double r2 = Random::get(0.0, 1.0); if (r2 < 0.5) selected[j + n_genes] = temp[j]; else selected[j + n_genes] = temp[j + n_genes]; } } } Result optimize(OptimizeOptions options) { const int n_individuals = options.population_size; const int n_elitism_copies = options.elitism_copies; const int n_generations = options.generations; const int n_steps = options.steps; const double mutation_rate = options.mutation_rate; const double crossover_rate = options.crossover_rate; const double initial_funding_ratio = options.initial_funding_ratio; const double target_funding_ratio = options.target_funding_ratio; std::vector<double> transaction_costs = { options.transaction_costs.domestic_equity, options.transaction_costs.global_equity, options.transaction_costs.real_estate, options.transaction_costs.alternative, options.transaction_costs.credit, options.transaction_costs.bonds_2y, options.transaction_costs.bonds_5y, options.transaction_costs.cash, options.transaction_costs.fta, options.transaction_costs.domestic_equity_future, options.transaction_costs.interest_rate_swap_2y, options.transaction_costs.interest_rate_swap_5y, options.transaction_costs.interest_rate_swap_20y}; std::vector<double> instrument_constraints = parse_instrument_constraints(options.instrument_constraints); std::vector<double> margin_constraints = parse_margin_constraints(options.margin_constraints); const int n_risks = N_RISKS; const int n_instruments = N_INSTRUMENTS; const int n_derivatives = N_DERIVATIVES; const int n_scenarios = pow(2.0, n_steps) - 1; const int n_genes = n_scenarios * n_instruments; // Will contain the final result double best_fitness = 0.0; std::vector<double> best_individual = std::vector<double>(n_genes, 0.0); // Generate initial individuals std::vector<double> individuals = initialize_individuals(n_individuals, n_instruments, n_scenarios); // ...and normalize them. normalize_individuals( individuals, n_individuals, n_instruments, n_derivatives, n_scenarios); // Generate scenarios std::vector<double> means = NORMAL_DEFAULT_MEANS; std::vector<double> standard_deviations = NORMAL_DEFAULT_STANDARD_DEVIATIONS; std::vector<double> correlations = NORMAL_DEFAULT_CORRELATIONS; std::vector<double> instrument_changes = generate_normal_scenarios( means, standard_deviations, correlations, n_risks, n_instruments, n_scenarios); // Generate goals std::tuple<std::vector<double>, std::vector<double>> goals = generate_normal_goals( instrument_changes, initial_funding_ratio, target_funding_ratio, n_scenarios, n_instruments); std::vector<double> intermediate_goals = std::vector<double>(n_scenarios, 1.0); // std::get<0>(goals); std::vector<double> final_goals = std::get<1>(goals); for (int t = 0; t < n_generations; ++t) { std::vector<double> fitnesses = compute_fitnesses( individuals, instrument_changes, transaction_costs, intermediate_goals, final_goals, instrument_constraints, margin_constraints, n_individuals, n_instruments, n_derivatives, n_scenarios); // Check global best fitness for (int i = 0; i < n_individuals; ++i) { if (fitnesses[i] >= best_fitness) { const int ix = i * n_genes; best_fitness = fitnesses[i]; best_individual = std::vector<double>( individuals.begin() + ix, individuals.begin() + ix + n_genes); } } // Clone individuals vector std::vector<double> offspring(individuals); for (int i = 0; i < n_individuals; i += 2) { const int ix = i * n_genes; // Selection std::tuple<int, int> indices = select_roulette(fitnesses); int ix1 = std::get<0>(indices) * n_genes; int ix2 = std::get<1>(indices) * n_genes; std::vector<double> selected(2 * n_genes); for (int j = 0; j < n_genes; ++j) { selected[j] = individuals[ix1 + j]; selected[n_genes + j] = individuals[ix2 + j]; } // Crossover crossover_individuals_scenario( selected, n_instruments, n_scenarios, crossover_rate); // Mutation mutate_individuals(selected, mutation_rate); // Add selected individuals for (int j = 0; j < n_genes; ++j) { offspring[i * n_genes] = selected[j]; } } // Elitism for (int i = 0; i < n_elitism_copies; ++i) { int ix = i * n_genes; for (int j = 0; j < n_genes; ++j) { offspring[ix + j] = best_individual[j]; } } normalize_individuals( offspring, n_individuals, n_instruments, n_derivatives, n_scenarios); // Replace generation individuals = offspring; } Result result; std::tuple<std::vector<double>, std::vector<double>> best_wealths = compute_wealths( best_individual, instrument_changes, transaction_costs, n_instruments, n_derivatives, n_scenarios); std::vector<double> best_intermediate_wealths = std::get<0>(best_wealths); std::vector<double> best_final_wealths = std::get<1>(best_wealths); double best_expected_return = compute_expected_wealth(best_final_wealths) - 1.0; double best_expected_risk = compute_expected_risk(best_intermediate_wealths, intermediate_goals); result.fitness = best_fitness; result.individual = best_individual; result.intermediate_wealths = best_intermediate_wealths; result.final_wealths = best_final_wealths; result.expected_return = best_expected_return; result.expected_risk = best_expected_risk; result.instrument_changes = instrument_changes; result.goals = intermediate_goals; return result; }
29.765988
125
0.637726
[ "vector" ]
935f67c2ef03545573a3d298757f7ba9dbbf599d
3,644
hpp
C++
gfcpp/v0/errors.hpp
dancullen/gfcpp
9b719e787a80f07a8bfecc3276a30e7689d0c108
[ "BSD-3-Clause" ]
null
null
null
gfcpp/v0/errors.hpp
dancullen/gfcpp
9b719e787a80f07a8bfecc3276a30e7689d0c108
[ "BSD-3-Clause" ]
null
null
null
gfcpp/v0/errors.hpp
dancullen/gfcpp
9b719e787a80f07a8bfecc3276a30e7689d0c108
[ "BSD-3-Clause" ]
null
null
null
/** * errors.hpp contains functions for manipulating errors. It is similar to Golang's `errors` package. */ #pragma once #include <string> namespace gfcpp { /** * error allows errors to be handled in C++ with Golang-like syntax and idioms. In other words, * this class encapsulates a boolean success/failure result (i.e., error != nil) along with * a string containing the error message. * Inspired by https://pkg.go.dev/builtin#error */ class error { public: /** * Constructor initializes a new error object. It's basically like calling Golang's `errors.New` function. */ error(const bool isNil, const std::string &message = "") : isNil_(isNil), message_(message) {} /** * operator bool allows the construct "if (err)". */ explicit operator bool(void) const { return !isNil_; } /** * Error returns the error message. */ std::string Error(void) const { return message_; } private: /** * isNil_ keeps track of whether or not an error actually exists. We cannot just store std::string * as a raw pointer because that would leak memory. Wrapping it with a smart pointer seems wasteful. * And using an empty string as a sentinel value for no error would be a hack and would not be able * to distinguish between no error and an error that simply doesn't provide any detailed information * about the error. */ bool isNil_; /** * message_ stores the details about the error. Note that you must check isNil_ for whether an error * occurred; an empty string does NOT indicate no error occurred-- it may simply indicate that no * details about the error are available. (No details would be poor practice but we support it anyway.) */ std::string message_; }; /** * nil is syntactic sugar for indicating a nil error, or in other words, a successful result. * It allows you to do comparisons such as `if (err != nil)`. */ static const error nil(true, ""); } // namespace gfcpp /** * CONTEXT wraps the given string with context info such as the current function's name. * * This MUST be implemented as a preprocessor macro in order for __func__ to be valid. * https://stackoverflow.com/questions/733056/is-there-a-way-to-get-function-name-inside-a-c-function */ #define CONTEXT(message) \ (std::string(__func__) + std::string(": ") + std::string(message)) /** * NewError returns a new error, annotated with context. Takes either a 'std::string' or 'const char *' for message. * Inspired by https://pkg.go.dev/errors#New * * This MUST be implemented as a preprocessor macro in order for __func__ (see CONTEXT) to be valid. * https://stackoverflow.com/questions/733056/is-there-a-way-to-get-function-name-inside-a-c-function */ #define NewError(message) \ gfcpp::error(false, CONTEXT(message)) /** * Errorf is used to wrap an existing error with details before it gets returned up the call stack. * Takes either 'std::string' or 'const char *' for 'message' and an 'error' for 'err'. Returns an * object of type 'error'. This is basically a poor man's version of fmt.Errorf() from Golang-- * it simply concatenate the strings without supporting any printf-like formatting features. * * Inspired by https://pkg.go.dev/fmt#Errorf * * This MUST be implemented as a preprocessor macro in order for __func__ to be valid. * https://stackoverflow.com/questions/733056/is-there-a-way-to-get-function-name-inside-a-c-function */ #define Errorf(message, err) \ gfcpp::error(false, std::string(__func__) + std::string(": ") + std::string(message) + err.Error())
36.808081
116
0.696762
[ "object" ]
9360b7a0894a7eec325089a31c8a26543d1956a3
2,825
cpp
C++
cyg_main.cpp
yasuo-ozu/cygraph-gui
ec4f2793cdd6d208b89e5795a3e08dceff6b29e6
[ "MIT" ]
1
2018-02-12T05:09:30.000Z
2018-02-12T05:09:30.000Z
cyg_main.cpp
yasuo-ozu/cygraph-gui
ec4f2793cdd6d208b89e5795a3e08dceff6b29e6
[ "MIT" ]
null
null
null
cyg_main.cpp
yasuo-ozu/cygraph-gui
ec4f2793cdd6d208b89e5795a3e08dceff6b29e6
[ "MIT" ]
null
null
null
#include "cyg_common.hpp" namespace Cygraph { int CygMain(int argc, char **argv) { UNUSED(argc, argv); /* auto *graph = new Graph(); auto *axis = new Axis(0, 10, 1); axis->set_text("ドレイン-ソース間電圧(Vds) [V]"); graph->axises.push_back(axis); auto *axis2 = new Axis(250, 0, -50); axis2->orientation = 0; axis2->set_text("ドレイン-ソース間電流(Id) [mA]"); graph->axises.push_back(axis2); auto *axis3 = new Axis(250, 0, -50); axis3->orientation = 3; axis3->set_text("ドレイン-ソース間電流(Id) [mA]"); graph->axises.push_back(axis3); auto *line1 = new GraphLine(axis, axis3); graph->lines.push_back(line1); auto *line2 = new GraphLine(axis, axis3); line2->draw_line = false; auto *point1 = new GraphPoint(GraphPoint::PS_CIRCLE); auto *point2 = new GraphPoint(GraphPoint::PS_CIRCLE); auto *point3 = new GraphPoint(GraphPoint::PS_CIRCLE); point2->size = 9.0; point2->invert = true; point3->size = 2; line2->points.push_back(point1); line2->points.push_back(point2); line2->points.push_back(point3); graph->lines.push_back(line2); auto *line3 = new GraphLine(axis, axis3); line3->efficient = 1.5; graph->lines.push_back(line3); auto *line4 = new GraphLine(axis, axis3); line4->efficient = 1.5; line4->draw_line = false; auto *point4 = new GraphPoint(GraphPoint::PS_TRIANGLE); auto *point5 = new GraphPoint(GraphPoint::PS_TRIANGLE); auto *point6 = new GraphPoint(GraphPoint::PS_CIRCLE); point5->size = 9.0; point5->invert = true; point6->size = 2; line4->points.push_back(point4); line4->points.push_back(point5); line4->points.push_back(point6); graph->lines.push_back(line4); auto *line5 = new GraphLine(axis, axis3); line5->efficient = 2.0; graph->lines.push_back(line5); auto *line6 = new GraphLine(axis, axis3); line6->efficient = 2.0; line6->draw_line = false; auto *point7 = new GraphPoint(GraphPoint::PS_SQUARE); auto *point8 = new GraphPoint(GraphPoint::PS_SQUARE); auto *point9 = new GraphPoint(GraphPoint::PS_CIRCLE); point8->size = 9.0; point8->invert = true; point9->size = 2; line6->points.push_back(point7); line6->points.push_back(point8); line6->points.push_back(point9); graph->lines.push_back(line6); auto *driver = new GtkDriver(800, 600); driver->render(graph); */ const char * const sample_script = R"( print("hello, world\n") )"; Graph *graph; if (argc == 2) { fprintf(stderr, "Loading from %s...\n", argv[1]); graph = ExecuteScript(argv[1]); } else { fprintf(stderr, "Loading sample...\n"); graph = ExecuteScriptFromText(sample_script); } if (graph == nullptr) { cerr << "Some error(s) occured." << endl; return 1; } auto *driver = new GtkDriver(800, 600); driver->render(graph); return 0; } } int main(int argc, char **argv) { return Cygraph::CygMain(argc, argv); }
30.706522
57
0.672212
[ "render" ]
93692b3996c8e896a1dcc0865e46aa2c1cc58234
188,006
cpp
C++
qtdeclarative/src/qml/compiler/qv4ssa.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qtdeclarative/src/qml/compiler/qv4ssa.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qtdeclarative/src/qml/compiler/qv4ssa.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // When building with debug code, the macro below will enable debug helpers when using libc++. // For example, the std::vector<T>::operator[] will use _LIBCPP_ASSERT to check if the index is // within the array bounds. Note that this only works reliably with OSX 10.9 or later. //#define _LIBCPP_DEBUG2 2 #include "qv4ssa_p.h" #include "qv4isel_util_p.h" #include "qv4util_p.h" #include <QtCore/QBuffer> #include <QtCore/QCoreApplication> #include <QtCore/QStringList> #include <QtCore/QSet> #include <QtCore/QLinkedList> #include <QtCore/QStack> #include <qv4runtime_p.h> #include <cmath> #include <iostream> #include <cassert> #include <algorithm> QT_USE_NAMESPACE using namespace QV4; using namespace IR; namespace { enum { DebugMoveMapping = 0 }; #ifdef QT_NO_DEBUG enum { DoVerification = 0 }; #else enum { DoVerification = 1 }; #endif static void showMeTheCode(IR::Function *function, const char *marker) { static const bool showCode = qEnvironmentVariableIsSet("QV4_SHOW_IR"); if (showCode) { qDebug() << marker; QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream stream(&buf); IRPrinter(&stream).print(function); stream << endl; qDebug("%s", buf.data().constData()); } } #if !defined(BROKEN_STD_VECTOR_BOOL_OR_BROKEN_STD_FIND) // Sanity: class BitVector { std::vector<bool> bits; public: BitVector(int size = 0, bool value = false) : bits(size, value) {} void reserve(int size) { bits.reserve(size); } int size() const { Q_ASSERT(bits.size() < INT_MAX); return static_cast<int>(bits.size()); } void resize(int newSize) { bits.resize(newSize); } void assign(int newSize, bool value) { bits.assign(newSize, value); } int findNext(int start, bool value, bool wrapAround) const { // The ++operator of std::vector<bool>::iterator in libc++ has a bug when using it on an // iterator pointing to the last element. It will not be set to ::end(), but beyond // that. (It will be set to the first multiple of the native word size that is bigger // than size().) // // See http://llvm.org/bugs/show_bug.cgi?id=19663 // // The work-around is to calculate the distance, and compare it to the size() to see if it's // beyond the end, or take the minimum of the distance and the size. size_t pos = std::distance(bits.begin(), std::find(bits.begin() + start, bits.end(), value)); if (wrapAround && pos >= static_cast<size_t>(size())) pos = std::distance(bits.begin(), std::find(bits.begin(), bits.begin() + start, value)); pos = qMin(pos, static_cast<size_t>(size())); Q_ASSERT(pos <= static_cast<size_t>(size())); Q_ASSERT(pos < INT_MAX); return static_cast<int>(pos); } bool at(int idx) const { return bits.at(idx); } void setBit(int idx) { bits[idx] = true; } void clearBit(int idx) { bits[idx] = false; } }; #else // Insanity: class BitVector { QBitArray bits; public: BitVector(int size = 0, bool value = false) : bits(size, value) {} void reserve(int size) { Q_UNUSED(size); } int size() const { return bits.size(); } void resize(int newSize) { bits.resize(newSize); } void assign(int newSize, bool value) { bits.resize(newSize); bits.fill(value); } int findNext(int start, bool value, bool wrapAround) const { for (int i = start, ei = size(); i < ei; ++i) { if (at(i) == value) return i; } if (wrapAround) { for (int i = 0, ei = start; i < ei; ++i) { if (at(i) == value) return i; } } return size(); } bool at(int idx) const { return bits.at(idx); } void setBit(int idx) { bits[idx] = true; } void clearBit(int idx) { bits[idx] = false; } }; #endif class ProcessedBlocks { BitVector processed; public: ProcessedBlocks(IR::Function *function) : processed(function->basicBlockCount(), false) {} bool alreadyProcessed(BasicBlock *bb) const { Q_ASSERT(bb); return processed.at(bb->index()); } void markAsProcessed(BasicBlock *bb) { processed.setBit(bb->index()); } }; class BasicBlockSet { typedef BitVector Flags; QVarLengthArray<int, 8> blockNumbers; Flags *blockFlags; IR::Function *function; enum { MaxVectorCapacity = 8 }; public: class const_iterator { const BasicBlockSet &set; // ### These two members could go into a union, but clang won't compile (https://codereview.qt-project.org/#change,74259) QVarLengthArray<int, 8>::const_iterator numberIt; int flagIt; friend class BasicBlockSet; const_iterator(const BasicBlockSet &set, bool end) : set(set) { if (end || !set.function) { if (!set.blockFlags) numberIt = set.blockNumbers.end(); else flagIt = set.blockFlags->size(); } else { if (!set.blockFlags) numberIt = set.blockNumbers.begin(); else findNextWithFlags(0); } } void findNextWithFlags(int start) { flagIt = set.blockFlags->findNext(start, true, /*wrapAround = */false); Q_ASSERT(flagIt <= set.blockFlags->size()); } public: BasicBlock *operator*() const { if (!set.blockFlags) { return set.function->basicBlock(*numberIt); } else { Q_ASSERT(flagIt <= set.function->basicBlockCount()); return set.function->basicBlock(flagIt); } } bool operator==(const const_iterator &other) const { if (&set != &other.set) return false; if (!set.blockFlags) return numberIt == other.numberIt; else return flagIt == other.flagIt; } bool operator!=(const const_iterator &other) const { return !(*this == other); } const_iterator &operator++() { if (!set.blockFlags) ++numberIt; else findNextWithFlags(flagIt + 1); return *this; } }; friend class const_iterator; public: BasicBlockSet(IR::Function *f = 0): blockFlags(0), function(0) { if (f) init(f); } #ifdef Q_COMPILER_RVALUE_REFS BasicBlockSet(BasicBlockSet &&other): blockFlags(0) { std::swap(blockNumbers, other.blockNumbers); std::swap(blockFlags, other.blockFlags); std::swap(function, other.function); } #endif // Q_COMPILER_RVALUE_REFS BasicBlockSet(const BasicBlockSet &other) : blockFlags(0) , function(other.function) { if (other.blockFlags) blockFlags = new Flags(*other.blockFlags); blockNumbers = other.blockNumbers; } BasicBlockSet &operator=(const BasicBlockSet &other) { if (blockFlags) { delete blockFlags; blockFlags = 0; } function = other.function; if (other.blockFlags) blockFlags = new Flags(*other.blockFlags); blockNumbers = other.blockNumbers; return *this; } ~BasicBlockSet() { delete blockFlags; } void init(IR::Function *f) { Q_ASSERT(!function); Q_ASSERT(f); function = f; } bool empty() const { return begin() == end(); } void insert(BasicBlock *bb) { Q_ASSERT(function); if (blockFlags) { blockFlags->setBit(bb->index()); return; } for (int i = 0; i < blockNumbers.size(); ++i) { if (blockNumbers[i] == bb->index()) return; } if (blockNumbers.size() == MaxVectorCapacity) { blockFlags = new Flags(function->basicBlockCount(), false); for (int i = 0; i < blockNumbers.size(); ++i) { blockFlags->setBit(blockNumbers[i]); } blockNumbers.clear(); blockFlags->setBit(bb->index()); } else { blockNumbers.append(bb->index()); } } void remove(BasicBlock *bb) { Q_ASSERT(function); if (blockFlags) { blockFlags->clearBit(bb->index()); return; } for (int i = 0; i < blockNumbers.size(); ++i) { if (blockNumbers[i] == bb->index()) { blockNumbers.remove(i); return; } } } const_iterator begin() const { return const_iterator(*this, false); } const_iterator end() const { return const_iterator(*this, true); } void collectValues(std::vector<BasicBlock *> &bbs) const { Q_ASSERT(function); for (const_iterator it = begin(), eit = end(); it != eit; ++it) bbs.push_back(*it); } bool contains(BasicBlock *bb) const { Q_ASSERT(function); if (blockFlags) return blockFlags->at(bb->index()); for (int i = 0; i < blockNumbers.size(); ++i) { if (blockNumbers[i] == bb->index()) return true; } return false; } }; class DominatorTree { enum { DebugDominatorFrontiers = 0, DebugImmediateDominators = 0, DebugCodeCanUseLotsOfCpu = 0 }; typedef int BasicBlockIndex; enum { InvalidBasicBlockIndex = -1 }; struct Data { int N; std::vector<int> dfnum; // BasicBlock index -> dfnum std::vector<int> vertex; std::vector<BasicBlockIndex> parent; // BasicBlock index -> parent BasicBlock index std::vector<BasicBlockIndex> ancestor; // BasicBlock index -> ancestor BasicBlock index std::vector<BasicBlockIndex> best; // BasicBlock index -> best BasicBlock index std::vector<BasicBlockIndex> semi; // BasicBlock index -> semi dominator BasicBlock index std::vector<BasicBlockIndex> samedom; // BasicBlock index -> same dominator BasicBlock index Data(): N(0) {} }; IR::Function *function; QScopedPointer<Data> d; std::vector<BasicBlockIndex> idom; // BasicBlock index -> immediate dominator BasicBlock index std::vector<BasicBlockSet> DF; // BasicBlock index -> dominator frontier struct DFSTodo { BasicBlockIndex node, parent; DFSTodo() : node(InvalidBasicBlockIndex) , parent(InvalidBasicBlockIndex) {} DFSTodo(BasicBlockIndex node, BasicBlockIndex parent) : node(node) , parent(parent) {} }; void DFS(BasicBlockIndex node) { std::vector<DFSTodo> worklist; worklist.reserve(d->vertex.capacity() / 2); DFSTodo todo(node, InvalidBasicBlockIndex); while (true) { BasicBlockIndex n = todo.node; if (d->dfnum[n] == 0) { d->dfnum[n] = d->N; d->vertex[d->N] = n; d->parent[n] = todo.parent; ++d->N; const BasicBlock::OutgoingEdges &out = function->basicBlock(n)->out; for (int i = out.size() - 1; i > 0; --i) worklist.push_back(DFSTodo(out[i]->index(), n)); if (out.size() > 0) { todo.node = out.first()->index(); todo.parent = n; continue; } } if (worklist.empty()) break; todo = worklist.back(); worklist.pop_back(); } } BasicBlockIndex ancestorWithLowestSemi(BasicBlockIndex v, std::vector<BasicBlockIndex> &worklist) { worklist.clear(); for (BasicBlockIndex it = v; it != InvalidBasicBlockIndex; it = d->ancestor[it]) worklist.push_back(it); if (worklist.size() < 2) return d->best[v]; BasicBlockIndex b = InvalidBasicBlockIndex; BasicBlockIndex last = worklist.back(); Q_ASSERT(worklist.size() <= INT_MAX); for (int it = static_cast<int>(worklist.size()) - 2; it >= 0; --it) { BasicBlockIndex bbIt = worklist[it]; d->ancestor[bbIt] = last; BasicBlockIndex &best_it = d->best[bbIt]; if (b != InvalidBasicBlockIndex && d->dfnum[d->semi[b]] < d->dfnum[d->semi[best_it]]) best_it = b; else b = best_it; } return b; } void link(BasicBlockIndex p, BasicBlockIndex n) { d->ancestor[n] = p; d->best[n] = n; } void calculateIDoms() { Q_ASSERT(function->basicBlock(0)->in.isEmpty()); const int bbCount = function->basicBlockCount(); d->vertex = std::vector<int>(bbCount, InvalidBasicBlockIndex); d->parent = std::vector<int>(bbCount, InvalidBasicBlockIndex); d->dfnum = std::vector<int>(size_t(bbCount), 0); d->semi = std::vector<BasicBlockIndex>(bbCount, InvalidBasicBlockIndex); d->ancestor = std::vector<BasicBlockIndex>(bbCount, InvalidBasicBlockIndex); idom = std::vector<BasicBlockIndex>(bbCount, InvalidBasicBlockIndex); d->samedom = std::vector<BasicBlockIndex>(bbCount, InvalidBasicBlockIndex); d->best = std::vector<BasicBlockIndex>(bbCount, InvalidBasicBlockIndex); QHash<BasicBlockIndex, std::vector<BasicBlockIndex> > bucket; bucket.reserve(bbCount); DFS(function->basicBlock(0)->index()); Q_ASSERT(d->N == function->liveBasicBlocksCount()); std::vector<BasicBlockIndex> worklist; worklist.reserve(d->vertex.capacity() / 2); for (int i = d->N - 1; i > 0; --i) { BasicBlockIndex n = d->vertex[i]; BasicBlockIndex p = d->parent[n]; BasicBlockIndex s = p; foreach (BasicBlock *v, function->basicBlock(n)->in) { BasicBlockIndex ss = InvalidBasicBlockIndex; if (d->dfnum[v->index()] <= d->dfnum[n]) ss = v->index(); else ss = d->semi[ancestorWithLowestSemi(v->index(), worklist)]; if (d->dfnum[ss] < d->dfnum[s]) s = ss; } d->semi[n] = s; bucket[s].push_back(n); link(p, n); if (bucket.contains(p)) { foreach (BasicBlockIndex v, bucket[p]) { BasicBlockIndex y = ancestorWithLowestSemi(v, worklist); BasicBlockIndex semi_v = d->semi[v]; if (d->semi[y] == semi_v) idom[v] = semi_v; else d->samedom[v] = y; } bucket.remove(p); } } for (int i = 1; i < d->N; ++i) { BasicBlockIndex n = d->vertex[i]; Q_ASSERT(n != InvalidBasicBlockIndex); Q_ASSERT(!bucket.contains(n)); Q_ASSERT(d->ancestor[n] != InvalidBasicBlockIndex && ((d->semi[n] != InvalidBasicBlockIndex && d->dfnum[d->ancestor[n]] <= d->dfnum[d->semi[n]]) || d->semi[n] == n)); BasicBlockIndex sdn = d->samedom[n]; if (sdn != InvalidBasicBlockIndex) idom[n] = idom[sdn]; } dumpImmediateDominators(); } struct NodeProgress { std::vector<BasicBlockIndex> children; std::vector<BasicBlockIndex> todo; }; public: DominatorTree(IR::Function *function) : function(function) , d(new Data) { calculateIDoms(); d.reset(); } void computeDF() { DF.resize(function->basicBlockCount()); // compute children of each node in the dominator tree std::vector<std::vector<BasicBlockIndex> > children; // BasicBlock index -> children children.resize(function->basicBlockCount()); foreach (BasicBlock *n, function->basicBlocks()) { if (n->isRemoved()) continue; const BasicBlockIndex nodeIndex = n->index(); Q_ASSERT(function->basicBlock(nodeIndex) == n); const BasicBlockIndex nodeDominator = idom[nodeIndex]; if (nodeDominator == InvalidBasicBlockIndex) continue; // there is no dominator to add this node to as a child (e.g. the start node) children[nodeDominator].push_back(nodeIndex); } // Fill the worklist and initialize the node status for each basic-block std::vector<NodeProgress> nodeStatus; nodeStatus.resize(function->basicBlockCount()); std::vector<BasicBlockIndex> worklist; worklist.reserve(function->basicBlockCount()); foreach (BasicBlock *bb, function->basicBlocks()) { if (bb->isRemoved()) continue; BasicBlockIndex nodeIndex = bb->index(); worklist.push_back(nodeIndex); NodeProgress &np = nodeStatus[nodeIndex]; np.children = children[nodeIndex]; np.todo = children[nodeIndex]; } BitVector DF_done(function->basicBlockCount(), false); while (!worklist.empty()) { BasicBlockIndex node = worklist.back(); if (DF_done.at(node)) { worklist.pop_back(); continue; } NodeProgress &np = nodeStatus[node]; std::vector<BasicBlockIndex>::iterator it = np.todo.begin(); while (it != np.todo.end()) { if (DF_done.at(*it)) { it = np.todo.erase(it); } else { worklist.push_back(*it); break; } } if (np.todo.empty()) { BasicBlockSet &S = DF[node]; S.init(function); foreach (BasicBlock *y, function->basicBlock(node)->out) if (idom[y->index()] != node) S.insert(y); foreach (BasicBlockIndex child, np.children) { const BasicBlockSet &ws = DF[child]; for (BasicBlockSet::const_iterator it = ws.begin(), eit = ws.end(); it != eit; ++it) { BasicBlock *w = *it; const BasicBlockIndex wIndex = w->index(); if (node == wIndex || !dominates(node, w->index())) S.insert(w); } } DF_done.setBit(node); worklist.pop_back(); } } if (DebugDominatorFrontiers) { QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream qout(&buf); qout << "Dominator Frontiers:" << endl; foreach (BasicBlock *n, function->basicBlocks()) { if (n->isRemoved()) continue; qout << "\tDF[" << n->index() << "]: {"; const BasicBlockSet &SList = DF[n->index()]; for (BasicBlockSet::const_iterator i = SList.begin(), ei = SList.end(); i != ei; ++i) { if (i != SList.begin()) qout << ", "; qout << (*i)->index(); } qout << "}" << endl; } qDebug("%s", buf.data().constData()); } if (DebugDominatorFrontiers && DebugCodeCanUseLotsOfCpu) { foreach (BasicBlock *n, function->basicBlocks()) { if (n->isRemoved()) continue; const BasicBlockSet &fBlocks = DF[n->index()]; for (BasicBlockSet::const_iterator it = fBlocks.begin(), eit = fBlocks.end(); it != eit; ++it) { BasicBlock *fBlock = *it; Q_ASSERT(!dominates(n, fBlock) || fBlock == n); bool hasDominatedSucc = false; foreach (BasicBlock *succ, fBlock->in) { if (dominates(n, succ)) { hasDominatedSucc = true; break; } } if (!hasDominatedSucc) { qDebug("%d in DF[%d] has no dominated predecessors", fBlock->index(), n->index()); } Q_ASSERT(hasDominatedSucc); } } } } const BasicBlockSet &dominatorFrontier(BasicBlock *n) const { return DF[n->index()]; } BasicBlock *immediateDominator(BasicBlock *bb) const { const BasicBlockIndex idx = idom[bb->index()]; if (idx == -1) return 0; return function->basicBlock(idx); } void dumpImmediateDominators() const { if (DebugImmediateDominators) { QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream qout(&buf); qout << "Immediate dominators:" << endl; foreach (BasicBlock *to, function->basicBlocks()) { if (to->isRemoved()) continue; qout << '\t'; BasicBlockIndex from = idom.at(to->index()); if (from != InvalidBasicBlockIndex) qout << from; else qout << "(none)"; qout << " -> " << to->index() << endl; } qDebug("%s", buf.data().constData()); } } void setImmediateDominator(BasicBlock *bb, BasicBlock *newDominator) { Q_ASSERT(bb->index() >= 0); Q_ASSERT(!newDominator || newDominator->index() >= 0); if (static_cast<std::vector<BasicBlockIndex>::size_type>(bb->index()) >= idom.size()) { // This is a new block, probably introduced by edge splitting. So, we'll have to grow // the array before inserting the immediate dominator. idom.resize(function->basicBlockCount(), InvalidBasicBlockIndex); } const BasicBlockIndex newIdx = newDominator ? newDominator->index() : InvalidBasicBlockIndex; if (DebugImmediateDominators) qDebug() << "Setting idom of" << bb->index() << "from" << idom[bb->index()] << "to" << newIdx; idom[bb->index()] = newIdx; } void collectSiblings(BasicBlock *node, BasicBlockSet &siblings) { siblings.insert(node); const BasicBlockIndex dominator = idom[node->index()]; if (dominator == InvalidBasicBlockIndex) return; for (size_t i = 0, ei = idom.size(); i != ei; ++i) { if (idom[i] == dominator) { BasicBlock *bb = function->basicBlock(int(i)); if (!bb->isRemoved()) siblings.insert(bb); } } } void recalculateIDoms(const BasicBlockSet &nodes, BasicBlock *limit = 0) { const BasicBlockIndex limitIndex = limit ? limit->index() : InvalidBasicBlockIndex; BasicBlockSet todo(nodes), postponed(function); while (!todo.empty()) recalculateIDom(*todo.begin(), todo, postponed, limitIndex); } bool dominates(BasicBlock *dominator, BasicBlock *dominated) const { return dominates(dominator->index(), dominated->index()); } struct Cmp { std::vector<int> *nodeDepths; Cmp(std::vector<int> *nodeDepths) : nodeDepths(nodeDepths) { Q_ASSERT(nodeDepths); } bool operator()(BasicBlock *one, BasicBlock *two) const { if (one->isRemoved()) return false; if (two->isRemoved()) return true; return nodeDepths->at(one->index()) > nodeDepths->at(two->index()); } }; // Calculate a depth-first iteration order on the nodes of the dominator tree. // // The order of the nodes in the vector is not the same as one where a recursive depth-first // iteration is done on a tree. Rather, the nodes are (reverse) sorted on tree depth. // So for the: // 1 dominates 2 // 2 dominates 3 // 3 dominates 4 // 2 dominates 5 // the order will be: // 4, 3, 5, 2, 1 // or: // 4, 5, 3, 2, 1 // So the order of nodes on the same depth is undefined, but it will be after the nodes // they dominate, and before the nodes that dominate them. // // The reason for this order is that a proper DFS pre-/post-order would require inverting // the idom vector by either building a real tree datastructure or by searching the idoms // for siblings and children. Both have a higher time complexity than sorting by depth. QVector<BasicBlock *> calculateDFNodeIterOrder() const { std::vector<int> depths = calculateNodeDepths(); QVector<BasicBlock *> order = function->basicBlocks(); std::sort(order.begin(), order.end(), Cmp(&depths)); for (int i = 0; i < order.size(); ) { if (order[i]->isRemoved()) order.remove(i); else ++i; } return order; } private: bool dominates(BasicBlockIndex dominator, BasicBlockIndex dominated) const { // dominator can be Invalid when the dominated block has no dominator (i.e. the start node) Q_ASSERT(dominated != InvalidBasicBlockIndex); if (dominator == dominated) return false; for (BasicBlockIndex it = idom[dominated]; it != InvalidBasicBlockIndex; it = idom[it]) { if (it == dominator) return true; } return false; } // Algorithm: // - for each node: // - get the depth of a node. If it's unknown (-1): // - get the depth of the immediate dominator. // - if that's unknown too, calculate it by calling calculateNodeDepth // - set the current node's depth to that of immediate dominator + 1 std::vector<int> calculateNodeDepths() const { std::vector<int> nodeDepths(size_t(function->basicBlockCount()), -1); nodeDepths[0] = 0; foreach (BasicBlock *bb, function->basicBlocks()) { if (bb->isRemoved()) continue; int &bbDepth = nodeDepths[bb->index()]; if (bbDepth == -1) { const int immDom = idom[bb->index()]; int immDomDepth = nodeDepths[immDom]; if (immDomDepth == -1) immDomDepth = calculateNodeDepth(immDom, nodeDepths); bbDepth = immDomDepth + 1; } } return nodeDepths; } // Algorithm: // - search for the first dominator of a node that has a known depth. As all nodes are // reachable from the start node, and that node's depth is 0, this is finite. // - while doing that search, put all unknown nodes in the worklist // - pop all nodes from the worklist, and set their depth to the previous' (== dominating) // node's depth + 1 // This way every node's depth is calculated once, and the complexity is O(n). int calculateNodeDepth(int nodeIdx, std::vector<int> &nodeDepths) const { std::vector<int> worklist; worklist.reserve(8); int depth = -1; do { worklist.push_back(nodeIdx); nodeIdx = idom[nodeIdx]; depth = nodeDepths[nodeIdx]; } while (depth == -1); for (std::vector<int>::const_reverse_iterator it = worklist.rbegin(), eit = worklist.rend(); it != eit; ++it) nodeDepths[*it] = ++depth; return depth; } // The immediate-dominator recalculation is used when edges are removed from the CFG. See // [Ramalingam] for a description. Note that instead of calculating the priority, a recursive // algorithm is used: when recalculating the immediate dominator of a node by looking for the // least-common ancestor, and a node is hit that also needs recalculation, a recursive call // is done to calculate that nodes immediate dominator first. // // Note that this simplified algorithm cannot cope with back-edges. It only works for // non-looping edges (which is our use-case). void recalculateIDom(BasicBlock *node, BasicBlockSet &todo, BasicBlockSet &postponed, BasicBlockIndex limit) { Q_ASSERT(!postponed.contains(node)); Q_ASSERT(todo.contains(node)); todo.remove(node); if (node->in.size() == 1) { // Special case: if the node has only one incoming edge, then that is the immediate // dominator. setImmediateDominator(node, node->in.first()); return; } std::vector<BasicBlockIndex> prefix; prefix.reserve(32); for (int i = 0, ei = node->in.size(); i != ei; ++i) { BasicBlock *in = node->in.at(i); if (node == in) // back-edge to self continue; if (dominates(node->index(), in->index())) // a known back-edge continue; if (prefix.empty()) { calculatePrefix(node, in, prefix, todo, postponed, limit); if (!prefix.empty()) { std::reverse(prefix.begin(), prefix.end()); Q_ASSERT(!prefix.empty()); Q_ASSERT(prefix.front() == limit || limit == InvalidBasicBlockIndex); } } else { std::vector<BasicBlockIndex> anotherPrefix; anotherPrefix.reserve(prefix.size()); calculatePrefix(node, in, anotherPrefix, todo, postponed, limit); if (!anotherPrefix.empty()) commonPrefix(prefix, anotherPrefix); } } Q_ASSERT(!prefix.empty()); idom[node->index()] = prefix.back(); } void calculatePrefix(BasicBlock *node, BasicBlock *in, std::vector<BasicBlockIndex> &prefix, BasicBlockSet &todo, BasicBlockSet &postponed, BasicBlockIndex limit) { for (BasicBlockIndex it = in->index(); it != InvalidBasicBlockIndex; it = idom[it]) { prefix.push_back(it); if (it == limit) return; BasicBlock *n = function->basicBlock(it); if (postponed.contains(n)) { // possible back-edge, bail out. prefix.clear(); return; } if (todo.contains(n)) { postponed.insert(node); recalculateIDom(n, todo, postponed, limit); postponed.remove(node); } } } // Calculate the LCA (Least Common Ancestor) by finding the longest common prefix between two // dominator chains. Note that "anotherPrefix" has the node's immediate dominator first, while // "bestPrefix" has it last (meaning: is in reverse order). The reason for this is that removing // nodes from "bestPrefix" is cheaper because it's done at the end of the vector, while // reversing all "anotherPrefix" nodes would take unnecessary time. static void commonPrefix(std::vector<BasicBlockIndex> &bestPrefix, const std::vector<BasicBlockIndex> &anotherPrefix) { const size_t anotherSize = anotherPrefix.size(); size_t minLen = qMin(bestPrefix.size(), anotherPrefix.size()); while (minLen != 0) { --minLen; if (bestPrefix[minLen] == anotherPrefix[anotherSize - minLen - 1]) { ++minLen; break; } } if (minLen != bestPrefix.size()) bestPrefix.erase(bestPrefix.begin() + minLen, bestPrefix.end()); } }; class VariableCollector: public StmtVisitor, ExprVisitor { std::vector<Temp> _allTemps; std::vector<BasicBlockSet> _defsites; std::vector<std::vector<int> > A_orig; BitVector nonLocals; BitVector killed; BasicBlock *currentBB; bool isCollectable(Temp *t) const { Q_UNUSED(t); Q_ASSERT(t->kind != Temp::PhysicalRegister && t->kind != Temp::StackSlot); return true; } void addDefInCurrentBlock(Temp *t) { std::vector<int> &temps = A_orig[currentBB->index()]; if (std::find(temps.begin(), temps.end(), t->index) == temps.end()) temps.push_back(t->index); } void addTemp(Temp *t) { if (_allTemps[t->index].kind == Temp::Invalid) _allTemps[t->index] = *t; } public: VariableCollector(IR::Function *function) { _allTemps.resize(function->tempCount); _defsites.resize(function->tempCount); for (int i = 0; i < function->tempCount; ++i) _defsites[i].init(function); nonLocals.resize(function->tempCount); const size_t ei = function->basicBlockCount(); A_orig.resize(ei); for (size_t i = 0; i != ei; ++i) A_orig[i].reserve(8); foreach (BasicBlock *bb, function->basicBlocks()) { if (bb->isRemoved()) continue; currentBB = bb; killed.assign(function->tempCount, false); foreach (Stmt *s, bb->statements()) s->accept(this); } } const std::vector<Temp> &allTemps() const { return _allTemps; } void collectDefSites(const Temp &n, std::vector<BasicBlock *> &bbs) const { Q_ASSERT(!n.isInvalid()); Q_ASSERT(n.index < _defsites.size()); _defsites[n.index].collectValues(bbs); } const std::vector<int> &inBlock(BasicBlock *n) const { return A_orig.at(n->index()); } bool isNonLocal(const Temp &var) const { Q_ASSERT(!var.isInvalid()); Q_ASSERT(static_cast<int>(var.index) < nonLocals.size()); return nonLocals.at(var.index); } protected: virtual void visitPhi(Phi *) {} virtual void visitConvert(Convert *e) { e->expr->accept(this); } virtual void visitConst(Const *) {} virtual void visitString(IR::String *) {} virtual void visitRegExp(IR::RegExp *) {} virtual void visitName(Name *) {} virtual void visitArgLocal(ArgLocal *) {} virtual void visitClosure(Closure *) {} virtual void visitUnop(Unop *e) { e->expr->accept(this); } virtual void visitBinop(Binop *e) { e->left->accept(this); e->right->accept(this); } virtual void visitSubscript(Subscript *e) { e->base->accept(this); e->index->accept(this); } virtual void visitMember(Member *e) { e->base->accept(this); } virtual void visitExp(Exp *s) { s->expr->accept(this); } virtual void visitJump(Jump *) {} virtual void visitCJump(CJump *s) { s->cond->accept(this); } virtual void visitRet(Ret *s) { s->expr->accept(this); } virtual void visitCall(Call *e) { e->base->accept(this); for (ExprList *it = e->args; it; it = it->next) it->expr->accept(this); } virtual void visitNew(New *e) { e->base->accept(this); for (ExprList *it = e->args; it; it = it->next) it->expr->accept(this); } virtual void visitMove(Move *s) { s->source->accept(this); if (Temp *t = s->target->asTemp()) { addTemp(t); if (isCollectable(t)) { _defsites[t->index].insert(currentBB); addDefInCurrentBlock(t); // For semi-pruned SSA: killed.setBit(t->index); } } else { s->target->accept(this); } } virtual void visitTemp(Temp *t) { addTemp(t); if (isCollectable(t)) if (!killed.at(t->index)) nonLocals.setBit(t->index); } }; struct UntypedTemp { Temp temp; UntypedTemp() {} UntypedTemp(const Temp &t): temp(t) {} }; inline bool operator==(const UntypedTemp &t1, const UntypedTemp &t2) Q_DECL_NOTHROW { return t1.temp.index == t2.temp.index && t1.temp.kind == t2.temp.kind; } inline bool operator!=(const UntypedTemp &t1, const UntypedTemp &t2) Q_DECL_NOTHROW { return !(t1 == t2); } class DefUses { public: struct DefUse { DefUse() : defStmt(0) , blockOfStatement(0) { uses.reserve(8); } Temp temp; Stmt *defStmt; BasicBlock *blockOfStatement; QVector<Stmt *> uses; bool isValid() const { return temp.kind != Temp::Invalid; } void clear() { defStmt = 0; blockOfStatement = 0; uses.clear(); } }; private: std::vector<DefUse> _defUses; typedef QVarLengthArray<Temp, 4> Temps; std::vector<Temps> _usesPerStatement; void ensure(Temp *newTemp) { if (_defUses.size() <= newTemp->index) { _defUses.resize(newTemp->index + 1); } } void ensure(Stmt *s) { Q_ASSERT(s->id() >= 0); if (static_cast<unsigned>(s->id()) >= _usesPerStatement.size()) { _usesPerStatement.resize(s->id() + 1); } } void addUseForStatement(Stmt *s, const Temp &var) { ensure(s); _usesPerStatement[s->id()].push_back(var); } public: DefUses(IR::Function *function) { _usesPerStatement.resize(function->statementCount()); _defUses.resize(function->tempCount); } void cleanup() { for (size_t i = 0, ei = _defUses.size(); i != ei; ++i) { DefUse &defUse = _defUses[i]; if (defUse.isValid() && !defUse.defStmt) defUse.clear(); } } unsigned statementCount() const { return unsigned(_usesPerStatement.size()); } unsigned tempCount() const { return unsigned(_defUses.size()); } const Temp &temp(int idx) const { return _defUses[idx].temp; } void addDef(Temp *newTemp, Stmt *defStmt, BasicBlock *defBlock) { ensure(newTemp); DefUse &defUse = _defUses[newTemp->index]; Q_ASSERT(!defUse.isValid()); defUse.temp = *newTemp; defUse.defStmt = defStmt; defUse.blockOfStatement = defBlock; } QVector<UntypedTemp> defsUntyped() const { QVector<UntypedTemp> res; res.reserve(tempCount()); foreach (const DefUse &du, _defUses) if (du.isValid()) res.append(UntypedTemp(du.temp)); return res; } std::vector<const Temp *> defs() const { std::vector<const Temp *> res; const size_t ei = _defUses.size(); res.reserve(ei); for (size_t i = 0; i != ei; ++i) { const DefUse &du = _defUses.at(i); if (du.isValid()) res.push_back(&du.temp); } return res; } void removeDef(const Temp &variable) { Q_ASSERT(static_cast<unsigned>(variable.index) < _defUses.size()); _defUses[variable.index].clear(); } void addUses(const Temp &variable, const QVector<Stmt *> &newUses) { Q_ASSERT(static_cast<unsigned>(variable.index) < _defUses.size()); QVector<Stmt *> &uses = _defUses[variable.index].uses; foreach (Stmt *stmt, newUses) if (std::find(uses.begin(), uses.end(), stmt) == uses.end()) uses.push_back(stmt); } void addUse(const Temp &variable, Stmt *newUse) { if (_defUses.size() <= variable.index) { _defUses.resize(variable.index + 1); DefUse &du = _defUses[variable.index]; du.temp = variable; du.uses.push_back(newUse); addUseForStatement(newUse, variable); return; } QVector<Stmt *> &uses = _defUses[variable.index].uses; if (std::find(uses.begin(), uses.end(), newUse) == uses.end()) uses.push_back(newUse); addUseForStatement(newUse, variable); } int useCount(const Temp &variable) const { Q_ASSERT(static_cast<unsigned>(variable.index) < _defUses.size()); return _defUses[variable.index].uses.size(); } Stmt *defStmt(const Temp &variable) const { Q_ASSERT(static_cast<unsigned>(variable.index) < _defUses.size()); return _defUses[variable.index].defStmt; } BasicBlock *defStmtBlock(const Temp &variable) const { Q_ASSERT(static_cast<unsigned>(variable.index) < _defUses.size()); return _defUses[variable.index].blockOfStatement; } void removeUse(Stmt *usingStmt, const Temp &var) { Q_ASSERT(static_cast<unsigned>(var.index) < _defUses.size()); QVector<Stmt *> &uses = _defUses[var.index].uses; uses.erase(std::remove(uses.begin(), uses.end(), usingStmt), uses.end()); } void registerNewStatement(Stmt *s) { ensure(s); } const Temps &usedVars(Stmt *s) const { Q_ASSERT(s->id() >= 0); Q_ASSERT(static_cast<unsigned>(s->id()) < _usesPerStatement.size()); return _usesPerStatement[s->id()]; } const QVector<Stmt *> &uses(const Temp &var) const { return _defUses[var.index].uses; } QVector<Stmt*> removeDefUses(Stmt *s) { QVector<Stmt*> defStmts; foreach (const Temp &usedVar, usedVars(s)) { if (Stmt *ds = defStmt(usedVar)) defStmts += ds; removeUse(s, usedVar); } if (Move *m = s->asMove()) { if (Temp *t = m->target->asTemp()) removeDef(*t); } else if (Phi *p = s->asPhi()) { removeDef(*p->targetTemp); } return defStmts; } void dump() const { QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream qout(&buf); qout << "Defines and uses:" << endl; foreach (const DefUse &du, _defUses) { if (!du.isValid()) continue; qout << '%' << du.temp.index; qout << " -> defined in block " << du.blockOfStatement->index() << ", statement: " << du.defStmt->id() << endl; qout << " uses:"; foreach (Stmt *s, du.uses) qout << ' ' << s->id(); qout << endl; } qout << "Uses per statement:" << endl; for (size_t i = 0, ei = _usesPerStatement.size(); i != ei; ++i) { qout << " " << i << ":"; foreach (const Temp &t, _usesPerStatement[i]) qout << ' ' << t.index; qout << endl; } qDebug("%s", buf.data().constData()); } }; void insertPhiNode(const Temp &a, BasicBlock *y, IR::Function *f) { Phi *phiNode = f->NewStmt<Phi>(); phiNode->d = new Phi::Data; phiNode->targetTemp = f->New<Temp>(); phiNode->targetTemp->init(a.kind, a.index); y->prependStatement(phiNode); phiNode->d->incoming.resize(y->in.size()); for (int i = 0, ei = y->in.size(); i < ei; ++i) { Temp *t = f->New<Temp>(); t->init(a.kind, a.index); phiNode->d->incoming[i] = t; } } // High-level (recursive) algorithm: // Mapping: old temp number -> new temp number // // Start: // Rename(start-node) // // Rename(node, mapping): // for each statement S in block n // if S not in a phi-function // for each use of some variable x in S // y = mapping[x] // replace the use of x with y in S // for each definition of some variable a in S [1] // a_new = generate new/unique temp // mapping[a] = a_new // replace definition of a with definition of a_new in S // for each successor Y of block n // Suppose n is the j-th predecessor of Y // for each phi function in Y // suppose the j-th operand of the phi-function is a // i = mapping[a] // replace the j-th operand with a_i // for each child X of n [2] // Rename(X) // for each newly generated temp from step [1] restore the old value [3] // // This algorithm can run out of CPU stack space when there are lots of basic-blocks, like in a // switch statement with 8000 cases that all fall-through. The iterativer version below uses a // work-item stack, where step [1] from the algorithm above also pushes an "undo mapping change", // and step [2] pushes a "rename(X)" action. This eliminates step [3]. // // Iterative version: // Mapping: old temp number -> new temp number // // The stack can hold two kinds of actions: // "Rename basic block n" // "Restore count for temp" // // Start: // counter = 0 // push "Rename start node" onto the stack // while the stack is not empty: // take the last item, and process it // // Rename(n) = // for each statement S in block n // if S not in a phi-function // for each use of some variable x in S // y = mapping[x] // replace the use of x with y in S // for each definition of some variable a in S // old = mapping[a] // push Undo(a, old) // counter = counter + 1 // new = counter; // mapping[a] = new // replace definition of a with definition of a_new in S // for each successor Y of block n // Suppose n is the j-th predecessor of Y // for each phi function in Y // suppose the j-th operand of the phi-function is a // i = mapping[a] // replace the j-th operand with a_i // for each child X of n // push Rename(X) // // Undo(t, c) = // mapping[t] = c class VariableRenamer: public StmtVisitor, public ExprVisitor { Q_DISABLE_COPY(VariableRenamer) IR::Function *function; DefUses &defUses; unsigned tempCount; typedef std::vector<int> Mapping; // maps from existing/old temp number to the new and unique temp number. enum { Absent = -1 }; Mapping vregMapping; ProcessedBlocks processed; BasicBlock *currentBB; Stmt *currentStmt; struct TodoAction { enum { RestoreVReg, Rename } action; union { struct { unsigned temp; int previous; } restoreData; struct { BasicBlock *basicBlock; } renameData; }; bool isValid() const { return action != Rename || renameData.basicBlock != 0; } TodoAction() { action = Rename; renameData.basicBlock = 0; } TodoAction(const Temp &t, int prev) { Q_ASSERT(t.kind == Temp::VirtualRegister); action = RestoreVReg; restoreData.temp = t.index; restoreData.previous = prev; } TodoAction(BasicBlock *bb) { Q_ASSERT(bb); action = Rename; renameData.basicBlock = bb; } }; QVector<TodoAction> todo; public: VariableRenamer(IR::Function *f, DefUses &defUses) : function(f) , defUses(defUses) , tempCount(0) , processed(f) { vregMapping.assign(f->tempCount, Absent); todo.reserve(f->basicBlockCount()); } void run() { todo.append(TodoAction(function->basicBlock(0))); while (!todo.isEmpty()) { TodoAction todoAction = todo.back(); Q_ASSERT(todoAction.isValid()); todo.pop_back(); switch (todoAction.action) { case TodoAction::Rename: rename(todoAction.renameData.basicBlock); break; case TodoAction::RestoreVReg: restore(vregMapping, todoAction.restoreData.temp, todoAction.restoreData.previous); break; default: Q_UNREACHABLE(); } } function->tempCount = tempCount; } private: static inline void restore(Mapping &mapping, int temp, int previous) { mapping[temp] = previous; } void rename(BasicBlock *bb) { while (bb && !processed.alreadyProcessed(bb)) { renameStatementsAndPhis(bb); processed.markAsProcessed(bb); BasicBlock *next = 0; foreach (BasicBlock *out, bb->out) { if (processed.alreadyProcessed(out)) continue; if (!next) next = out; else todo.append(TodoAction(out)); } bb = next; } } void renameStatementsAndPhis(BasicBlock *bb) { currentBB = bb; foreach (Stmt *s, bb->statements()) { currentStmt = s; s->accept(this); } foreach (BasicBlock *Y, bb->out) { const int j = Y->in.indexOf(bb); Q_ASSERT(j >= 0 && j < Y->in.size()); foreach (Stmt *s, Y->statements()) { if (Phi *phi = s->asPhi()) { Temp *t = phi->d->incoming[j]->asTemp(); unsigned newTmp = currentNumber(*t); // qDebug()<<"I: replacing phi use"<<a<<"with"<<newTmp<<"in L"<<Y->index; t->index = newTmp; t->kind = Temp::VirtualRegister; defUses.addUse(*t, phi); } else { break; } } } } unsigned currentNumber(const Temp &t) { int nr = Absent; switch (t.kind) { case Temp::VirtualRegister: nr = vregMapping[t.index]; break; default: Q_UNREACHABLE(); nr = Absent; break; } if (nr == Absent) { // Special case: we didn't prune the Phi nodes yet, so for proper temps (virtual // registers) the SSA algorithm might insert superfluous Phis that have uses without // definition. E.g.: if a temporary got introduced in the "then" clause, it "could" // reach the "end-if" block, so there will be a phi node for that temp. A later pass // will clean this up by looking for uses-without-defines in phi nodes. So, what we do // is to generate a new unique number, and leave it dangling. nr = nextFreeTemp(t); } return nr; } unsigned nextFreeTemp(const Temp &t) { unsigned newIndex = tempCount++; Q_ASSERT(newIndex <= INT_MAX); int oldIndex = Absent; switch (t.kind) { case Temp::VirtualRegister: oldIndex = vregMapping[t.index]; vregMapping[t.index] = newIndex; break; default: Q_UNREACHABLE(); } todo.append(TodoAction(t, oldIndex)); return newIndex; } protected: virtual void visitTemp(Temp *e) { // only called for uses, not defs // qDebug()<<"I: replacing use of"<<e->index<<"with"<<stack[e->index].top(); e->index = currentNumber(*e); e->kind = Temp::VirtualRegister; defUses.addUse(*e, currentStmt); } virtual void visitMove(Move *s) { // uses: s->source->accept(this); // defs: if (Temp *t = s->target->asTemp()) renameTemp(t); else s->target->accept(this); } void renameTemp(Temp *t) { // only called for defs, not uses const int newIdx = nextFreeTemp(*t); // qDebug()<<"I: replacing def of"<<a<<"with"<<newIdx; t->kind = Temp::VirtualRegister; t->index = newIdx; defUses.addDef(t, currentStmt, currentBB); } virtual void visitConvert(Convert *e) { e->expr->accept(this); } virtual void visitPhi(Phi *s) { renameTemp(s->targetTemp); } virtual void visitExp(Exp *s) { s->expr->accept(this); } virtual void visitJump(Jump *) {} virtual void visitCJump(CJump *s) { s->cond->accept(this); } virtual void visitRet(Ret *s) { s->expr->accept(this); } virtual void visitConst(Const *) {} virtual void visitString(IR::String *) {} virtual void visitRegExp(IR::RegExp *) {} virtual void visitName(Name *) {} virtual void visitArgLocal(ArgLocal *) {} virtual void visitClosure(Closure *) {} virtual void visitUnop(Unop *e) { e->expr->accept(this); } virtual void visitBinop(Binop *e) { e->left->accept(this); e->right->accept(this); } virtual void visitCall(Call *e) { e->base->accept(this); for (ExprList *it = e->args; it; it = it->next) it->expr->accept(this); } virtual void visitNew(New *e) { e->base->accept(this); for (ExprList *it = e->args; it; it = it->next) it->expr->accept(this); } virtual void visitSubscript(Subscript *e) { e->base->accept(this); e->index->accept(this); } virtual void visitMember(Member *e) { e->base->accept(this); } }; // This function converts the IR to semi-pruned SSA form. For details about SSA and the algorightm, // see [Appel]. For the changes needed for semi-pruned SSA form, and for its advantages, see [Briggs]. void convertToSSA(IR::Function *function, const DominatorTree &df, DefUses &defUses) { // Collect all applicable variables: VariableCollector variables(function); // Prepare for phi node insertion: std::vector<BitVector > A_phi; const size_t ei = function->basicBlockCount(); A_phi.resize(ei); for (size_t i = 0; i != ei; ++i) A_phi[i].assign(function->tempCount, false); std::vector<BasicBlock *> W; W.reserve(8); // Place phi functions: foreach (const Temp &a, variables.allTemps()) { if (a.isInvalid()) continue; if (!variables.isNonLocal(a)) continue; // for semi-pruned SSA W.clear(); variables.collectDefSites(a, W); while (!W.empty()) { BasicBlock *n = W.back(); W.pop_back(); const BasicBlockSet &dominatorFrontierForN = df.dominatorFrontier(n); for (BasicBlockSet::const_iterator it = dominatorFrontierForN.begin(), eit = dominatorFrontierForN.end(); it != eit; ++it) { BasicBlock *y = *it; if (!A_phi.at(y->index()).at(a.index)) { insertPhiNode(a, y, function); A_phi[y->index()].setBit(a.index); const std::vector<int> &varsInBlockY = variables.inBlock(y); if (std::find(varsInBlockY.begin(), varsInBlockY.end(), a.index) == varsInBlockY.end()) W.push_back(y); } } } } // Rename variables: VariableRenamer(function, defUses).run(); } /// Calculate if a phi node result is used only by other phi nodes, and if those uses are /// in turn also used by other phi nodes. bool hasPhiOnlyUses(Phi *phi, const DefUses &defUses, QBitArray &collectedPhis) { collectedPhis.setBit(phi->id()); foreach (Stmt *use, defUses.uses(*phi->targetTemp)) { Phi *dependentPhi = use->asPhi(); if (!dependentPhi) return false; // there is a use by a non-phi node if (collectedPhis.at(dependentPhi->id())) continue; // we already found this node if (!hasPhiOnlyUses(dependentPhi, defUses, collectedPhis)) return false; } return true; } void cleanupPhis(DefUses &defUses) { QBitArray toRemove(defUses.statementCount()); QBitArray collectedPhis(defUses.statementCount()); std::vector<Phi *> allPhis; allPhis.reserve(32); foreach (const Temp *def, defUses.defs()) { Stmt *defStmt = defUses.defStmt(*def); if (!defStmt) continue; Phi *phi = defStmt->asPhi(); if (!phi) continue; allPhis.push_back(phi); if (toRemove.at(phi->id())) continue; collectedPhis.fill(false); if (hasPhiOnlyUses(phi, defUses, collectedPhis)) toRemove |= collectedPhis; } foreach (Phi *phi, allPhis) { if (!toRemove.at(phi->id())) continue; const Temp &targetVar = *phi->targetTemp; defUses.defStmtBlock(targetVar)->removeStatement(phi); foreach (const Temp &usedVar, defUses.usedVars(phi)) defUses.removeUse(phi, usedVar); defUses.removeDef(targetVar); } defUses.cleanup(); } class StatementWorklist { IR::Function *theFunction; std::vector<Stmt *> stmts; BitVector worklist; unsigned worklistSize; std::vector<int> replaced; BitVector removed; Q_DISABLE_COPY(StatementWorklist) public: StatementWorklist(IR::Function *function) : theFunction(function) , stmts(function->statementCount(), static_cast<Stmt *>(0)) , worklist(function->statementCount(), false) , worklistSize(0) , replaced(function->statementCount(), Stmt::InvalidId) , removed(function->statementCount()) { grow(); foreach (BasicBlock *bb, function->basicBlocks()) { if (bb->isRemoved()) continue; foreach (Stmt *s, bb->statements()) { if (!s) continue; stmts[s->id()] = s; worklist.setBit(s->id()); ++worklistSize; } } } void reset() { worklist.assign(worklist.size(), false); worklistSize = 0; foreach (Stmt *s, stmts) { if (!s) continue; worklist.setBit(s->id()); ++worklistSize; } replaced.assign(replaced.size(), Stmt::InvalidId); removed.assign(removed.size(), false); } void remove(Stmt *stmt) { replaced[stmt->id()] = Stmt::InvalidId; removed.setBit(stmt->id()); if (worklist.at(stmt->id())) { worklist.clearBit(stmt->id()); Q_ASSERT(worklistSize > 0); --worklistSize; } } void replace(Stmt *oldStmt, Stmt *newStmt) { Q_ASSERT(oldStmt); Q_ASSERT(replaced[oldStmt->id()] == Stmt::InvalidId); Q_ASSERT(removed.at(oldStmt->id()) == false); Q_ASSERT(newStmt); registerNewStatement(newStmt); Q_ASSERT(replaced[newStmt->id()] == Stmt::InvalidId); Q_ASSERT(removed.at(newStmt->id()) == false); replaced[oldStmt->id()] = newStmt->id(); worklist.clearBit(oldStmt->id()); } void applyToFunction() { foreach (BasicBlock *bb, theFunction->basicBlocks()) { if (bb->isRemoved()) continue; for (int i = 0; i < bb->statementCount();) { Stmt *stmt = bb->statements().at(i); int id = stmt->id(); Q_ASSERT(id != Stmt::InvalidId); Q_ASSERT(static_cast<unsigned>(stmt->id()) < stmts.size()); for (int replacementId = replaced[id]; replacementId != Stmt::InvalidId; replacementId = replaced[replacementId]) id = replacementId; Q_ASSERT(id != Stmt::InvalidId); Q_ASSERT(static_cast<unsigned>(stmt->id()) < stmts.size()); if (removed.at(id)) { bb->removeStatement(i); } else { if (id != stmt->id()) bb->replaceStatement(i, stmts[id]); ++i; } } } replaced.assign(replaced.size(), Stmt::InvalidId); removed.assign(removed.size(), false); } StatementWorklist &operator+=(const QVector<Stmt *> &stmts) { foreach (Stmt *s, stmts) this->operator+=(s); return *this; } StatementWorklist &operator+=(Stmt *s) { if (!s) return *this; Q_ASSERT(s->id() >= 0); Q_ASSERT(s->id() < worklist.size()); if (!worklist.at(s->id())) { worklist.setBit(s->id()); ++worklistSize; } return *this; } StatementWorklist &operator-=(Stmt *s) { Q_ASSERT(s->id() >= 0); Q_ASSERT(s->id() < worklist.size()); if (worklist.at(s->id())) { worklist.clearBit(s->id()); Q_ASSERT(worklistSize > 0); --worklistSize; } return *this; } Stmt *takeNext(Stmt *last) { if (worklistSize == 0) return 0; const int startAt = last ? last->id() + 1 : 0; Q_ASSERT(startAt >= 0); Q_ASSERT(startAt <= worklist.size()); Q_ASSERT(static_cast<size_t>(worklist.size()) == stmts.size()); int pos = worklist.findNext(startAt, true, /*wrapAround = */true); worklist.clearBit(pos); Q_ASSERT(worklistSize > 0); --worklistSize; Stmt *s = stmts.at(pos); Q_ASSERT(s); if (removed.at(s->id())) return takeNext(s); return s; } IR::Function *function() const { return theFunction; } void registerNewStatement(Stmt *s) { Q_ASSERT(s->id() >= 0); if (static_cast<unsigned>(s->id()) >= stmts.size()) { if (static_cast<unsigned>(s->id()) >= stmts.capacity()) grow(); int newSize = s->id() + 1; stmts.resize(newSize, 0); worklist.resize(newSize); replaced.resize(newSize, Stmt::InvalidId); removed.resize(newSize); } stmts[s->id()] = s; } private: void grow() { Q_ASSERT(stmts.capacity() < INT_MAX / 2); int newCapacity = ((static_cast<int>(stmts.capacity()) + 1) * 3) / 2; stmts.reserve(newCapacity); worklist.reserve(newCapacity); replaced.reserve(newCapacity); removed.reserve(newCapacity); } }; class SideEffectsChecker: public ExprVisitor { bool _sideEffect; public: SideEffectsChecker() : _sideEffect(false) {} bool hasSideEffects(Expr *expr) { bool sideEffect = false; qSwap(_sideEffect, sideEffect); expr->accept(this); qSwap(_sideEffect, sideEffect); return sideEffect; } protected: void markAsSideEffect() { _sideEffect = true; } bool seenSideEffects() const { return _sideEffect; } protected: void visitConst(Const *) Q_DECL_OVERRIDE {} void visitString(IR::String *) Q_DECL_OVERRIDE {} void visitRegExp(IR::RegExp *) Q_DECL_OVERRIDE {} void visitName(Name *e) Q_DECL_OVERRIDE { if (e->freeOfSideEffects) return; // TODO: maybe we can distinguish between built-ins of which we know that they do not have // a side-effect. if (e->builtin == Name::builtin_invalid || (e->id && *e->id != QStringLiteral("this"))) markAsSideEffect(); } void visitTemp(Temp *) Q_DECL_OVERRIDE {} void visitArgLocal(ArgLocal *) Q_DECL_OVERRIDE {} void visitClosure(Closure *) Q_DECL_OVERRIDE { markAsSideEffect(); } void visitConvert(Convert *e) Q_DECL_OVERRIDE { e->expr->accept(this); switch (e->expr->type) { case QObjectType: case StringType: case VarType: markAsSideEffect(); break; default: break; } } void visitUnop(Unop *e) Q_DECL_OVERRIDE { e->expr->accept(this); switch (e->op) { case OpUPlus: case OpUMinus: case OpNot: case OpIncrement: case OpDecrement: if (e->expr->type == VarType || e->expr->type == StringType || e->expr->type == QObjectType) markAsSideEffect(); break; default: break; } } void visitBinop(Binop *e) Q_DECL_OVERRIDE { // TODO: prune parts that don't have a side-effect. For example, in: // function f(x) { +x+1; return 0; } // we can prune the binop and leave the unop/conversion. _sideEffect = hasSideEffects(e->left); _sideEffect |= hasSideEffects(e->right); if (e->left->type == VarType || e->left->type == StringType || e->left->type == QObjectType || e->right->type == VarType || e->right->type == StringType || e->right->type == QObjectType) markAsSideEffect(); } void visitSubscript(Subscript *e) Q_DECL_OVERRIDE { e->base->accept(this); e->index->accept(this); markAsSideEffect(); } void visitMember(Member *e) Q_DECL_OVERRIDE { e->base->accept(this); if (e->freeOfSideEffects) return; markAsSideEffect(); } void visitCall(Call *e) Q_DECL_OVERRIDE { e->base->accept(this); for (ExprList *args = e->args; args; args = args->next) args->expr->accept(this); markAsSideEffect(); // TODO: there are built-in functions that have no side effect. } void visitNew(New *e) Q_DECL_OVERRIDE { e->base->accept(this); for (ExprList *args = e->args; args; args = args->next) args->expr->accept(this); markAsSideEffect(); // TODO: there are built-in types that have no side effect. } }; class EliminateDeadCode: public SideEffectsChecker { DefUses &_defUses; StatementWorklist &_worklist; QVector<Temp *> _collectedTemps; public: EliminateDeadCode(DefUses &defUses, StatementWorklist &worklist) : _defUses(defUses) , _worklist(worklist) { _collectedTemps.reserve(8); } void run(Expr *&expr, Stmt *stmt) { _collectedTemps.clear(); if (!hasSideEffects(expr)) { expr = 0; foreach (Temp *t, _collectedTemps) { _defUses.removeUse(stmt, *t); _worklist += _defUses.defStmt(*t); } } } protected: void visitTemp(Temp *e) Q_DECL_OVERRIDE { _collectedTemps.append(e); } }; struct DiscoveredType { int type; MemberExpressionResolver *memberResolver; DiscoveredType() : type(UnknownType), memberResolver(0) {} DiscoveredType(Type t) : type(t), memberResolver(0) { Q_ASSERT(type != QObjectType); } explicit DiscoveredType(int t) : type(t), memberResolver(0) { Q_ASSERT(type != QObjectType); } explicit DiscoveredType(MemberExpressionResolver *memberResolver) : type(QObjectType) , memberResolver(memberResolver) { Q_ASSERT(memberResolver); } bool test(Type t) const { return type & t; } bool isNumber() const { return (type & NumberType) && !(type & ~NumberType); } bool operator!=(Type other) const { return type != other; } bool operator==(Type other) const { return type == other; } bool operator==(const DiscoveredType &other) const { return type == other.type; } bool operator!=(const DiscoveredType &other) const { return type != other.type; } }; class PropagateTempTypes: public StmtVisitor, ExprVisitor { const DefUses &defUses; UntypedTemp theTemp; DiscoveredType newType; public: PropagateTempTypes(const DefUses &defUses) : defUses(defUses) {} void run(const UntypedTemp &temp, const DiscoveredType &type) { newType = type; theTemp = temp; if (Stmt *defStmt = defUses.defStmt(temp.temp)) defStmt->accept(this); foreach (Stmt *use, defUses.uses(temp.temp)) use->accept(this); } protected: virtual void visitConst(Const *) {} virtual void visitString(IR::String *) {} virtual void visitRegExp(IR::RegExp *) {} virtual void visitName(Name *) {} virtual void visitTemp(Temp *e) { if (theTemp == UntypedTemp(*e)) { e->type = static_cast<Type>(newType.type); e->memberResolver = newType.memberResolver; } } virtual void visitArgLocal(ArgLocal *) {} virtual void visitClosure(Closure *) {} virtual void visitConvert(Convert *e) { e->expr->accept(this); } virtual void visitUnop(Unop *e) { e->expr->accept(this); } virtual void visitBinop(Binop *e) { e->left->accept(this); e->right->accept(this); } virtual void visitCall(Call *e) { e->base->accept(this); for (ExprList *it = e->args; it; it = it->next) it->expr->accept(this); } virtual void visitNew(New *e) { e->base->accept(this); for (ExprList *it = e->args; it; it = it->next) it->expr->accept(this); } virtual void visitSubscript(Subscript *e) { e->base->accept(this); e->index->accept(this); } virtual void visitMember(Member *e) { e->base->accept(this); } virtual void visitExp(Exp *s) {s->expr->accept(this);} virtual void visitMove(Move *s) { s->source->accept(this); s->target->accept(this); } virtual void visitJump(Jump *) {} virtual void visitCJump(CJump *s) { s->cond->accept(this); } virtual void visitRet(Ret *s) { s->expr->accept(this); } virtual void visitPhi(Phi *s) { s->targetTemp->accept(this); foreach (Expr *e, s->d->incoming) e->accept(this); } }; class TypeInference: public StmtVisitor, public ExprVisitor { enum { DebugTypeInference = 0 }; QQmlEnginePrivate *qmlEngine; const DefUses &_defUses; typedef std::vector<DiscoveredType> TempTypes; TempTypes _tempTypes; StatementWorklist *_worklist; struct TypingResult { DiscoveredType type; bool fullyTyped; TypingResult(const DiscoveredType &type = DiscoveredType()) { #if defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 6 // avoid optimization bug in gcc 4.6.3 armhf ((int volatile &) this->type.type) = type.type; #endif this->type = type; fullyTyped = type.type != UnknownType; } explicit TypingResult(MemberExpressionResolver *memberResolver) : type(memberResolver) , fullyTyped(true) {} }; TypingResult _ty; public: TypeInference(QQmlEnginePrivate *qmlEngine, const DefUses &defUses) : qmlEngine(qmlEngine) , _defUses(defUses) , _tempTypes(_defUses.tempCount()) , _worklist(0) , _ty(UnknownType) {} void run(StatementWorklist &w) { _worklist = &w; Stmt *s = 0; while ((s = _worklist->takeNext(s))) { if (s->asJump()) continue; if (DebugTypeInference) { QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream qout(&buf); qout<<"Typing stmt "; IRPrinter(&qout).print(s); qDebug("%s", buf.data().constData()); } if (!run(s)) { *_worklist += s; if (DebugTypeInference) { QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream qout(&buf); qout<<"Pushing back stmt: "; IRPrinter(&qout).print(s); qDebug("%s", buf.data().constData()); } } else { if (DebugTypeInference) { QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream qout(&buf); qout<<"Finished: "; IRPrinter(&qout).print(s); qDebug("%s", buf.data().constData()); } } } PropagateTempTypes propagator(_defUses); for (size_t i = 0, ei = _tempTypes.size(); i != ei; ++i) { const Temp &temp = _defUses.temp(int(i)); if (temp.kind == Temp::Invalid) continue; const DiscoveredType &tempType = _tempTypes[i]; if (tempType.type == UnknownType) continue; propagator.run(temp, tempType); } _worklist = 0; } private: bool run(Stmt *s) { TypingResult ty; std::swap(_ty, ty); s->accept(this); std::swap(_ty, ty); return ty.fullyTyped; } TypingResult run(Expr *e) { TypingResult ty; std::swap(_ty, ty); e->accept(this); std::swap(_ty, ty); if (ty.type != UnknownType) setType(e, ty.type); return ty; } void setType(Expr *e, DiscoveredType ty) { if (Temp *t = e->asTemp()) { if (DebugTypeInference) qDebug() << "Setting type for temp" << t->index << " to " << typeName(Type(ty.type)) << "(" << ty.type << ")" << endl; DiscoveredType &it = _tempTypes[t->index]; if (it != ty) { it = ty; if (DebugTypeInference) { foreach (Stmt *s, _defUses.uses(*t)) { QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream qout(&buf); qout << "Pushing back dependent stmt: "; IRPrinter(&qout).print(s); qDebug("%s", buf.data().constData()); } } *_worklist += _defUses.uses(*t); } } else { e->type = (Type) ty.type; } } protected: virtual void visitConst(Const *e) { if (e->type & NumberType) { if (canConvertToSignedInteger(e->value)) _ty = TypingResult(SInt32Type); else if (canConvertToUnsignedInteger(e->value)) _ty = TypingResult(UInt32Type); else _ty = TypingResult(e->type); } else _ty = TypingResult(e->type); } virtual void visitString(IR::String *) { _ty = TypingResult(StringType); } virtual void visitRegExp(IR::RegExp *) { _ty = TypingResult(VarType); } virtual void visitName(Name *) { _ty = TypingResult(VarType); } virtual void visitTemp(Temp *e) { if (e->memberResolver && e->memberResolver->isValid()) _ty = TypingResult(e->memberResolver); else _ty = TypingResult(_tempTypes[e->index]); setType(e, _ty.type); } virtual void visitArgLocal(ArgLocal *e) { _ty = TypingResult(VarType); setType(e, _ty.type); } virtual void visitClosure(Closure *) { _ty = TypingResult(VarType); } virtual void visitConvert(Convert *e) { _ty = TypingResult(e->type); } virtual void visitUnop(Unop *e) { _ty = run(e->expr); switch (e->op) { case OpUPlus: _ty.type = DoubleType; return; case OpUMinus: _ty.type = DoubleType; return; case OpCompl: _ty.type = SInt32Type; return; case OpNot: _ty.type = BoolType; return; case OpIncrement: case OpDecrement: Q_ASSERT(!"Inplace operators should have been removed!"); default: Q_UNIMPLEMENTED(); Q_UNREACHABLE(); } } virtual void visitBinop(Binop *e) { TypingResult leftTy = run(e->left); TypingResult rightTy = run(e->right); _ty.fullyTyped = leftTy.fullyTyped && rightTy.fullyTyped; switch (e->op) { case OpAdd: if (leftTy.type.test(VarType) || leftTy.type.test(QObjectType) || rightTy.type.test(VarType) || rightTy.type.test(QObjectType)) _ty.type = VarType; else if (leftTy.type.test(StringType) || rightTy.type.test(StringType)) _ty.type = StringType; else if (leftTy.type != UnknownType && rightTy.type != UnknownType) _ty.type = DoubleType; else _ty.type = UnknownType; break; case OpSub: _ty.type = DoubleType; break; case OpMul: case OpDiv: case OpMod: _ty.type = DoubleType; break; case OpBitAnd: case OpBitOr: case OpBitXor: case OpLShift: case OpRShift: _ty.type = SInt32Type; break; case OpURShift: _ty.type = UInt32Type; break; case OpGt: case OpLt: case OpGe: case OpLe: case OpEqual: case OpNotEqual: case OpStrictEqual: case OpStrictNotEqual: case OpAnd: case OpOr: case OpInstanceof: case OpIn: _ty.type = BoolType; break; default: Q_UNIMPLEMENTED(); Q_UNREACHABLE(); } } virtual void visitCall(Call *e) { _ty = run(e->base); for (ExprList *it = e->args; it; it = it->next) _ty.fullyTyped &= run(it->expr).fullyTyped; _ty.type = VarType; } virtual void visitNew(New *e) { _ty = run(e->base); for (ExprList *it = e->args; it; it = it->next) _ty.fullyTyped &= run(it->expr).fullyTyped; _ty.type = VarType; } virtual void visitSubscript(Subscript *e) { _ty.fullyTyped = run(e->base).fullyTyped && run(e->index).fullyTyped; _ty.type = VarType; } virtual void visitMember(Member *e) { _ty = run(e->base); if (_ty.fullyTyped && _ty.type.memberResolver && _ty.type.memberResolver->isValid()) { MemberExpressionResolver *resolver = _ty.type.memberResolver; _ty.type.type = resolver->resolveMember(qmlEngine, resolver, e); } else _ty.type = VarType; } virtual void visitExp(Exp *s) { _ty = run(s->expr); } virtual void visitMove(Move *s) { TypingResult sourceTy = run(s->source); if (Temp *t = s->target->asTemp()) { setType(t, sourceTy.type); _ty = sourceTy; return; } _ty = run(s->target); _ty.fullyTyped &= sourceTy.fullyTyped; } virtual void visitJump(Jump *) { _ty = TypingResult(MissingType); } virtual void visitCJump(CJump *s) { _ty = run(s->cond); } virtual void visitRet(Ret *s) { _ty = run(s->expr); } virtual void visitPhi(Phi *s) { _ty = run(s->d->incoming[0]); for (int i = 1, ei = s->d->incoming.size(); i != ei; ++i) { TypingResult ty = run(s->d->incoming[i]); if (!ty.fullyTyped && _ty.fullyTyped) { // When one of the temps not fully typed, we already know that we cannot completely type this node. // So, pick the type we calculated upto this point, and wait until the unknown one will be typed. // At that point, this statement will be re-scheduled, and then we can fully type this node. _ty.fullyTyped = false; break; } _ty.type.type |= ty.type.type; _ty.fullyTyped &= ty.fullyTyped; if (_ty.type.test(QObjectType) && _ty.type.memberResolver) _ty.type.memberResolver->clear(); // ### TODO: find common ancestor meta-object } switch (_ty.type.type) { case UnknownType: case UndefinedType: case NullType: case BoolType: case SInt32Type: case UInt32Type: case DoubleType: case StringType: case QObjectType: case VarType: // The type is not a combination of two or more types, so we're done. break; default: // There are multiple types involved, so: if (_ty.type.isNumber()) // The type is any combination of double/int32/uint32, but nothing else. So we can // type it as double. _ty.type = DoubleType; else // There just is no single type that can hold this combination, so: _ty.type = VarType; } setType(s->targetTemp, _ty.type); } }; class ReverseInference { const DefUses &_defUses; public: ReverseInference(const DefUses &defUses) : _defUses(defUses) {} void run(IR::Function *f) { Q_UNUSED(f); QVector<UntypedTemp> knownOk; QVector<UntypedTemp> candidates = _defUses.defsUntyped(); while (!candidates.isEmpty()) { UntypedTemp temp = candidates.last(); candidates.removeLast(); if (knownOk.contains(temp)) continue; if (!isUsedAsInt32(temp, knownOk)) continue; Stmt *s = _defUses.defStmt(temp.temp); Move *m = s->asMove(); if (!m) continue; Temp *target = m->target->asTemp(); if (!target || temp != UntypedTemp(*target) || target->type == SInt32Type) continue; if (Temp *t = m->source->asTemp()) { candidates.append(*t); } else if (m->source->asConvert()) { break; } else if (Binop *b = m->source->asBinop()) { bool iterateOnOperands = true; switch (b->op) { case OpSub: case OpMul: case OpAdd: if (b->left->type == SInt32Type && b->right->type == SInt32Type) { iterateOnOperands = false; break; } else { continue; } case OpBitAnd: case OpBitOr: case OpBitXor: case OpLShift: case OpRShift: case OpURShift: break; default: continue; } if (iterateOnOperands) { if (Temp *lt = b->left->asTemp()) candidates.append(*lt); if (Temp *rt = b->right->asTemp()) candidates.append(*rt); } } else if (Unop *u = m->source->asUnop()) { if (u->op == OpCompl || u->op == OpUPlus) { if (Temp *t = u->expr->asTemp()) candidates.append(*t); } } else { continue; } knownOk.append(temp); } PropagateTempTypes propagator(_defUses); foreach (const UntypedTemp &t, knownOk) { propagator.run(t, SInt32Type); if (Stmt *defStmt = _defUses.defStmt(t.temp)) { if (Move *m = defStmt->asMove()) { if (Convert *c = m->source->asConvert()) { c->type = SInt32Type; } else if (Unop *u = m->source->asUnop()) { if (u->op != OpUMinus) u->type = SInt32Type; } else if (Binop *b = m->source->asBinop()) { b->type = SInt32Type; } } } } } private: bool isUsedAsInt32(const UntypedTemp &t, const QVector<UntypedTemp> &knownOk) const { const QVector<Stmt *> &uses = _defUses.uses(t.temp); if (uses.isEmpty()) return false; foreach (Stmt *use, uses) { if (Move *m = use->asMove()) { Temp *targetTemp = m->target->asTemp(); if (m->source->asTemp()) { if (!targetTemp || !knownOk.contains(*targetTemp)) return false; } else if (m->source->asConvert()) { continue; } else if (Binop *b = m->source->asBinop()) { switch (b->op) { case OpAdd: case OpSub: case OpMul: if (!targetTemp || !knownOk.contains(*targetTemp)) return false; case OpBitAnd: case OpBitOr: case OpBitXor: case OpRShift: case OpLShift: case OpURShift: continue; default: return false; } } else if (Unop *u = m->source->asUnop()) { if (u->op == OpUPlus) { if (!targetTemp || !knownOk.contains(*targetTemp)) return false; } else if (u->op != OpCompl) { return false; } } else { return false; } } else return false; } return true; } }; void convertConst(Const *c, Type targetType) { switch (targetType) { case DoubleType: break; case SInt32Type: c->value = QV4::Primitive::toInt32(c->value); break; case UInt32Type: c->value = QV4::Primitive::toUInt32(c->value); break; case BoolType: c->value = !(c->value == 0 || std::isnan(c->value)); break; case NullType: case UndefinedType: c->value = qSNaN(); c->type = targetType; default: Q_UNIMPLEMENTED(); Q_ASSERT(!"Unimplemented!"); break; } c->type = targetType; } class TypePropagation: public StmtVisitor, public ExprVisitor { DefUses &_defUses; Type _ty; IR::Function *_f; bool run(Expr *&e, Type requestedType = UnknownType, bool insertConversion = true) { qSwap(_ty, requestedType); e->accept(this); qSwap(_ty, requestedType); if (requestedType != UnknownType) { if (e->type != requestedType) { if (requestedType & NumberType || requestedType == BoolType) { if (insertConversion) addConversion(e, requestedType); return true; } } } return false; } struct Conversion { Expr **expr; Type targetType; Stmt *stmt; Conversion(Expr **expr = 0, Type targetType = UnknownType, Stmt *stmt = 0) : expr(expr) , targetType(targetType) , stmt(stmt) {} }; Stmt *_currStmt; QVector<Conversion> _conversions; void addConversion(Expr *&expr, Type targetType) { _conversions.append(Conversion(&expr, targetType, _currStmt)); } public: TypePropagation(DefUses &defUses) : _defUses(defUses), _ty(UnknownType) {} void run(IR::Function *f, StatementWorklist &worklist) { _f = f; foreach (BasicBlock *bb, f->basicBlocks()) { if (bb->isRemoved()) continue; _conversions.clear(); foreach (Stmt *s, bb->statements()) { _currStmt = s; s->accept(this); } foreach (const Conversion &conversion, _conversions) { IR::Move *move = conversion.stmt->asMove(); // Note: isel only supports move into member when source is a temp, so convert // is not a supported source. if (move && move->source->asTemp() && !move->target->asMember()) { *conversion.expr = bb->CONVERT(*conversion.expr, conversion.targetType); } else if (Const *c = (*conversion.expr)->asConst()) { convertConst(c, conversion.targetType); } else if (ArgLocal *al = (*conversion.expr)->asArgLocal()) { Temp *target = bb->TEMP(bb->newTemp()); target->type = conversion.targetType; Expr *convert = bb->CONVERT(al, conversion.targetType); Move *convCall = f->NewStmt<Move>(); worklist.registerNewStatement(convCall); convCall->init(target, convert); _defUses.addDef(target, convCall, bb); Temp *source = bb->TEMP(target->index); source->type = conversion.targetType; _defUses.addUse(*source, conversion.stmt); if (conversion.stmt->asPhi()) { // Only temps can be used as arguments to phi nodes, so this is a sanity check...: Q_UNREACHABLE(); } else { bb->insertStatementBefore(conversion.stmt, convCall); } *conversion.expr = source; } else if (Temp *t = (*conversion.expr)->asTemp()) { Temp *target = bb->TEMP(bb->newTemp()); target->type = conversion.targetType; Expr *convert = bb->CONVERT(t, conversion.targetType); Move *convCall = f->NewStmt<Move>(); worklist.registerNewStatement(convCall); convCall->init(target, convert); _defUses.addDef(target, convCall, bb); _defUses.addUse(*t, convCall); Temp *source = bb->TEMP(target->index); source->type = conversion.targetType; _defUses.removeUse(conversion.stmt, *t); _defUses.addUse(*source, conversion.stmt); if (Phi *phi = conversion.stmt->asPhi()) { int idx = phi->d->incoming.indexOf(t); Q_ASSERT(idx != -1); bb->in[idx]->insertStatementBeforeTerminator(convCall); } else { bb->insertStatementBefore(conversion.stmt, convCall); } *conversion.expr = source; } else if (Unop *u = (*conversion.expr)->asUnop()) { // convert: // int32{%2} = double{-double{%1}}; // to: // double{%3} = double{-double{%1}}; // int32{%2} = int32{convert(double{%3})}; Temp *tmp = bb->TEMP(bb->newTemp()); tmp->type = u->type; Move *extraMove = f->NewStmt<Move>(); worklist.registerNewStatement(extraMove); extraMove->init(tmp, u); _defUses.addDef(tmp, extraMove, bb); if (Temp *unopOperand = u->expr->asTemp()) { _defUses.addUse(*unopOperand, extraMove); _defUses.removeUse(move, *unopOperand); } bb->insertStatementBefore(conversion.stmt, extraMove); *conversion.expr = bb->CONVERT(CloneExpr::cloneTemp(tmp, f), conversion.targetType); _defUses.addUse(*tmp, move); } else { Q_UNREACHABLE(); } } } } protected: virtual void visitConst(Const *c) { if (_ty & NumberType && c->type & NumberType) { if (_ty == SInt32Type) c->value = QV4::Primitive::toInt32(c->value); else if (_ty == UInt32Type) c->value = QV4::Primitive::toUInt32(c->value); c->type = _ty; } } virtual void visitString(IR::String *) {} virtual void visitRegExp(IR::RegExp *) {} virtual void visitName(Name *) {} virtual void visitTemp(Temp *) {} virtual void visitArgLocal(ArgLocal *) {} virtual void visitClosure(Closure *) {} virtual void visitConvert(Convert *e) { run(e->expr, e->type); } virtual void visitUnop(Unop *e) { run(e->expr, e->type); } virtual void visitBinop(Binop *e) { // FIXME: This routine needs more tuning! switch (e->op) { case OpAdd: case OpSub: case OpMul: case OpDiv: case OpMod: case OpBitAnd: case OpBitOr: case OpBitXor: run(e->left, e->type); run(e->right, e->type); break; case OpLShift: case OpRShift: case OpURShift: run(e->left, SInt32Type); run(e->right, SInt32Type); break; case OpGt: case OpLt: case OpGe: case OpLe: case OpEqual: case OpNotEqual: if (e->left->type == DoubleType) { run(e->right, DoubleType); } else if (e->right->type == DoubleType) { run(e->left, DoubleType); } else { run(e->left, e->left->type); run(e->right, e->right->type); } break; case OpStrictEqual: case OpStrictNotEqual: case OpInstanceof: case OpIn: run(e->left, e->left->type); run(e->right, e->right->type); break; default: Q_UNIMPLEMENTED(); Q_UNREACHABLE(); } } virtual void visitCall(Call *e) { run(e->base); for (ExprList *it = e->args; it; it = it->next) run(it->expr); } virtual void visitNew(New *e) { run(e->base); for (ExprList *it = e->args; it; it = it->next) run(it->expr); } virtual void visitSubscript(Subscript *e) { run(e->base); run(e->index); } virtual void visitMember(Member *e) { run(e->base); } virtual void visitExp(Exp *s) { run(s->expr); } virtual void visitMove(Move *s) { if (s->source->asConvert()) return; // this statement got inserted for a phi-node type conversion run(s->target); if (Unop *u = s->source->asUnop()) { if (u->op == OpUPlus) { if (run(u->expr, s->target->type, false)) { Convert *convert = _f->New<Convert>(); convert->init(u->expr, s->target->type); s->source = convert; } else { s->source = u->expr; } return; } } const Member *targetMember = s->target->asMember(); const bool inhibitConversion = targetMember && targetMember->inhibitTypeConversionOnWrite; run(s->source, s->target->type, !inhibitConversion); } virtual void visitJump(Jump *) {} virtual void visitCJump(CJump *s) { run(s->cond, BoolType); } virtual void visitRet(Ret *s) { run(s->expr); } virtual void visitPhi(Phi *s) { Type ty = s->targetTemp->type; for (int i = 0, ei = s->d->incoming.size(); i != ei; ++i) run(s->d->incoming[i], ty); } }; void splitCriticalEdges(IR::Function *f, DominatorTree &df, StatementWorklist &worklist, DefUses &defUses) { foreach (BasicBlock *toBB, f->basicBlocks()) { if (toBB->isRemoved()) continue; if (toBB->in.size() < 2) continue; for (int inIdx = 0, eInIdx = toBB->in.size(); inIdx != eInIdx; ++inIdx) { BasicBlock *fromBB = toBB->in[inIdx]; if (fromBB->out.size() < 2) continue; // We found a critical edge. // create the basic block: BasicBlock *newBB = f->newBasicBlock(toBB->catchBlock); Jump *s = f->NewStmt<Jump>(); worklist.registerNewStatement(s); defUses.registerNewStatement(s); s->init(toBB); newBB->appendStatement(s); // rewire the old outgoing edge int outIdx = fromBB->out.indexOf(toBB); fromBB->out[outIdx] = newBB; newBB->in.append(fromBB); // rewire the old incoming edge toBB->in[inIdx] = newBB; newBB->out.append(toBB); // add newBB to the correct loop group if (toBB->isGroupStart()) { BasicBlock *container; for (container = fromBB->containingGroup(); container; container = container->containingGroup()) if (container == toBB) break; if (container == toBB) // if we were already inside the toBB loop newBB->setContainingGroup(toBB); else newBB->setContainingGroup(toBB->containingGroup()); } else { newBB->setContainingGroup(toBB->containingGroup()); } // patch the terminator Stmt *terminator = fromBB->terminator(); if (Jump *j = terminator->asJump()) { Q_ASSERT(outIdx == 0); j->target = newBB; } else if (CJump *j = terminator->asCJump()) { if (outIdx == 0) j->iftrue = newBB; else if (outIdx == 1) j->iffalse = newBB; else Q_ASSERT(!"Invalid out edge index for CJUMP!"); } else if (terminator->asRet()) { Q_ASSERT(!"A block with a RET at the end cannot have outgoing edges."); } else { Q_ASSERT(!"Unknown terminator!"); } // qDebug() << "splitting edge" << fromBB->index() << "->" << toBB->index() // << "by inserting block" << newBB->index(); // Set the immediate dominator of the new block to inBB df.setImmediateDominator(newBB, fromBB); bool toNeedsNewIdom = true; foreach (BasicBlock *bb, toBB->in) { if (bb != newBB && !df.dominates(toBB, bb)) { toNeedsNewIdom = false; break; } } if (toNeedsNewIdom) df.setImmediateDominator(toBB, newBB); } } } // Detect all (sub-)loops in a function. // // Doing loop detection on the CFG is better than relying on the statement information in // order to mark loops. Although JavaScript only has natural loops, it can still be the case // that something is not a loop even though a loop-like-statement is in the source. For // example: // while (true) { // if (i > 0) // break; // else // break; // } // // Algorithm: // - do a DFS on the dominator tree, where for each node: // - collect all back-edges // - if there are back-edges, the node is a loop-header for a new loop, so: // - walk the CFG is reverse-direction, and for every node: // - if the node already belongs to a loop, we've found a nested loop: // - get the loop-header for the (outermost) nested loop // - add that loop-header to the current loop // - continue by walking all incoming edges that do not yet belong to the current loop // - if the node does not belong to a loop yet, add it to the current loop, and // go on with all incoming edges // // Loop-header detection by checking for back-edges is very straight forward: a back-edge is // an incoming edge where the other node is dominated by the current node. Meaning: all // execution paths that reach that other node have to go through the current node, that other // node ends with a (conditional) jump back to the loop header. // // The exact order of the DFS on the dominator tree is not important. The only property has to // be that a node is only visited when all the nodes it dominates have been visited before. // The reason for the DFS is that for nested loops, the inner loop's loop-header is dominated // by the outer loop's header. So, by visiting depth-first, sub-loops are identified before // their containing loops, which makes nested-loop identification free. An added benefit is // that the nodes for those sub-loops are only processed once. // // Note: independent loops that share the same header are merged together. For example, in // the code snippet below, there are 2 back-edges into the loop-header, but only one single // loop will be detected. // while (a) { // if (b) // continue; // else // continue; // } class LoopDetection { enum { DebugLoopDetection = 0 }; Q_DISABLE_COPY(LoopDetection) public: struct LoopInfo { BasicBlock *loopHeader; QVector<BasicBlock *> loopBody; QVector<LoopInfo *> nestedLoops; LoopInfo *parentLoop; LoopInfo(BasicBlock *loopHeader = 0) : loopHeader(loopHeader) , parentLoop(0) {} bool isValid() const { return loopHeader != 0; } void addNestedLoop(LoopInfo *nested) { Q_ASSERT(nested); Q_ASSERT(!nestedLoops.contains(nested)); Q_ASSERT(nested->parentLoop == 0); nested->parentLoop = this; nestedLoops.append(nested); } }; public: LoopDetection(const DominatorTree &dt) : dt(dt) {} ~LoopDetection() { qDeleteAll(loopInfos); } void run(IR::Function *function) { std::vector<BasicBlock *> backedges; backedges.reserve(4); foreach (BasicBlock *bb, dt.calculateDFNodeIterOrder()) { Q_ASSERT(!bb->isRemoved()); backedges.clear(); foreach (BasicBlock *in, bb->in) if (dt.dominates(bb, in)) backedges.push_back(in); if (!backedges.empty()) { subLoop(bb, backedges); } } createLoopInfos(function); dumpLoopInfo(); } void dumpLoopInfo() const { if (!DebugLoopDetection) return; foreach (LoopInfo *info, loopInfos) { qDebug() << "Loop header:" << info->loopHeader->index() << "for loop" << quint64(info); foreach (BasicBlock *bb, info->loopBody) qDebug() << " " << bb->index(); foreach (LoopInfo *nested, info->nestedLoops) qDebug() << " sub loop:" << quint64(nested); qDebug() << " parent loop:" << quint64(info->parentLoop); } } QVector<LoopInfo *> allLoops() const { return loopInfos; } // returns all loop headers for loops that have no nested loops. QVector<LoopInfo *> innermostLoops() const { QVector<LoopInfo *> inner(loopInfos); for (int i = 0; i < inner.size(); ) { if (inner.at(i)->nestedLoops.isEmpty()) ++i; else inner.remove(i); } return inner; } private: void subLoop(BasicBlock *loopHead, const std::vector<BasicBlock *> &backedges) { loopHead->markAsGroupStart(); std::vector<BasicBlock *> worklist; worklist.reserve(backedges.size() + 8); worklist.insert(worklist.end(), backedges.begin(), backedges.end()); while (!worklist.empty()) { BasicBlock *predIt = worklist.back(); worklist.pop_back(); BasicBlock *subloop = predIt->containingGroup(); if (subloop) { // This is a discovered block. Find its outermost discovered loop. while (BasicBlock *parentLoop = subloop->containingGroup()) subloop = parentLoop; // If it is already discovered to be a subloop of this loop, continue. if (subloop == loopHead) continue; // Yay, it's a subloop of this loop. subloop->setContainingGroup(loopHead); predIt = subloop; // Add all predecessors of the subloop header to the worklist, as long as // those predecessors are not in the current subloop. It might be the case // that they are in other loops, which we will then add as a subloop to the // current loop. foreach (BasicBlock *predIn, predIt->in) if (predIn->containingGroup() != subloop) worklist.push_back(predIn); } else { if (predIt == loopHead) continue; // This is an undiscovered block. Map it to the current loop. predIt->setContainingGroup(loopHead); // Add all incoming edges to the worklist. foreach (BasicBlock *bb, predIt->in) worklist.push_back(bb); } } } private: const DominatorTree &dt; QVector<LoopInfo *> loopInfos; void createLoopInfos(IR::Function *function) { foreach (BasicBlock *bb, function->basicBlocks()) { if (bb->isRemoved()) continue; if (BasicBlock *loopHeader = bb->containingGroup()) findLoop(loopHeader)->loopBody.append(bb); } foreach (LoopInfo *info, loopInfos) { if (BasicBlock *containingLoopHeader = info->loopHeader->containingGroup()) findLoop(containingLoopHeader)->addNestedLoop(info); } } LoopInfo *findLoop(BasicBlock *loopHeader) { foreach (LoopInfo *info, loopInfos) { if (info->loopHeader == loopHeader) return info; } LoopInfo *info = new LoopInfo; info->loopHeader = loopHeader; loopInfos.append(info); return info; } }; // High-level algorithm: // 0. start with the first node (the start node) of a function // 1. emit the node // 2. add all outgoing edges that are not yet emitted to the postponed stack // 3. When the postponed stack is empty, pop a stack from the loop stack. If that is empty too, // we're done. // 4. pop a node from the postponed stack, and check if it can be scheduled: // a. if all incoming edges are scheduled, go to 4. // b. if an incoming edge is unscheduled, but it's a back-edge (an edge in a loop that jumps // back to the start of the loop), ignore it // c. if there is any unscheduled edge that is not a back-edge, ignore this node, and go to 4. // 5. if this node is the start of a loop, push the postponed stack on the loop stack. // 6. go back to 1. // // The postponing action in step 2 will put the node into its containing group. The case where this // is important is when a (labeled) continue or a (labeled) break statement occur in a loop: the // outgoing edge points to a node that is not part of the current loop (and possibly not of the // parent loop). // // Linear scan register allocation benefits greatly from short life-time intervals with few holes // (see for example section 4 (Lifetime Analysis) of [Wimmer1]). This algorithm makes sure that the // blocks of a group are scheduled together, with no non-loop blocks in between. This applies // recursively for nested loops. It also schedules groups of if-then-else-endif blocks together for // the same reason. class BlockScheduler { IR::Function *function; const DominatorTree &dominatorTree; struct WorkForGroup { BasicBlock *group; QStack<BasicBlock *> postponed; WorkForGroup(BasicBlock *group = 0): group(group) {} }; WorkForGroup currentGroup; QStack<WorkForGroup> postponedGroups; QVector<BasicBlock *> sequence; ProcessedBlocks emitted; QHash<BasicBlock *, BasicBlock *> loopsStartEnd; bool checkCandidate(BasicBlock *candidate) { Q_ASSERT(candidate->containingGroup() == currentGroup.group); foreach (BasicBlock *in, candidate->in) { if (emitted.alreadyProcessed(in)) continue; if (dominatorTree.dominates(candidate, in)) // this is a loop, where there in -> candidate edge is the jump back to the top of the loop. continue; return false; // an incoming edge that is not yet emitted, and is not a back-edge } if (candidate->isGroupStart()) { // postpone everything, and schedule the loop first. postponedGroups.push(currentGroup); currentGroup = WorkForGroup(candidate); } return true; } BasicBlock *pickNext() { while (true) { while (currentGroup.postponed.isEmpty()) { if (postponedGroups.isEmpty()) return 0; if (currentGroup.group) // record the first and the last node of a group loopsStartEnd.insert(currentGroup.group, sequence.last()); currentGroup = postponedGroups.pop(); } BasicBlock *next = currentGroup.postponed.pop(); if (checkCandidate(next)) return next; } Q_UNREACHABLE(); return 0; } void emitBlock(BasicBlock *bb) { Q_ASSERT(!bb->isRemoved()); if (emitted.alreadyProcessed(bb)) return; sequence.append(bb); emitted.markAsProcessed(bb); } void schedule(BasicBlock *functionEntryPoint) { BasicBlock *next = functionEntryPoint; while (next) { emitBlock(next); for (int i = next->out.size(); i != 0; ) { // postpone all outgoing edges, if they were not already processed --i; BasicBlock *out = next->out[i]; if (!emitted.alreadyProcessed(out)) postpone(out); } next = pickNext(); } } void postpone(BasicBlock *bb) { if (currentGroup.group == bb->containingGroup()) { currentGroup.postponed.append(bb); return; } for (int i = postponedGroups.size(); i != 0; ) { --i; WorkForGroup &g = postponedGroups[i]; if (g.group == bb->containingGroup()) { g.postponed.append(bb); return; } } Q_UNREACHABLE(); } public: BlockScheduler(IR::Function *function, const DominatorTree &dominatorTree) : function(function) , dominatorTree(dominatorTree) , sequence(0) , emitted(function) {} QHash<BasicBlock *, BasicBlock *> go() { showMeTheCode(function, "Before block scheduling"); schedule(function->basicBlock(0)); Q_ASSERT(function->liveBasicBlocksCount() == sequence.size()); function->setScheduledBlocks(sequence); function->renumberBasicBlocks(); return loopsStartEnd; } }; #ifndef QT_NO_DEBUG void checkCriticalEdges(QVector<BasicBlock *> basicBlocks) { foreach (BasicBlock *bb, basicBlocks) { if (bb && bb->out.size() > 1) { foreach (BasicBlock *bb2, bb->out) { if (bb2 && bb2->in.size() > 1) { qDebug() << "found critical edge between block" << bb->index() << "and block" << bb2->index(); Q_ASSERT(false); } } } } } #endif static void cleanupBasicBlocks(IR::Function *function) { showMeTheCode(function, "Before basic block cleanup"); // Algorithm: this is the iterative version of a depth-first search for all blocks that are // reachable through outgoing edges, starting with the start block and all exception handler // blocks. QBitArray reachableBlocks(function->basicBlockCount()); QVarLengthArray<BasicBlock *, 16> postponed; for (int i = 0, ei = function->basicBlockCount(); i != ei; ++i) { BasicBlock *bb = function->basicBlock(i); if (i == 0 || bb->isExceptionHandler()) postponed.append(bb); } while (!postponed.isEmpty()) { BasicBlock *bb = postponed.back(); postponed.pop_back(); if (bb->isRemoved()) // this block was removed before, we don't need to clean it up. continue; reachableBlocks.setBit(bb->index()); foreach (BasicBlock *outBB, bb->out) { if (!reachableBlocks.at(outBB->index())) postponed.append(outBB); } } foreach (BasicBlock *bb, function->basicBlocks()) { if (bb->isRemoved()) // the block has already been removed, so ignore it continue; if (reachableBlocks.at(bb->index())) // the block is reachable, so ignore it continue; foreach (BasicBlock *outBB, bb->out) { if (outBB->isRemoved() || !reachableBlocks.at(outBB->index())) continue; // We do not need to unlink from blocks that are scheduled to be removed. int idx = outBB->in.indexOf(bb); if (idx != -1) { outBB->in.remove(idx); foreach (Stmt *s, outBB->statements()) { if (Phi *phi = s->asPhi()) phi->d->incoming.remove(idx); else break; } } } function->removeBasicBlock(bb); } showMeTheCode(function, "After basic block cleanup"); } inline Const *isConstPhi(Phi *phi) { if (Const *c = phi->d->incoming[0]->asConst()) { for (int i = 1, ei = phi->d->incoming.size(); i != ei; ++i) { if (Const *cc = phi->d->incoming[i]->asConst()) { if (c->value != cc->value) return 0; if (!(c->type == cc->type || (c->type & NumberType && cc->type & NumberType))) return 0; if (int(c->value) == 0 && int(cc->value) == 0) if (isNegative(c->value) != isNegative(cc->value)) return 0; } else { return 0; } } return c; } return 0; } static Expr *clone(Expr *e, IR::Function *function) { if (Temp *t = e->asTemp()) { return CloneExpr::cloneTemp(t, function); } else if (Const *c = e->asConst()) { return CloneExpr::cloneConst(c, function); } else if (Name *n = e->asName()) { return CloneExpr::cloneName(n, function); } else { Q_UNREACHABLE(); return e; } } class ExprReplacer: public StmtVisitor, public ExprVisitor { DefUses &_defUses; IR::Function* _function; Temp *_toReplace; Expr *_replacement; public: ExprReplacer(DefUses &defUses, IR::Function *function) : _defUses(defUses) , _function(function) , _toReplace(0) , _replacement(0) {} void operator()(Temp *toReplace, Expr *replacement, StatementWorklist &W, QVector<Stmt *> *newUses = 0) { Q_ASSERT(replacement->asTemp() || replacement->asConst() || replacement->asName()); // qout << "Replacing ";toReplace->dump(qout);qout<<" by ";replacement->dump(qout);qout<<endl; qSwap(_toReplace, toReplace); qSwap(_replacement, replacement); const QVector<Stmt *> &uses = _defUses.uses(*_toReplace); if (newUses) newUses->reserve(uses.size()); // qout << " " << uses.size() << " uses:"<<endl; foreach (Stmt *use, uses) { // qout<<" ";use->dump(qout);qout<<"\n"; use->accept(this); // qout<<" -> ";use->dump(qout);qout<<"\n"; W += use; if (newUses) newUses->push_back(use); } qSwap(_replacement, replacement); qSwap(_toReplace, toReplace); } protected: virtual void visitConst(Const *) {} virtual void visitString(IR::String *) {} virtual void visitRegExp(IR::RegExp *) {} virtual void visitName(Name *) {} virtual void visitTemp(Temp *) {} virtual void visitArgLocal(ArgLocal *) {} virtual void visitClosure(Closure *) {} virtual void visitConvert(Convert *e) { check(e->expr); } virtual void visitUnop(Unop *e) { check(e->expr); } virtual void visitBinop(Binop *e) { check(e->left); check(e->right); } virtual void visitCall(Call *e) { check(e->base); for (ExprList *it = e->args; it; it = it->next) check(it->expr); } virtual void visitNew(New *e) { check(e->base); for (ExprList *it = e->args; it; it = it->next) check(it->expr); } virtual void visitSubscript(Subscript *e) { check(e->base); check(e->index); } virtual void visitMember(Member *e) { check(e->base); } virtual void visitExp(Exp *s) { check(s->expr); } virtual void visitMove(Move *s) { check(s->target); check(s->source); } virtual void visitJump(Jump *) {} virtual void visitCJump(CJump *s) { check(s->cond); } virtual void visitRet(Ret *s) { check(s->expr); } virtual void visitPhi(Phi *s) { for (int i = 0, ei = s->d->incoming.size(); i != ei; ++i) check(s->d->incoming[i]); } private: void check(Expr *&e) { if (equals(e, _toReplace)) e = clone(_replacement, _function); else e->accept(this); } // This only calculates equality for everything needed by constant propagation bool equals(Expr *e1, Expr *e2) const { if (e1 == e2) return true; if (Const *c1 = e1->asConst()) { if (Const *c2 = e2->asConst()) return c1->value == c2->value && (c1->type == c2->type || (c1->type & NumberType && c2->type & NumberType)); } else if (Temp *t1 = e1->asTemp()) { if (Temp *t2 = e2->asTemp()) return *t1 == *t2; } else if (Name *n1 = e1->asName()) { if (Name *n2 = e2->asName()) { if (n1->id) { if (n2->id) return *n1->id == *n2->id; } else { return n1->builtin == n2->builtin; } } } if (e1->type == IR::NullType && e2->type == IR::NullType) return true; if (e1->type == IR::UndefinedType && e2->type == IR::UndefinedType) return true; return false; } }; namespace { /// This function removes the basic-block from the function's list, unlinks any uses and/or defs, /// and removes unreachable staements from the worklist, so that optimiseSSA won't consider them /// anymore. void unlink(BasicBlock *from, BasicBlock *to, IR::Function *func, DefUses &defUses, StatementWorklist &W, DominatorTree &dt) { struct Util { static void removeIncomingEdge(BasicBlock *from, BasicBlock *to, DefUses &defUses, StatementWorklist &W) { int idx = to->in.indexOf(from); if (idx == -1) return; to->in.remove(idx); foreach (Stmt *outStmt, to->statements()) { if (!outStmt) continue; if (Phi *phi = outStmt->asPhi()) { if (Temp *t = phi->d->incoming[idx]->asTemp()) { defUses.removeUse(phi, *t); W += defUses.defStmt(*t); } phi->d->incoming.remove(idx); W += phi; } else { break; } } } static bool isReachable(BasicBlock *bb, const DominatorTree &dt) { foreach (BasicBlock *in, bb->in) { if (in->isRemoved()) continue; if (dt.dominates(bb, in)) // a back-edge, not interesting continue; return true; } return false; } }; // don't purge blocks that are entry points for catch statements. They might not be directly // connected, but are required anyway if (to->isExceptionHandler()) return; // First, unlink the edge from->out.removeOne(to); Util::removeIncomingEdge(from, to, defUses, W); BasicBlockSet siblings; siblings.init(func); // Check if the target is still reachable... if (Util::isReachable(to, dt)) { // yes, recalculate the immediate dominator, and we're done. dt.collectSiblings(to, siblings); } else { // The target is unreachable, so purge it: QVector<BasicBlock *> toPurge; toPurge.reserve(8); toPurge.append(to); while (!toPurge.isEmpty()) { BasicBlock *bb = toPurge.first(); toPurge.removeFirst(); if (bb->isRemoved()) continue; // unlink all incoming edges foreach (BasicBlock *in, bb->in) { int idx = in->out.indexOf(bb); if (idx != -1) in->out.remove(idx); } // unlink all outgoing edges, including "arguments" to phi statements foreach (BasicBlock *out, bb->out) { if (out->isRemoved()) continue; Util::removeIncomingEdge(bb, out, defUses, W); if (Util::isReachable(out, dt)) { dt.collectSiblings(out, siblings); } else { // if a successor has no incoming edges after unlinking the current basic block, // then it is unreachable, and can be purged too toPurge.append(out); } } // unlink all defs/uses from the statements in the basic block foreach (Stmt *s, bb->statements()) { if (!s) continue; W += defUses.removeDefUses(s); W -= s; } siblings.remove(bb); dt.setImmediateDominator(bb, 0); func->removeBasicBlock(bb); } } dt.recalculateIDoms(siblings); } bool tryOptimizingComparison(Expr *&expr) { Binop *b = expr->asBinop(); if (!b) return false; Const *leftConst = b->left->asConst(); if (!leftConst || leftConst->type == StringType || leftConst->type == VarType || leftConst->type == QObjectType) return false; Const *rightConst = b->right->asConst(); if (!rightConst || rightConst->type == StringType || rightConst->type == VarType || rightConst->type == QObjectType) return false; QV4::Primitive l = convertToValue(leftConst); QV4::Primitive r = convertToValue(rightConst); switch (b->op) { case OpGt: leftConst->value = Runtime::compareGreaterThan(l, r); leftConst->type = BoolType; expr = leftConst; return true; case OpLt: leftConst->value = Runtime::compareLessThan(l, r); leftConst->type = BoolType; expr = leftConst; return true; case OpGe: leftConst->value = Runtime::compareGreaterEqual(l, r); leftConst->type = BoolType; expr = leftConst; return true; case OpLe: leftConst->value = Runtime::compareLessEqual(l, r); leftConst->type = BoolType; expr = leftConst; return true; case OpStrictEqual: leftConst->value = Runtime::compareStrictEqual(l, r); leftConst->type = BoolType; expr = leftConst; return true; case OpEqual: leftConst->value = Runtime::compareEqual(l, r); leftConst->type = BoolType; expr = leftConst; return true; case OpStrictNotEqual: leftConst->value = Runtime::compareStrictNotEqual(l, r); leftConst->type = BoolType; expr = leftConst; return true; case OpNotEqual: leftConst->value = Runtime::compareNotEqual(l, r); leftConst->type = BoolType; expr = leftConst; return true; default: break; } return false; } void cfg2dot(IR::Function *f, const QVector<LoopDetection::LoopInfo *> &loops = QVector<LoopDetection::LoopInfo *>()) { static const bool showCode = qEnvironmentVariableIsSet("QV4_SHOW_IR"); if (!showCode) return; QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream qout(&buf); struct Util { QTextStream &qout; Util(QTextStream &qout): qout(qout) {} void genLoop(LoopDetection::LoopInfo *loop) { qout << " subgraph \"cluster" << quint64(loop) << "\" {\n"; qout << " L" << loop->loopHeader->index() << ";\n"; foreach (BasicBlock *bb, loop->loopBody) qout << " L" << bb->index() << ";\n"; foreach (LoopDetection::LoopInfo *nested, loop->nestedLoops) genLoop(nested); qout << " }\n"; } }; QString name; if (f->name) name = *f->name; else name = QStringLiteral("%1").arg((unsigned long long)f); qout << "digraph \"" << name << "\" { ordering=out;\n"; foreach (LoopDetection::LoopInfo *l, loops) { if (l->parentLoop == 0) Util(qout).genLoop(l); } foreach (BasicBlock *bb, f->basicBlocks()) { if (bb->isRemoved()) continue; int idx = bb->index(); qout << " L" << idx << " [label=\"L" << idx << "\""; if (idx == 0 || bb->terminator()->asRet()) qout << ", shape=doublecircle"; else qout << ", shape=circle"; qout << "];\n"; foreach (BasicBlock *out, bb->out) qout << " L" << idx << " -> L" << out->index() << "\n"; } qout << "}\n"; buf.close(); qDebug("%s", buf.data().constData()); } } // anonymous namespace void optimizeSSA(StatementWorklist &W, DefUses &defUses, DominatorTree &df) { IR::Function *function = W.function(); ExprReplacer replaceUses(defUses, function); Stmt *s = 0; while ((s = W.takeNext(s))) { if (Phi *phi = s->asPhi()) { // dead code elimination: if (defUses.useCount(*phi->targetTemp) == 0) { W += defUses.removeDefUses(phi); W.remove(s); continue; } // constant propagation: if (Const *c = isConstPhi(phi)) { replaceUses(phi->targetTemp, c, W); defUses.removeDef(*phi->targetTemp); W.remove(s); continue; } // copy propagation: if (phi->d->incoming.size() == 1) { Temp *t = phi->targetTemp; Expr *e = phi->d->incoming.first(); QVector<Stmt *> newT2Uses; replaceUses(t, e, W, &newT2Uses); if (Temp *t2 = e->asTemp()) { defUses.removeUse(s, *t2); defUses.addUses(*t2, newT2Uses); W += defUses.defStmt(*t2); } defUses.removeDef(*t); W.remove(s); continue; } } else if (Move *m = s->asMove()) { if (Convert *convert = m->source->asConvert()) { if (Const *sourceConst = convert->expr->asConst()) { convertConst(sourceConst, convert->type); m->source = sourceConst; W += m; continue; } else if (Temp *sourceTemp = convert->expr->asTemp()) { if (sourceTemp->type == convert->type) { m->source = sourceTemp; W += m; continue; } } } if (Temp *targetTemp = m->target->asTemp()) { // dead code elimination: if (defUses.useCount(*targetTemp) == 0) { EliminateDeadCode(defUses, W).run(m->source, s); if (!m->source) W.remove(s); continue; } // constant propagation: if (Const *sourceConst = m->source->asConst()) { Q_ASSERT(sourceConst->type != UnknownType); replaceUses(targetTemp, sourceConst, W); defUses.removeDef(*targetTemp); W.remove(s); continue; } if (Member *member = m->source->asMember()) { if (member->kind == Member::MemberOfEnum) { Const *c = function->New<Const>(); const int enumValue = member->enumValue; c->init(SInt32Type, enumValue); replaceUses(targetTemp, c, W); defUses.removeDef(*targetTemp); W.remove(s); defUses.removeUse(s, *member->base->asTemp()); continue; } else if (member->kind != IR::Member::MemberOfIdObjectsArray && member->attachedPropertiesId != 0 && member->property && member->base->asTemp()) { // Attached properties have no dependency on their base. Isel doesn't // need it and we can eliminate the temp used to initialize it. defUses.removeUse(s, *member->base->asTemp()); Const *c = function->New<Const>(); c->init(SInt32Type, 0); member->base = c; continue; } } // copy propagation: if (Temp *sourceTemp = m->source->asTemp()) { QVector<Stmt *> newT2Uses; replaceUses(targetTemp, sourceTemp, W, &newT2Uses); defUses.removeUse(s, *sourceTemp); defUses.addUses(*sourceTemp, newT2Uses); defUses.removeDef(*targetTemp); W.remove(s); continue; } if (Unop *unop = m->source->asUnop()) { // Constant unary expression evaluation: if (Const *constOperand = unop->expr->asConst()) { if (constOperand->type & NumberType || constOperand->type == BoolType) { // TODO: implement unop propagation for other constant types bool doneSomething = false; switch (unop->op) { case OpNot: constOperand->value = !constOperand->value; constOperand->type = BoolType; doneSomething = true; break; case OpUMinus: if (int(constOperand->value) == 0 && int(constOperand->value) == constOperand->value) { if (isNegative(constOperand->value)) constOperand->value = 0; else constOperand->value = -1 / Q_INFINITY; constOperand->type = DoubleType; doneSomething = true; break; } constOperand->value = -constOperand->value; doneSomething = true; break; case OpUPlus: if (unop->type != UnknownType) constOperand->type = unop->type; doneSomething = true; break; case OpCompl: constOperand->value = ~QV4::Primitive::toInt32(constOperand->value); constOperand->type = SInt32Type; doneSomething = true; break; case OpIncrement: constOperand->value = constOperand->value + 1; doneSomething = true; break; case OpDecrement: constOperand->value = constOperand->value - 1; doneSomething = true; break; default: break; }; if (doneSomething) { m->source = constOperand; W += m; } } } // TODO: if the result of a unary not operation is only used in a cjump, // then inline it. continue; } if (Binop *binop = m->source->asBinop()) { Const *leftConst = binop->left->asConst(); Const *rightConst = binop->right->asConst(); { // Typical casts to int32: Expr *casted = 0; switch (binop->op) { case OpBitAnd: if (leftConst && !rightConst && QV4::Primitive::toUInt32(leftConst->value) == 0xffffffff) casted = binop->right; else if (!leftConst && rightConst && QV4::Primitive::toUInt32(rightConst->value) == 0xffffffff) casted = binop->left; break; case OpBitOr: if (leftConst && !rightConst && QV4::Primitive::toInt32(leftConst->value) == 0) casted = binop->right; else if (!leftConst && rightConst && QV4::Primitive::toUInt32(rightConst->value) == 0) casted = binop->left; break; default: break; } if (casted && casted->type == SInt32Type) { m->source = casted; W += m; continue; } } if (rightConst) { switch (binop->op) { case OpLShift: case OpRShift: if (double v = QV4::Primitive::toInt32(rightConst->value) & 0x1f) { // mask right hand side of shift operations rightConst->value = v; rightConst->type = SInt32Type; } else { // shifting a value over 0 bits is a move: if (rightConst->value == 0) { m->source = binop->left; W += m; } } break; default: break; } } // TODO: More constant binary expression evaluation // TODO: If the result of the move is only used in one single cjump, then // inline the binop into the cjump. if (!leftConst || leftConst->type == StringType || leftConst->type == VarType || leftConst->type == QObjectType) continue; if (!rightConst || rightConst->type == StringType || rightConst->type == VarType || rightConst->type == QObjectType) continue; QV4::Primitive lc = convertToValue(leftConst); QV4::Primitive rc = convertToValue(rightConst); double l = lc.toNumber(); double r = rc.toNumber(); switch (binop->op) { case OpMul: leftConst->value = l * r; leftConst->type = DoubleType; m->source = leftConst; W += m; break; case OpAdd: leftConst->value = l + r; leftConst->type = DoubleType; m->source = leftConst; W += m; break; case OpSub: leftConst->value = l - r; leftConst->type = DoubleType; m->source = leftConst; W += m; break; case OpDiv: leftConst->value = l / r; leftConst->type = DoubleType; m->source = leftConst; W += m; break; case OpMod: leftConst->value = std::fmod(l, r); leftConst->type = DoubleType; m->source = leftConst; W += m; break; default: if (tryOptimizingComparison(m->source)) W += m; break; } continue; } } // TODO: var{#0} = double{%10} where %10 is defined once and used once. E.g.: function(t){t = t % 2; return t; } } else if (CJump *cjump = s->asCJump()) { if (Const *constantCondition = cjump->cond->asConst()) { // Note: this assumes that there are no critical edges! Meaning, we can safely purge // any basic blocks that are found to be unreachable. Jump *jump = function->NewStmt<Jump>(); W.registerNewStatement(jump); if (convertToValue(constantCondition).toBoolean()) { jump->target = cjump->iftrue; unlink(cjump->parent, cjump->iffalse, function, defUses, W, df); } else { jump->target = cjump->iffalse; unlink(cjump->parent, cjump->iftrue, function, defUses, W, df); } W.replace(s, jump); continue; } else if (cjump->cond->asBinop()) { if (tryOptimizingComparison(cjump->cond)) W += cjump; continue; } // TODO: Constant unary expression evaluation // TODO: if the expression is an unary not operation, lift the expression, and switch // the then/else blocks. } } W.applyToFunction(); } //### TODO: use DefUses from the optimizer, because it already has all this information class InputOutputCollector: protected StmtVisitor, protected ExprVisitor { void setOutput(Temp *out) { Q_ASSERT(!output); output = out; } public: std::vector<Temp *> inputs; Temp *output; InputOutputCollector() { inputs.reserve(4); } void collect(Stmt *s) { inputs.resize(0); output = 0; s->accept(this); } protected: virtual void visitConst(Const *) {} virtual void visitString(IR::String *) {} virtual void visitRegExp(IR::RegExp *) {} virtual void visitName(Name *) {} virtual void visitTemp(Temp *e) { inputs.push_back(e); } virtual void visitArgLocal(ArgLocal *) {} virtual void visitClosure(Closure *) {} virtual void visitConvert(Convert *e) { e->expr->accept(this); } virtual void visitUnop(Unop *e) { e->expr->accept(this); } virtual void visitBinop(Binop *e) { e->left->accept(this); e->right->accept(this); } virtual void visitCall(Call *e) { e->base->accept(this); for (ExprList *it = e->args; it; it = it->next) it->expr->accept(this); } virtual void visitNew(New *e) { e->base->accept(this); for (ExprList *it = e->args; it; it = it->next) it->expr->accept(this); } virtual void visitSubscript(Subscript *e) { e->base->accept(this); e->index->accept(this); } virtual void visitMember(Member *e) { e->base->accept(this); } virtual void visitExp(Exp *s) { s->expr->accept(this); } virtual void visitMove(Move *s) { s->source->accept(this); if (Temp *t = s->target->asTemp()) { setOutput(t); } else { s->target->accept(this); } } virtual void visitJump(Jump *) {} virtual void visitCJump(CJump *s) { s->cond->accept(this); } virtual void visitRet(Ret *s) { s->expr->accept(this); } virtual void visitPhi(Phi *) { // Handled separately } }; /* * The algorithm is described in: * * Linear Scan Register Allocation on SSA Form * Christian Wimmer & Michael Franz, CGO'10, April 24-28, 2010 * * See LifeTimeIntervals::renumber for details on the numbering. */ class LifeRanges { typedef QSet<Temp> LiveRegs; std::vector<LiveRegs> _liveIn; std::vector<LifeTimeInterval *> _intervals; LifeTimeIntervals::Ptr _sortedIntervals; LifeTimeInterval &interval(const Temp *temp) { LifeTimeInterval *&lti = _intervals[temp->index]; if (Q_UNLIKELY(!lti)) { lti = new LifeTimeInterval; lti->setTemp(*temp); } return *lti; } int defPosition(IR::Stmt *s) const { return usePosition(s) + 1; } int usePosition(IR::Stmt *s) const { return _sortedIntervals->positionForStatement(s); } int start(IR::BasicBlock *bb) const { return _sortedIntervals->startPosition(bb); } int end(IR::BasicBlock *bb) const { return _sortedIntervals->endPosition(bb); } public: LifeRanges(IR::Function *function, const QHash<BasicBlock *, BasicBlock *> &startEndLoops) : _intervals(function->tempCount) { _sortedIntervals = LifeTimeIntervals::create(function); _liveIn.resize(function->basicBlockCount()); for (int i = function->basicBlockCount() - 1; i >= 0; --i) { BasicBlock *bb = function->basicBlock(i); buildIntervals(bb, startEndLoops.value(bb, 0)); } _intervals.clear(); } LifeTimeIntervals::Ptr intervals() const { return _sortedIntervals; } void dump() const { QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream qout(&buf); qout << "Life ranges:" << endl; qout << "Intervals:" << endl; foreach (const LifeTimeInterval *range, _sortedIntervals->intervals()) { range->dump(qout); qout << endl; } IRPrinter printer(&qout); for (size_t i = 0, ei = _liveIn.size(); i != ei; ++i) { qout << "L" << i <<" live-in: "; QList<Temp> live = QList<Temp>::fromSet(_liveIn.at(i)); if (live.isEmpty()) qout << "(none)"; std::sort(live.begin(), live.end()); for (int i = 0; i < live.size(); ++i) { if (i > 0) qout << ", "; printer.print(&live[i]); } qout << endl; } buf.close(); qDebug("%s", buf.data().constData()); } private: void buildIntervals(BasicBlock *bb, BasicBlock *loopEnd) { LiveRegs live; foreach (BasicBlock *successor, bb->out) { live.unite(_liveIn[successor->index()]); const int bbIndex = successor->in.indexOf(bb); Q_ASSERT(bbIndex >= 0); foreach (Stmt *s, successor->statements()) { if (Phi *phi = s->asPhi()) { if (Temp *t = phi->d->incoming.at(bbIndex)->asTemp()) live.insert(*t); } else { break; } } } QVector<Stmt *> statements = bb->statements(); foreach (const Temp &opd, live) interval(&opd).addRange(start(bb), end(bb)); InputOutputCollector collector; for (int i = statements.size() - 1; i >= 0; --i) { Stmt *s = statements.at(i); if (Phi *phi = s->asPhi()) { LiveRegs::iterator it = live.find(*phi->targetTemp); if (it == live.end()) { // a phi node target that is only defined, but never used interval(phi->targetTemp).setFrom(start(bb)); } else { live.erase(it); } _sortedIntervals->add(&interval(phi->targetTemp)); continue; } collector.collect(s); //### TODO: use DefUses from the optimizer, because it already has all this information if (Temp *opd = collector.output) { LifeTimeInterval &lti = interval(opd); lti.setFrom(defPosition(s)); live.remove(lti.temp()); _sortedIntervals->add(&lti); } //### TODO: use DefUses from the optimizer, because it already has all this information for (size_t i = 0, ei = collector.inputs.size(); i != ei; ++i) { Temp *opd = collector.inputs[i]; interval(opd).addRange(start(bb), usePosition(s)); live.insert(*opd); } } if (loopEnd) { // Meaning: bb is a loop header, because loopEnd is set to non-null. foreach (const Temp &opd, live) interval(&opd).addRange(start(bb), usePosition(loopEnd->terminator())); } _liveIn[bb->index()] = live; } }; void removeUnreachleBlocks(IR::Function *function) { QVector<BasicBlock *> newSchedule; newSchedule.reserve(function->basicBlockCount()); foreach (BasicBlock *bb, function->basicBlocks()) if (!bb->isRemoved()) newSchedule.append(bb); function->setScheduledBlocks(newSchedule); function->renumberBasicBlocks(); } class ConvertArgLocals: protected StmtVisitor, protected ExprVisitor { public: ConvertArgLocals(IR::Function *function) : function(function) , convertArgs(!function->usesArgumentsObject) { tempForFormal.resize(function->formals.size(), -1); tempForLocal.resize(function->locals.size(), -1); } void toTemps() { if (function->variablesCanEscape()) return; QVector<Stmt *> extraMoves; if (convertArgs) { const int formalCount = function->formals.size(); extraMoves.reserve(formalCount + function->basicBlock(0)->statementCount()); extraMoves.resize(formalCount); for (int i = 0; i != formalCount; ++i) { const int newTemp = function->tempCount++; tempForFormal[i] = newTemp; ArgLocal *source = function->New<ArgLocal>(); source->init(ArgLocal::Formal, i, 0); Temp *target = function->New<Temp>(); target->init(Temp::VirtualRegister, newTemp); Move *m = function->NewStmt<Move>(); m->init(target, source); extraMoves[i] = m; } } foreach (BasicBlock *bb, function->basicBlocks()) if (!bb->isRemoved()) foreach (Stmt *s, bb->statements()) s->accept(this); if (convertArgs && function->formals.size() > 0) function->basicBlock(0)->prependStatements(extraMoves); function->locals.clear(); } protected: virtual void visitConst(Const *) {} virtual void visitString(IR::String *) {} virtual void visitRegExp(IR::RegExp *) {} virtual void visitName(Name *) {} virtual void visitTemp(Temp *) {} virtual void visitArgLocal(ArgLocal *) {} virtual void visitClosure(Closure *) {} virtual void visitConvert(Convert *e) { check(e->expr); } virtual void visitUnop(Unop *e) { check(e->expr); } virtual void visitBinop(Binop *e) { check(e->left); check(e->right); } virtual void visitCall(Call *e) { check(e->base); for (ExprList *it = e->args; it; it = it->next) check(it->expr); } virtual void visitNew(New *e) { check(e->base); for (ExprList *it = e->args; it; it = it->next) check(it->expr); } virtual void visitSubscript(Subscript *e) { check(e->base); check(e->index); } virtual void visitMember(Member *e) { check(e->base); } virtual void visitExp(Exp *s) { check(s->expr); } virtual void visitMove(Move *s) { check(s->target); check(s->source); } virtual void visitJump(Jump *) {} virtual void visitCJump(CJump *s) { check(s->cond); } virtual void visitRet(Ret *s) { check(s->expr); } virtual void visitPhi(Phi *) { Q_UNREACHABLE(); } private: void check(Expr *&e) { if (ArgLocal *al = e->asArgLocal()) { if (al->kind == ArgLocal::Local) { Temp *t = function->New<Temp>(); t->init(Temp::VirtualRegister, fetchTempForLocal(al->index)); e = t; } else if (convertArgs && al->kind == ArgLocal::Formal) { Temp *t = function->New<Temp>(); t->init(Temp::VirtualRegister, fetchTempForFormal(al->index)); e = t; } } else { e->accept(this); } } int fetchTempForLocal(int local) { int &ref = tempForLocal[local]; if (ref == -1) ref = function->tempCount++; return ref; } int fetchTempForFormal(int formal) { return tempForFormal[formal]; } IR::Function *function; bool convertArgs; std::vector<int> tempForFormal; std::vector<int> tempForLocal; }; class CloneBasicBlock: protected IR::StmtVisitor, protected CloneExpr { public: BasicBlock *operator()(IR::BasicBlock *originalBlock) { block = new BasicBlock(originalBlock->function, 0); foreach (Stmt *s, originalBlock->statements()) { s->accept(this); clonedStmt->location = s->location; } return block; } protected: virtual void visitExp(Exp *stmt) { clonedStmt = block->EXP(clone(stmt->expr)); } virtual void visitMove(Move *stmt) { clonedStmt = block->MOVE(clone(stmt->target), clone(stmt->source)); } virtual void visitJump(Jump *stmt) { clonedStmt = block->JUMP(stmt->target); } virtual void visitCJump(CJump *stmt) { clonedStmt = block->CJUMP(clone(stmt->cond), stmt->iftrue, stmt->iffalse); } virtual void visitRet(Ret *stmt) { clonedStmt = block->RET(clone(stmt->expr)); } virtual void visitPhi(Phi *stmt) { Phi *phi = block->function->NewStmt<Phi>(); clonedStmt = phi; phi->targetTemp = clone(stmt->targetTemp); phi->d = new Phi::Data; foreach (Expr *in, stmt->d->incoming) phi->d->incoming.append(clone(in)); block->appendStatement(phi); } private: IR::Stmt *clonedStmt; }; // Loop-peeling is done by unfolding the loop once. The "original" loop basic blocks stay where they // are, and a copy of the loop is placed after it. Special care is taken while copying the loop body: // by having the copies of the basic-blocks point to the same nodes as the "original" basic blocks, // updating the immediate dominators is easy: if the edge of a copied basic-block B points to a // block C that has also been copied, set the immediate dominator of B to the corresponding // immediate dominator of C. Finally, for any node outside the loop that gets a new edge attached, // the immediate dominator has to be re-calculated. class LoopPeeling { DominatorTree &dt; public: LoopPeeling(DominatorTree &dt) : dt(dt) {} void run(const QVector<LoopDetection::LoopInfo *> &loops) { foreach (LoopDetection::LoopInfo *loopInfo, loops) peelLoop(loopInfo); } private: // All copies have their outgoing edges pointing to the same successor block as the originals. // For each copied block, check where the outgoing edges point to. If it's a block inside the // (original) loop, rewire it to the corresponding copy. Otherwise, which is when it points // out of the loop, leave it alone. // As an extra, collect all edges that point out of the copied loop, because the targets need // to have their immediate dominator rechecked. void rewire(BasicBlock *newLoopBlock, const QVector<BasicBlock *> &from, const QVector<BasicBlock *> &to, QVector<BasicBlock *> &loopExits) { for (int i = 0, ei = newLoopBlock->out.size(); i != ei; ++i) { BasicBlock *&out = newLoopBlock->out[i]; const int idx = from.indexOf(out); if (idx == -1) { if (!loopExits.contains(out)) loopExits.append(out); } else { out->in.removeOne(newLoopBlock); BasicBlock *newTo = to.at(idx); newTo->in.append(newLoopBlock); out = newTo; Stmt *terminator = newLoopBlock->terminator(); if (Jump *jump = terminator->asJump()) { Q_ASSERT(i == 0); jump->target = newTo; } else if (CJump *cjump = terminator->asCJump()) { Q_ASSERT(i == 0 || i == 1); if (i == 0) cjump->iftrue = newTo; else cjump->iffalse = newTo; } } } } void peelLoop(LoopDetection::LoopInfo *loop) { CloneBasicBlock clone; LoopDetection::LoopInfo unpeeled(*loop); unpeeled.loopHeader = clone(unpeeled.loopHeader); unpeeled.loopHeader->setContainingGroup(loop->loopHeader->containingGroup()); unpeeled.loopHeader->markAsGroupStart(true); for (int i = 0, ei = unpeeled.loopBody.size(); i != ei; ++i) { BasicBlock *&bodyBlock = unpeeled.loopBody[i]; bodyBlock = clone(bodyBlock); bodyBlock->setContainingGroup(unpeeled.loopHeader); Q_ASSERT(bodyBlock->statementCount() == loop->loopBody[i]->statementCount()); } // The cloned blocks will have no incoming edges, but they do have outgoing ones (copying // the terminators will automatically insert that edge). The blocks where the originals // pointed to will have an extra incoming edge from the copied blocks. foreach (BasicBlock *in, loop->loopHeader->in) { if (unpeeled.loopHeader != in // this can happen for really tight loops (where there are no body blocks). This is a back-edge in that case. && !unpeeled.loopBody.contains(in) // if the edge is not coming from within the copied set, leave it alone && !dt.dominates(loop->loopHeader, in)) // an edge coming from within the loop (so a back-edge): this is handled when rewiring all outgoing edges continue; unpeeled.loopHeader->in.append(in); loop->loopHeader->in.removeOne(in); Stmt *terminator = in->terminator(); if (Jump *jump = terminator->asJump()) { jump->target = unpeeled.loopHeader; in->out[0] = unpeeled.loopHeader; } else if (CJump *cjump = terminator->asCJump()) { if (cjump->iftrue == loop->loopHeader) { cjump->iftrue = unpeeled.loopHeader; Q_ASSERT(in->out[0] == loop->loopHeader); in->out[0] = unpeeled.loopHeader; } else if (cjump->iffalse == loop->loopHeader) { cjump->iffalse = unpeeled.loopHeader; Q_ASSERT(in->out[1] == loop->loopHeader); in->out[1] = unpeeled.loopHeader; } else { Q_UNREACHABLE(); } } } QVector<BasicBlock *> loopExits; loopExits.reserve(8); loopExits.append(unpeeled.loopHeader); IR::Function *f = unpeeled.loopHeader->function; rewire(unpeeled.loopHeader, loop->loopBody, unpeeled.loopBody, loopExits); f->addBasicBlock(unpeeled.loopHeader); for (int i = 0, ei = unpeeled.loopBody.size(); i != ei; ++i) { BasicBlock *bodyBlock = unpeeled.loopBody.at(i); rewire(bodyBlock, loop->loopBody, unpeeled.loopBody, loopExits); f->addBasicBlock(bodyBlock); } // The original loop is now peeled off, and won't jump back to the loop header. Meaning, it // is not a loop anymore, so unmark it. loop->loopHeader->markAsGroupStart(false); foreach (BasicBlock *bb, loop->loopBody) bb->setContainingGroup(loop->loopHeader->containingGroup()); // calculate the idoms in a separate loop, because addBasicBlock in the previous loop will // set the block index, which in turn is used by the dominator tree. for (int i = 0, ei = unpeeled.loopBody.size(); i != ei; ++i) { BasicBlock *bodyBlock = unpeeled.loopBody.at(i); BasicBlock *idom = dt.immediateDominator(loop->loopBody.at(i)); const int idx = loop->loopBody.indexOf(idom); if (idom == loop->loopHeader) idom = unpeeled.loopHeader; else if (idx != -1) idom = unpeeled.loopBody.at(idx); Q_ASSERT(idom); dt.setImmediateDominator(bodyBlock, idom); } BasicBlockSet siblings(f); foreach (BasicBlock *bb, loopExits) dt.collectSiblings(bb, siblings); dt.recalculateIDoms(siblings, loop->loopHeader); } }; static void verifyCFG(IR::Function *function) { if (!DoVerification) return; foreach (BasicBlock *bb, function->basicBlocks()) { if (bb->isRemoved()) { Q_ASSERT(bb->in.isEmpty()); Q_ASSERT(bb->out.isEmpty()); continue; } Q_ASSERT(function->basicBlock(bb->index()) == bb); // Check the terminators: if (Jump *jump = bb->terminator()->asJump()) { Q_UNUSED(jump); Q_ASSERT(jump->target); Q_ASSERT(!jump->target->isRemoved()); Q_ASSERT(bb->out.size() == 1); Q_ASSERT(bb->out.first() == jump->target); } else if (CJump *cjump = bb->terminator()->asCJump()) { Q_UNUSED(cjump); Q_ASSERT(bb->out.size() == 2); Q_ASSERT(cjump->iftrue); Q_ASSERT(!cjump->iftrue->isRemoved()); Q_ASSERT(cjump->iftrue == bb->out[0]); Q_ASSERT(cjump->iffalse); Q_ASSERT(!cjump->iffalse->isRemoved()); Q_ASSERT(cjump->iffalse == bb->out[1]); } else if (bb->terminator()->asRet()) { Q_ASSERT(bb->out.size() == 0); } else { Q_UNREACHABLE(); } // Check the outgoing edges: foreach (BasicBlock *out, bb->out) { Q_UNUSED(out); Q_ASSERT(!out->isRemoved()); Q_ASSERT(out->in.contains(bb)); } // Check the incoming edges: foreach (BasicBlock *in, bb->in) { Q_UNUSED(in); Q_ASSERT(!in->isRemoved()); Q_ASSERT(in->out.contains(bb)); } } } static void verifyImmediateDominators(const DominatorTree &dt, IR::Function *function) { if (!DoVerification) return; cfg2dot(function); dt.dumpImmediateDominators(); DominatorTree referenceTree(function); foreach (BasicBlock *bb, function->basicBlocks()) { if (bb->isRemoved()) continue; BasicBlock *idom = dt.immediateDominator(bb); BasicBlock *referenceIdom = referenceTree.immediateDominator(bb); Q_UNUSED(idom); Q_UNUSED(referenceIdom); Q_ASSERT(idom == referenceIdom); } } static void verifyNoPointerSharing(IR::Function *function) { if (!DoVerification) return; class : public StmtVisitor, public ExprVisitor { public: void operator()(IR::Function *f) { foreach (BasicBlock *bb, f->basicBlocks()) { if (bb->isRemoved()) continue; foreach (Stmt *s, bb->statements()) s->accept(this); } } protected: virtual void visitExp(Exp *s) { check(s); s->expr->accept(this); } virtual void visitMove(Move *s) { check(s); s->target->accept(this); s->source->accept(this); } virtual void visitJump(Jump *s) { check(s); } virtual void visitCJump(CJump *s) { check(s); s->cond->accept(this); } virtual void visitRet(Ret *s) { check(s); s->expr->accept(this); } virtual void visitPhi(Phi *s) { check(s); s->targetTemp->accept(this); foreach (Expr *e, s->d->incoming) e->accept(this); } virtual void visitConst(Const *e) { check(e); } virtual void visitString(IR::String *e) { check(e); } virtual void visitRegExp(IR::RegExp *e) { check(e); } virtual void visitName(Name *e) { check(e); } virtual void visitTemp(Temp *e) { check(e); } virtual void visitArgLocal(ArgLocal *e) { check(e); } virtual void visitClosure(Closure *e) { check(e); } virtual void visitConvert(Convert *e) { check(e); e->expr->accept(this); } virtual void visitUnop(Unop *e) { check(e); e->expr->accept(this); } virtual void visitBinop(Binop *e) { check(e); e->left->accept(this); e->right->accept(this); } virtual void visitCall(Call *e) { check(e); e->base->accept(this); check(e->args); } virtual void visitNew(New *e) { check(e); e->base->accept(this); check(e->args); } virtual void visitSubscript(Subscript *e) { check(e); e->base->accept(this); e->index->accept(this); } virtual void visitMember(Member *e) { check(e); e->base->accept(this); } void check(ExprList *l) { for (ExprList *it = l; it; it = it->next) check(it->expr); } private: void check(Stmt *s) { Q_ASSERT(!stmts.contains(s)); stmts.insert(s); } void check(Expr *e) { Q_ASSERT(!exprs.contains(e)); exprs.insert(e); } QSet<Stmt *> stmts; QSet<Expr *> exprs; } V; V(function); } class RemoveLineNumbers: public SideEffectsChecker, public StmtVisitor { public: static void run(IR::Function *function) { foreach (BasicBlock *bb, function->basicBlocks()) { if (bb->isRemoved()) continue; foreach (Stmt *s, bb->statements()) { if (!hasSideEffects(s)) { s->location = QQmlJS::AST::SourceLocation(); } } } } private: static bool hasSideEffects(Stmt *stmt) { RemoveLineNumbers checker; stmt->accept(&checker); return checker.seenSideEffects(); } void visitExp(Exp *s) Q_DECL_OVERRIDE { s->expr->accept(this); } void visitMove(Move *s) Q_DECL_OVERRIDE { s->source->accept(this); s->target->accept(this); } void visitJump(Jump *) Q_DECL_OVERRIDE {} void visitCJump(CJump *s) Q_DECL_OVERRIDE { s->cond->accept(this); } void visitRet(Ret *s) Q_DECL_OVERRIDE { s->expr->accept(this); } void visitPhi(Phi *) Q_DECL_OVERRIDE {} }; } // anonymous namespace void LifeTimeInterval::setFrom(int from) { Q_ASSERT(from > 0); if (_ranges.isEmpty()) { // this is the case where there is no use, only a define _ranges.push_front(Range(from, from)); if (_end == InvalidPosition) _end = from; } else { _ranges.first().start = from; } } void LifeTimeInterval::addRange(int from, int to) { Q_ASSERT(from > 0); Q_ASSERT(to > 0); Q_ASSERT(to >= from); if (_ranges.isEmpty()) { _ranges.push_front(Range(from, to)); _end = to; return; } Range *p = &_ranges.first(); if (to + 1 >= p->start && p->end + 1 >= from) { p->start = qMin(p->start, from); p->end = qMax(p->end, to); while (_ranges.count() > 1) { Range *p1 = p + 1; if (p->end + 1 < p1->start || p1->end + 1 < p->start) break; p1->start = qMin(p->start, p1->start); p1->end = qMax(p->end, p1->end); _ranges.pop_front(); p = &_ranges.first(); } } else { if (to < p->start) { _ranges.push_front(Range(from, to)); } else { Q_ASSERT(from > _ranges.last().end); _ranges.push_back(Range(from, to)); } } _end = _ranges.last().end; } LifeTimeInterval LifeTimeInterval::split(int atPosition, int newStart) { Q_ASSERT(atPosition < newStart || newStart == InvalidPosition); Q_ASSERT(atPosition <= _end); Q_ASSERT(newStart <= _end || newStart == InvalidPosition); if (_ranges.isEmpty() || atPosition < _ranges.first().start) return LifeTimeInterval(); LifeTimeInterval newInterval = *this; newInterval.setSplitFromInterval(true); // search where to split the interval for (int i = 0, ei = _ranges.size(); i < ei; ++i) { if (_ranges.at(i).start <= atPosition) { if (_ranges.at(i).end >= atPosition) { // split happens in the middle of a range. Keep this range in both the old and the // new interval, and correct the end/start later _ranges.resize(i + 1); newInterval._ranges.remove(0, i); break; } } else { // split happens between two ranges. _ranges.resize(i); newInterval._ranges.remove(0, i); break; } } if (newInterval._ranges.first().end == atPosition) newInterval._ranges.removeFirst(); if (newStart == InvalidPosition) { // the temp stays inactive for the rest of its lifetime newInterval = LifeTimeInterval(); } else { // find the first range where the temp will get active again: while (!newInterval._ranges.isEmpty()) { const Range &range = newInterval._ranges.first(); if (range.start > newStart) { // The split position is before the start of the range. Either we managed to skip // over the correct range, or we got an invalid split request. Either way, this // Should Never Happen <TM>. Q_ASSERT(range.start > newStart); return LifeTimeInterval(); } else if (range.start <= newStart && range.end >= newStart) { // yay, we found the range that should be the new first range in the new interval! break; } else { // the temp stays inactive for this interval, so remove it. newInterval._ranges.removeFirst(); } } Q_ASSERT(!newInterval._ranges.isEmpty()); newInterval._ranges.first().start = newStart; _end = newStart; } // if we're in the middle of a range, set the end to the split position if (_ranges.last().end > atPosition) _ranges.last().end = atPosition; validate(); newInterval.validate(); return newInterval; } void LifeTimeInterval::dump(QTextStream &out) const { IRPrinter(&out).print(const_cast<Temp *>(&_temp)); out << ": ends at " << _end << " with ranges "; if (_ranges.isEmpty()) out << "(none)"; for (int i = 0; i < _ranges.size(); ++i) { if (i > 0) out << ", "; out << _ranges[i].start << " - " << _ranges[i].end; } if (_reg != InvalidRegister) out << " (register " << _reg << ")"; } bool LifeTimeInterval::lessThan(const LifeTimeInterval *r1, const LifeTimeInterval *r2) { if (r1->_ranges.first().start == r2->_ranges.first().start) { if (r1->isSplitFromInterval() == r2->isSplitFromInterval()) return r1->_ranges.last().end < r2->_ranges.last().end; else return r1->isSplitFromInterval(); } else return r1->_ranges.first().start < r2->_ranges.first().start; } bool LifeTimeInterval::lessThanForTemp(const LifeTimeInterval *r1, const LifeTimeInterval *r2) { return r1->temp() < r2->temp(); } LifeTimeIntervals::LifeTimeIntervals(IR::Function *function) : _basicBlockPosition(function->basicBlockCount()) , _positionForStatement(function->statementCount(), IR::Stmt::InvalidId) , _lastPosition(0) { _intervals.reserve(function->tempCount + 32); // we reserve a bit more space for intervals, because the register allocator will add intervals with fixed ranges for each register. renumber(function); } // Renumbering works as follows: // - phi statements are not numbered // - statement numbers start at 0 (zero) and increment get an even number (lastPosition + 2) // - basic blocks start at firstStatementNumber - 1, or rephrased: lastPosition + 1 // - basic blocks end at the number of the last statement // And during life-time calculation the next rule is used: // - any temporary starts its life-time at definingStatementPosition + 1 // // This numbering simulates half-open intervals. For example: // 0: %1 = 1 // 2: %2 = 2 // 4: %3 = %1 + %2 // 6: print(%3) // Here the half-open life-time intervals would be: // %1: (0-4] // %2: (2-4] // %3: (4-6] // Instead, we use the even statement positions for uses of temporaries, and the odd positions for // their definitions: // %1: [1-4] // %2: [3-4] // %3: [5-6] // This has the nice advantage that placing %3 (for example) is really easy: the start will // never overlap with the end of the uses of the operands used in the defining statement. // // The reason to start a basic-block at firstStatementPosition - 1 is to have correct start // positions for target temporaries of phi-nodes. Those temporaries will now start before the // first statement. This also means that any moves that get generated when transforming out of SSA // form, will not interfere with (read: overlap) any defining statements in the preceding // basic-block. void LifeTimeIntervals::renumber(IR::Function *function) { foreach (BasicBlock *bb, function->basicBlocks()) { if (bb->isRemoved()) continue; _basicBlockPosition[bb->index()].start = _lastPosition + 1; foreach (Stmt *s, bb->statements()) { if (s->asPhi()) continue; _lastPosition += 2; _positionForStatement[s->id()] = _lastPosition; } _basicBlockPosition[bb->index()].end = _lastPosition; } } LifeTimeIntervals::~LifeTimeIntervals() { qDeleteAll(_intervals); } Optimizer::Optimizer(IR::Function *function) : function(function) , inSSA(false) {} void Optimizer::run(QQmlEnginePrivate *qmlEngine, bool doTypeInference, bool peelLoops) { showMeTheCode(function, "Before running the optimizer"); cleanupBasicBlocks(function); function->removeSharedExpressions(); int statementCount = 0; foreach (BasicBlock *bb, function->basicBlocks()) if (!bb->isRemoved()) statementCount += bb->statementCount(); // showMeTheCode(function); static bool doSSA = qEnvironmentVariableIsEmpty("QV4_NO_SSA"); if (!function->hasTry && !function->hasWith && !function->module->debugMode && doSSA && statementCount <= 300) { // qout << "SSA for " << (function->name ? qPrintable(*function->name) : "<anonymous>") << endl; ConvertArgLocals(function).toTemps(); showMeTheCode(function, "After converting arguments to locals"); // Calculate the dominator tree: DominatorTree df(function); { // This is in a separate scope, because loop-peeling doesn't (yet) update the LoopInfo // calculated by the LoopDetection. So by putting it in a separate scope, it is not // available after peeling. LoopDetection loopDetection(df); loopDetection.run(function); showMeTheCode(function, "After loop detection"); // cfg2dot(function, loopDetection.allLoops()); if (peelLoops) { QVector<LoopDetection::LoopInfo *> innerLoops = loopDetection.innermostLoops(); LoopPeeling(df).run(innerLoops); // cfg2dot(function, loopDetection.allLoops()); showMeTheCode(function, "After loop peeling"); if (!innerLoops.isEmpty()) verifyImmediateDominators(df, function); } } verifyCFG(function); verifyNoPointerSharing(function); df.computeDF(); verifyCFG(function); verifyImmediateDominators(df, function); DefUses defUses(function); // qout << "Converting to SSA..." << endl; convertToSSA(function, df, defUses); // showMeTheCode(function); // defUses.dump(); // qout << "Cleaning up phi nodes..." << endl; cleanupPhis(defUses); showMeTheCode(function, "After cleaning up phi-nodes"); StatementWorklist worklist(function); if (doTypeInference) { // qout << "Running type inference..." << endl; TypeInference(qmlEngine, defUses).run(worklist); showMeTheCode(function, "After type inference"); // qout << "Doing reverse inference..." << endl; ReverseInference(defUses).run(function); // showMeTheCode(function); // qout << "Doing type propagation..." << endl; TypePropagation(defUses).run(function, worklist); // showMeTheCode(function); verifyNoPointerSharing(function); } static const bool doOpt = qEnvironmentVariableIsEmpty("QV4_NO_OPT"); if (doOpt) { // qout << "Running SSA optimization..." << endl; worklist.reset(); optimizeSSA(worklist, defUses, df); showMeTheCode(function, "After optimization"); verifyImmediateDominators(df, function); verifyCFG(function); } verifyNoPointerSharing(function); // Basic-block cycles that are unreachable (i.e. for loops in a then-part where the // condition is calculated to be always false) are not yet removed. This will choke the // block scheduling, so remove those now. // qout << "Cleaning up unreachable basic blocks..." << endl; cleanupBasicBlocks(function); // showMeTheCode(function); // Transform the CFG into edge-split SSA. // qout << "Starting edge splitting..." << endl; splitCriticalEdges(function, df, worklist, defUses); // showMeTheCode(function); verifyImmediateDominators(df, function); verifyCFG(function); // qout << "Doing block scheduling..." << endl; // df.dumpImmediateDominators(); startEndLoops = BlockScheduler(function, df).go(); showMeTheCode(function, "After basic block scheduling"); // cfg2dot(function); #ifndef QT_NO_DEBUG checkCriticalEdges(function->basicBlocks()); #endif if (!function->module->debugMode) { RemoveLineNumbers::run(function); showMeTheCode(function, "After line number removal"); } // qout << "Finished SSA." << endl; inSSA = true; } else { removeUnreachleBlocks(function); inSSA = false; } } void Optimizer::convertOutOfSSA() { if (!inSSA) return; // There should be no critical edges at this point. foreach (BasicBlock *bb, function->basicBlocks()) { MoveMapping moves; foreach (BasicBlock *successor, bb->out) { const int inIdx = successor->in.indexOf(bb); Q_ASSERT(inIdx >= 0); foreach (Stmt *s, successor->statements()) { if (Phi *phi = s->asPhi()) { moves.add(clone(phi->d->incoming[inIdx], function), clone(phi->targetTemp, function)->asTemp()); } else { break; } } } if (DebugMoveMapping) { QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream os(&buf); os << "Move mapping for function "; if (function->name) os << *function->name; else os << (void *) function; os << " on basic-block L" << bb->index() << ":" << endl; moves.dump(); buf.close(); qDebug("%s", buf.data().constData()); } moves.order(); moves.insertMoves(bb, function, true); } foreach (BasicBlock *bb, function->basicBlocks()) { while (!bb->isEmpty()) { if (bb->statements().first()->asPhi()) { bb->removeStatement(0); } else { break; } } } } LifeTimeIntervals::Ptr Optimizer::lifeTimeIntervals() const { Q_ASSERT(isInSSA()); LifeRanges lifeRanges(function, startEndLoops); // lifeRanges.dump(); // showMeTheCode(function); return lifeRanges.intervals(); } QSet<Jump *> Optimizer::calculateOptionalJumps() { QSet<Jump *> optional; QSet<BasicBlock *> reachableWithoutJump; const int maxSize = function->basicBlockCount(); optional.reserve(maxSize); reachableWithoutJump.reserve(maxSize); for (int i = maxSize - 1; i >= 0; --i) { BasicBlock *bb = function->basicBlock(i); if (bb->isRemoved()) continue; if (Jump *jump = bb->statements().last()->asJump()) { if (reachableWithoutJump.contains(jump->target)) { if (bb->statements().size() > 1) reachableWithoutJump.clear(); optional.insert(jump); reachableWithoutJump.insert(bb); continue; } } reachableWithoutJump.clear(); reachableWithoutJump.insert(bb); } return optional; } void Optimizer::showMeTheCode(IR::Function *function, const char *marker) { ::showMeTheCode(function, marker); } static inline bool overlappingStorage(const Temp &t1, const Temp &t2) { // This is the same as the operator==, but for one detail: memory locations are not sensitive // to types, and neither are general-purpose registers. if (t1.index != t2.index) return false; // different position, where-ever that may (physically) be. if (t1.kind != t2.kind) return false; // formal/local/(physical-)register/stack do never overlap if (t1.kind != Temp::PhysicalRegister) // Other than registers, ... return t1.kind == t2.kind; // ... everything else overlaps: any memory location can hold everything. // So now the index is the same, and we know that both stored in a register. If both are // floating-point registers, they are the same. Or, if both are non-floating-point registers, // generally called general-purpose registers, they are also the same. return (t1.type == DoubleType && t2.type == DoubleType) || (t1.type != DoubleType && t2.type != DoubleType); } MoveMapping::Moves MoveMapping::sourceUsages(Expr *e, const Moves &moves) { Moves usages; if (Temp *t = e->asTemp()) { for (int i = 0, ei = moves.size(); i != ei; ++i) { const Move &move = moves[i]; if (Temp *from = move.from->asTemp()) if (overlappingStorage(*from, *t)) usages.append(move); } } return usages; } void MoveMapping::add(Expr *from, Temp *to) { if (Temp *t = from->asTemp()) { if (overlappingStorage(*t, *to)) { // assignments like fp1 = fp1 or var{&1} = double{&1} can safely be skipped. if (DebugMoveMapping) { QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream os(&buf); IRPrinter printer(&os); os << "Skipping "; printer.print(to); os << " <- "; printer.print(from); buf.close(); qDebug("%s", buf.data().constData()); } return; } } Move m(from, to); if (_moves.contains(m)) return; _moves.append(m); } void MoveMapping::order() { QList<Move> todo = _moves; QList<Move> output, swaps; output.reserve(_moves.size()); QList<Move> delayed; delayed.reserve(_moves.size()); while (!todo.isEmpty()) { const Move m = todo.first(); todo.removeFirst(); schedule(m, todo, delayed, output, swaps); } output += swaps; Q_ASSERT(todo.isEmpty()); Q_ASSERT(delayed.isEmpty()); qSwap(_moves, output); } QList<IR::Move *> MoveMapping::insertMoves(BasicBlock *bb, IR::Function *function, bool atEnd) const { QList<IR::Move *> newMoves; newMoves.reserve(_moves.size()); int insertionPoint = atEnd ? bb->statements().size() - 1 : 0; foreach (const Move &m, _moves) { IR::Move *move = function->NewStmt<IR::Move>(); move->init(clone(m.to, function), clone(m.from, function)); move->swap = m.needsSwap; bb->insertStatementBefore(insertionPoint++, move); newMoves.append(move); } return newMoves; } void MoveMapping::dump() const { if (DebugMoveMapping) { QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream os(&buf); IRPrinter printer(&os); os << "Move mapping has " << _moves.size() << " moves..." << endl; foreach (const Move &m, _moves) { os << "\t"; printer.print(m.to); if (m.needsSwap) os << " <-> "; else os << " <-- "; printer.print(m.from); os << endl; } qDebug("%s", buf.data().constData()); } } MoveMapping::Action MoveMapping::schedule(const Move &m, QList<Move> &todo, QList<Move> &delayed, QList<Move> &output, QList<Move> &swaps) const { Moves usages = sourceUsages(m.to, todo) + sourceUsages(m.to, delayed); foreach (const Move &dependency, usages) { if (!output.contains(dependency)) { if (delayed.contains(dependency)) { // We have a cycle! Break it by swapping instead of assigning. if (DebugMoveMapping) { delayed += m; QBuffer buf; buf.open(QIODevice::WriteOnly); QTextStream out(&buf); IRPrinter printer(&out); out<<"we have a cycle! temps:" << endl; foreach (const Move &m, delayed) { out<<"\t"; printer.print(m.to); out<<" <- "; printer.print(m.from); out<<endl; } qDebug("%s", buf.data().constData()); delayed.removeOne(m); } return NeedsSwap; } else { delayed.append(m); todo.removeOne(dependency); Action action = schedule(dependency, todo, delayed, output, swaps); delayed.removeOne(m); Move mm(m); if (action == NeedsSwap) { mm.needsSwap = true; swaps.append(mm); } else { output.append(mm); } return action; } } } output.append(m); return NormalMove; } // References: // [Wimmer1] C. Wimmer and M. Franz. Linear Scan Register Allocation on SSA Form. In Proceedings of // CGO’10, ACM Press, 2010 // [Wimmer2] C. Wimmer and H. Mossenbock. Optimized Interval Splitting in a Linear Scan Register // Allocator. In Proceedings of the ACM/USENIX International Conference on Virtual // Execution Environments, pages 132–141. ACM Press, 2005. // [Briggs] P. Briggs, K.D. Cooper, T.J. Harvey, and L.T. Simpson. Practical Improvements to the // Construction and Destruction of Static Single Assignment Form. // [Appel] A.W. Appel. Modern Compiler Implementation in Java. Second edition, Cambridge // University Press. // [Ramalingam] G. Ramalingam and T. Reps. An Incremental Algorithm for Maintaining the Dominator // Tree of a Reducible Flowgraph.
33.5725
182
0.533908
[ "object", "shape", "vector", "transform" ]
9369a6089ac71816aa58bd7f78744c03bc5595fe
1,949
hpp
C++
include/caffe/layers/kl_loss_layer.hpp
golunovas/caffe
4b2cb4c7039905adc0490654e6cabbdfa658855a
[ "Intel", "BSD-2-Clause" ]
null
null
null
include/caffe/layers/kl_loss_layer.hpp
golunovas/caffe
4b2cb4c7039905adc0490654e6cabbdfa658855a
[ "Intel", "BSD-2-Clause" ]
null
null
null
include/caffe/layers/kl_loss_layer.hpp
golunovas/caffe
4b2cb4c7039905adc0490654e6cabbdfa658855a
[ "Intel", "BSD-2-Clause" ]
2
2019-03-15T13:41:45.000Z
2019-12-02T14:38:11.000Z
#ifndef CAFFE_KL_LOSS_LAYER_HPP_ #define CAFFE_KL_LOSS_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/layers/loss_layer.hpp" #include "caffe/layers/softmax_layer.hpp" namespace caffe { template <typename Dtype> class KLLossLayer : public LossLayer<Dtype> { public: explicit KLLossLayer(const LayerParameter& param) : LossLayer<Dtype>(param) {} 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 inline const char* type() const { return "KLLoss"; } virtual inline int ExactNumTopBlobs() const { return -1; } virtual inline int MinTopBlobs() const { return 1; } virtual inline int MaxTopBlobs() const { return 2; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); /// The internal SoftmaxLayer used to map predictions to a distribution. shared_ptr<Layer<Dtype> > softmax_layer_; /// prob stores the output probability predictions from the SoftmaxLayer. Blob<Dtype> prob_; /// bottom vector holder used in call to the underlying SoftmaxLayer::Forward vector<Blob<Dtype>*> softmax_bottom_vec_; /// top vector holder used in call to the underlying SoftmaxLayer::Forward vector<Blob<Dtype>*> softmax_top_vec_; int softmax_axis_, outer_num_, inner_num_; }; } // namespace caffe #endif // CAFFE_KL_LOSS_LAYER_HPP_
34.803571
79
0.73217
[ "vector" ]
936c8cd6e67772211ddb29ed761480829201eb16
21,697
cpp
C++
cpl/cpl_vsil.cpp
grig27/mitab
0e87a24116af40cb2ec9b122a531b4043bf5154a
[ "Unlicense" ]
19
2015-04-21T05:34:04.000Z
2021-12-30T03:03:36.000Z
cpl/cpl_vsil.cpp
grig27/mitab
0e87a24116af40cb2ec9b122a531b4043bf5154a
[ "Unlicense" ]
1
2019-04-17T15:56:29.000Z
2019-04-17T15:56:29.000Z
cpl/cpl_vsil.cpp
grig27/mitab
0e87a24116af40cb2ec9b122a531b4043bf5154a
[ "Unlicense" ]
21
2015-02-27T10:42:38.000Z
2021-01-18T10:34:24.000Z
/****************************************************************************** * $Id: cpl_vsil.cpp 18725 2010-02-04 21:02:19Z rouault $ * * Project: VSI Virtual File System * Purpose: Implementation VSI*L File API and other file system access * methods going through file virtualization. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2005, Frank Warmerdam <warmerdam@pobox.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 "cpl_vsi_virtual.h" #include "cpl_string.h" #include <string> CPL_CVSID("$Id: cpl_vsil.cpp 18725 2010-02-04 21:02:19Z rouault $"); /************************************************************************/ /* VSIReadDir() */ /************************************************************************/ /** * \brief Read names in a directory. * * This function abstracts access to directory contains. It returns a * list of strings containing the names of files, and directories in this * directory. The resulting string list becomes the responsibility of the * application and should be freed with CSLDestroy() when no longer needed. * * Note that no error is issued via CPLError() if the directory path is * invalid, though NULL is returned. * * This function used to be known as CPLReadDir(), but the old name is now * deprecated. * * @param pszPath the relative, or absolute path of a directory to read. * @return The list of entries in the directory, or NULL if the directory * doesn't exist. */ char **VSIReadDir(const char *pszPath) { VSIFilesystemHandler *poFSHandler = VSIFileManager::GetHandler( pszPath ); return poFSHandler->ReadDir( pszPath ); } /************************************************************************/ /* CPLReadDir() */ /* */ /* This is present only to provide ABI compatability with older */ /* versions. */ /************************************************************************/ #undef CPLReadDir CPL_C_START char CPL_DLL **CPLReadDir( const char *pszPath ); CPL_C_END char **CPLReadDir( const char *pszPath ) { return VSIReadDir(pszPath); } /************************************************************************/ /* VSIMkdir() */ /************************************************************************/ /** * \brief Create a directory. * * Create a new directory with the indicated mode. The mode is ignored * on some platforms. A reasonable default mode value would be 0666. * This method goes through the VSIFileHandler virtualization and may * work on unusual filesystems such as in memory. * * Analog of the POSIX mkdir() function. * * @param pszPathname the path to the directory to create. * @param mode the permissions mode. * * @return 0 on success or -1 on an error. */ int VSIMkdir( const char *pszPathname, long mode ) { VSIFilesystemHandler *poFSHandler = VSIFileManager::GetHandler( pszPathname ); return poFSHandler->Mkdir( pszPathname, mode ); } /************************************************************************/ /* VSIUnlink() */ /*************************a***********************************************/ /** * \brief Delete a file. * * Deletes a file object from the file system. * * This method goes through the VSIFileHandler virtualization and may * work on unusual filesystems such as in memory. * * Analog of the POSIX unlink() function. * * @param pszFilename the path of the file to be deleted. * * @return 0 on success or -1 on an error. */ int VSIUnlink( const char * pszFilename ) { VSIFilesystemHandler *poFSHandler = VSIFileManager::GetHandler( pszFilename ); return poFSHandler->Unlink( pszFilename ); } /************************************************************************/ /* VSIRename() */ /************************************************************************/ /** * \brief Rename a file. * * Renames a file object in the file system. It should be possible * to rename a file onto a new filesystem, but it is safest if this * function is only used to rename files that remain in the same directory. * * This method goes through the VSIFileHandler virtualization and may * work on unusual filesystems such as in memory. * * Analog of the POSIX rename() function. * * @param oldpath the name of the file to be renamed. * @param newpath the name the file should be given. * * @return 0 on success or -1 on an error. */ int VSIRename( const char * oldpath, const char * newpath ) { VSIFilesystemHandler *poFSHandler = VSIFileManager::GetHandler( oldpath ); return poFSHandler->Rename( oldpath, newpath ); } /************************************************************************/ /* VSIRmdir() */ /************************************************************************/ /** * \brief Delete a directory. * * Deletes a directory object from the file system. On some systems * the directory must be empty before it can be deleted. * * This method goes through the VSIFileHandler virtualization and may * work on unusual filesystems such as in memory. * * Analog of the POSIX rmdir() function. * * @param pszDirname the path of the directory to be deleted. * * @return 0 on success or -1 on an error. */ int VSIRmdir( const char * pszDirname ) { VSIFilesystemHandler *poFSHandler = VSIFileManager::GetHandler( pszDirname ); return poFSHandler->Rmdir( pszDirname ); } /************************************************************************/ /* VSIStatL() */ /************************************************************************/ /** * \brief Get filesystem object info. * * Fetches status information about a filesystem object (file, directory, etc). * The returned information is placed in the VSIStatBufL structure. For * portability only the st_size (size in bytes), and st_mode (file type). * This method is similar to VSIStat(), but will work on large files on * systems where this requires special calls. * * This method goes through the VSIFileHandler virtualization and may * work on unusual filesystems such as in memory. * * Analog of the POSIX stat() function. * * @param pszFilename the path of the filesystem object to be queried. * @param psStatBuf the structure to load with information. * * @return 0 on success or -1 on an error. */ int VSIStatL( const char * pszFilename, VSIStatBufL *psStatBuf ) { char szAltPath[4]; /* enable to work on "C:" as if it were "C:\" */ if( strlen(pszFilename) == 2 && pszFilename[1] == ':' ) { szAltPath[0] = pszFilename[0]; szAltPath[1] = pszFilename[1]; szAltPath[2] = '\\'; szAltPath[3] = '\0'; pszFilename = szAltPath; } VSIFilesystemHandler *poFSHandler = VSIFileManager::GetHandler( pszFilename ); return poFSHandler->Stat( pszFilename, psStatBuf ); } /************************************************************************/ /* VSIFOpenL() */ /************************************************************************/ /** * \brief Open file. * * This function opens a file with the desired access. Large files (larger * than 2GB) should be supported. Binary access is always implied and * the "b" does not need to be included in the pszAccess string. * * Note that the "FILE *" returned by this function is not really a * standard C library FILE *, and cannot be used with any functions other * than the "VSI*L" family of functions. They aren't "real" FILE objects. * * This method goes through the VSIFileHandler virtualization and may * work on unusual filesystems such as in memory. * * Analog of the POSIX fopen() function. * * @param pszFilename the file to open. * @param pszAccess access requested (ie. "r", "r+", "w". * * @return NULL on failure, or the file handle. */ FILE *VSIFOpenL( const char * pszFilename, const char * pszAccess ) { VSIFilesystemHandler *poFSHandler = VSIFileManager::GetHandler( pszFilename ); FILE* fp = (FILE *) poFSHandler->Open( pszFilename, pszAccess ); VSIDebug3( "VSIFOpenL(%s,%s) = %p", pszFilename, pszAccess, fp ); return fp; } /************************************************************************/ /* VSIFCloseL() */ /************************************************************************/ /** * \brief Close file. * * This function closes the indicated file. * * This method goes through the VSIFileHandler virtualization and may * work on unusual filesystems such as in memory. * * Analog of the POSIX fclose() function. * * @param fp file handle opened with VSIFOpenL(). * * @return 0 on success or -1 on failure. */ int VSIFCloseL( FILE * fp ) { VSIVirtualHandle *poFileHandle = (VSIVirtualHandle *) fp; VSIDebug1( "VSICloseL(%p)", fp ); int nResult = poFileHandle->Close(); delete poFileHandle; return nResult; } /************************************************************************/ /* VSIFSeekL() */ /************************************************************************/ /** * \brief Seek to requested offset. * * Seek to the desired offset (nOffset) in the indicated file. * * This method goes through the VSIFileHandler virtualization and may * work on unusual filesystems such as in memory. * * Analog of the POSIX fseek() call. * * @param fp file handle opened with VSIFOpenL(). * @param nOffset offset in bytes. * @param nWhence one of SEEK_SET, SEEK_CUR or SEEK_END. * * @return 0 on success or -1 one failure. */ int VSIFSeekL( FILE * fp, vsi_l_offset nOffset, int nWhence ) { VSIVirtualHandle *poFileHandle = (VSIVirtualHandle *) fp; return poFileHandle->Seek( nOffset, nWhence ); } /************************************************************************/ /* VSIFTellL() */ /************************************************************************/ /** * \brief Tell current file offset. * * Returns the current file read/write offset in bytes from the beginning of * the file. * * This method goes through the VSIFileHandler virtualization and may * work on unusual filesystems such as in memory. * * Analog of the POSIX ftell() call. * * @param fp file handle opened with VSIFOpenL(). * * @return file offset in bytes. */ vsi_l_offset VSIFTellL( FILE * fp ) { VSIVirtualHandle *poFileHandle = (VSIVirtualHandle *) fp; return poFileHandle->Tell(); } /************************************************************************/ /* VSIRewindL() */ /************************************************************************/ void VSIRewindL( FILE * fp ) { VSIFSeekL( fp, 0, SEEK_SET ); } /************************************************************************/ /* VSIFFlushL() */ /************************************************************************/ /** * \brief Flush pending writes to disk. * * For files in write or update mode and on filesystem types where it is * applicable, all pending output on the file is flushed to the physical disk. * * This method goes through the VSIFileHandler virtualization and may * work on unusual filesystems such as in memory. * * Analog of the POSIX fflush() call. * * @param fp file handle opened with VSIFOpenL(). * * @return 0 on success or -1 on error. */ int VSIFFlushL( FILE * fp ) { VSIVirtualHandle *poFileHandle = (VSIVirtualHandle *) fp; return poFileHandle->Flush(); } /************************************************************************/ /* VSIFReadL() */ /************************************************************************/ /** * \brief Read bytes from file. * * Reads nCount objects of nSize bytes from the indicated file at the * current offset into the indicated buffer. * * This method goes through the VSIFileHandler virtualization and may * work on unusual filesystems such as in memory. * * Analog of the POSIX fread() call. * * @param pBuffer the buffer into which the data should be read (at least * nCount * nSize bytes in size. * @param nSize size of objects to read in bytes. * @param nCount number of objects to read. * @param fp file handle opened with VSIFOpenL(). * * @return number of objects successfully read. */ size_t VSIFReadL( void * pBuffer, size_t nSize, size_t nCount, FILE * fp ) { VSIVirtualHandle *poFileHandle = (VSIVirtualHandle *) fp; return poFileHandle->Read( pBuffer, nSize, nCount ); } /************************************************************************/ /* VSIFWriteL() */ /************************************************************************/ /** * \brief Write bytes to file. * * Writess nCount objects of nSize bytes to the indicated file at the * current offset into the indicated buffer. * * This method goes through the VSIFileHandler virtualization and may * work on unusual filesystems such as in memory. * * Analog of the POSIX fwrite() call. * * @param pBuffer the buffer from which the data should be written (at least * nCount * nSize bytes in size. * @param nSize size of objects to read in bytes. * @param nCount number of objects to read. * @param fp file handle opened with VSIFOpenL(). * * @return number of objects successfully written. */ size_t VSIFWriteL( const void *pBuffer, size_t nSize, size_t nCount, FILE *fp ) { VSIVirtualHandle *poFileHandle = (VSIVirtualHandle *) fp; return poFileHandle->Write( pBuffer, nSize, nCount ); } /************************************************************************/ /* VSIFEofL() */ /************************************************************************/ /** * \brief Test for end of file. * * Returns TRUE (non-zero) if the file read/write offset is currently at the * end of the file. * * This method goes through the VSIFileHandler virtualization and may * work on unusual filesystems such as in memory. * * Analog of the POSIX feof() call. * * @param fp file handle opened with VSIFOpenL(). * * @return TRUE if at EOF else FALSE. */ int VSIFEofL( FILE * fp ) { VSIVirtualHandle *poFileHandle = (VSIVirtualHandle *) fp; return poFileHandle->Eof(); } /************************************************************************/ /* VSIFPrintfL() */ /************************************************************************/ /** * \brief Formatted write to file. * * Provides fprintf() style formatted output to a VSI*L file. This formats * an internal buffer which is written using VSIFWriteL(). * * Analog of the POSIX fprintf() call. * * @param fp file handle opened with VSIFOpenL(). * @param pszFormat the printf style format string. * * @return the number of bytes written or -1 on an error. */ int VSIFPrintfL( FILE *fp, const char *pszFormat, ... ) { va_list args; CPLString osResult; va_start( args, pszFormat ); osResult.vPrintf( pszFormat, args ); va_end( args ); return VSIFWriteL( osResult.c_str(), 1, osResult.length(), fp ); } /************************************************************************/ /* VSIFPutcL() */ /************************************************************************/ int VSIFPutcL( int nChar, FILE * fp ) { unsigned char cChar = (unsigned char)nChar; return VSIFWriteL(&cChar, 1, 1, fp); } /************************************************************************/ /* ==================================================================== */ /* VSIFileManager() */ /* ==================================================================== */ /************************************************************************/ /* ** Notes on Multithreading: ** ** The VSIFileManager maintains a list of file type handlers (mem, large ** file, etc). It should be thread safe as long as all the handlers are ** instantiated before multiple threads begin to operate. **/ /************************************************************************/ /* VSIFileManager() */ /************************************************************************/ VSIFileManager::VSIFileManager() { poDefaultHandler = NULL; } /************************************************************************/ /* ~VSIFileManager() */ /************************************************************************/ VSIFileManager::~VSIFileManager() { std::map<std::string,VSIFilesystemHandler*>::const_iterator iter; for( iter = oHandlers.begin(); iter != oHandlers.end(); iter++ ) { delete iter->second; } delete poDefaultHandler; } /************************************************************************/ /* Get() */ /************************************************************************/ static VSIFileManager *poManager = NULL; VSIFileManager *VSIFileManager::Get() { if( poManager == NULL ) { poManager = new VSIFileManager; VSIInstallLargeFileHandler(); VSIInstallSubFileHandler(); VSIInstallMemFileHandler(); #ifdef HAVE_LIBZ VSIInstallGZipFileHandler(); VSIInstallZipFileHandler(); #endif VSIInstallStdoutHandler(); } return poManager; } /************************************************************************/ /* GetHandler() */ /************************************************************************/ VSIFilesystemHandler *VSIFileManager::GetHandler( const char *pszPath ) { VSIFileManager *poThis = Get(); std::map<std::string,VSIFilesystemHandler*>::const_iterator iter; int nPathLen = strlen(pszPath); for( iter = poThis->oHandlers.begin(); iter != poThis->oHandlers.end(); iter++ ) { const char* pszIterKey = iter->first.c_str(); int nIterKeyLen = iter->first.size(); if( strncmp(pszPath,pszIterKey,nIterKeyLen) == 0 ) return iter->second; /* "/vsimem\foo" should be handled as "/vsimem/foo" */ if (nIterKeyLen && nPathLen > nIterKeyLen && pszIterKey[nIterKeyLen-1] == '/' && pszPath[nIterKeyLen-1] == '\\' && strncmp(pszPath,pszIterKey,nIterKeyLen-1) == 0 ) return iter->second; } return poThis->poDefaultHandler; } /************************************************************************/ /* InstallHandler() */ /************************************************************************/ void VSIFileManager::InstallHandler( const std::string& osPrefix, VSIFilesystemHandler *poHandler ) { if( osPrefix == "" ) Get()->poDefaultHandler = poHandler; else Get()->oHandlers[osPrefix] = poHandler; } /************************************************************************/ /* VSICleanupFileManager() */ /************************************************************************/ void VSICleanupFileManager() { if( poManager ) { delete poManager; poManager = NULL; } }
32.143704
79
0.502788
[ "object" ]
936e35bf3306f5531dc1b3c2cecd57bc3c597bc3
2,871
cc
C++
chrome/common/temp_scaffolding_stubs.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
11
2015-03-20T04:08:08.000Z
2021-11-15T15:51:36.000Z
chrome/common/temp_scaffolding_stubs.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
chrome/common/temp_scaffolding_stubs.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/temp_scaffolding_stubs.h" #include <vector> #include "base/gfx/rect.h" #include "base/logging.h" #include "chrome/browser/automation/automation_provider.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/fonts_languages_window.h" #include "chrome/browser/memory_details.h" //-------------------------------------------------------------------------- void AutomationProvider::GetAutocompleteEditForBrowser( int browser_handle, bool* success, int* autocomplete_edit_handle) { *success = false; NOTIMPLEMENTED(); } void AutomationProvider::GetAutocompleteEditText(int autocomplete_edit_handle, bool* success, std::wstring* text) { *success = false; NOTIMPLEMENTED(); } void AutomationProvider::SetAutocompleteEditText(int autocomplete_edit_handle, const std::wstring& text, bool* success) { *success = false; NOTIMPLEMENTED(); } void AutomationProvider::AutocompleteEditGetMatches( int autocomplete_edit_handle, bool* success, std::vector<AutocompleteMatchData>* matches) { *success = false; NOTIMPLEMENTED(); } void AutomationProvider::AutocompleteEditIsQueryInProgress( int autocomplete_edit_handle, bool* success, bool* query_in_progress) { *success = false; NOTIMPLEMENTED(); } void AutomationProvider::OnMessageFromExternalHost( int handle, const std::string& message, const std::string& origin, const std::string& target) { NOTIMPLEMENTED(); } void InstallJankometer(const CommandLine&) { // http://code.google.com/p/chromium/issues/detail?id=8077 } void UninstallJankometer() { // http://code.google.com/p/chromium/issues/detail?id=8077 } void BrowserList::AllBrowsersClosed() { // TODO(port): Close any dependent windows if necessary when the last browser // window is closed. } //-------------------------------------------------------------------------- bool DockInfo::GetNewWindowBounds(gfx::Rect* new_window_bounds, bool* maximize_new_window) const { // TODO(pinkerton): Implement on Mac. // http://crbug.com/9274 return true; } void DockInfo::AdjustOtherWindowBounds() const { // TODO(pinkerton): Implement on Mac. // http://crbug.com/9274 } //------------------------------------------------------------------------------ void ShowFontsLanguagesWindow(gfx::NativeWindow window, FontsLanguagesPage page, Profile* profile) { NOTIMPLEMENTED(); }
29.90625
80
0.611285
[ "vector" ]
93704023377dd09f94e204659f101a8715eab87f
4,253
cpp
C++
src/symtab.cpp
yspjack/compiler-design
2bd3faea4ff0f8b9bbb26711a2c1289fa3718027
[ "MIT" ]
null
null
null
src/symtab.cpp
yspjack/compiler-design
2bd3faea4ff0f8b9bbb26711a2c1289fa3718027
[ "MIT" ]
null
null
null
src/symtab.cpp
yspjack/compiler-design
2bd3faea4ff0f8b9bbb26711a2c1289fa3718027
[ "MIT" ]
null
null
null
#include <map> #include <vector> #include <string> #include <cstdio> #include <cassert> #include "lexer.h" #include "symtab.h" #include "errproc.h" using namespace std; Symbol::Symbol() :clazz(-1), type(-1), name("") {} Symbol::Symbol(int clazz, int type, const string& name) : clazz(clazz), type(type), name(name) { assert((clazz == SYM_FUNC) || (type != SYM_VOID)); if (clazz != SYM_FUNC) { if (type == SYM_INT) { size = sizeof(int); } else if (type == SYM_CHAR) { size = sizeof(char); } } addr = 0; value = 0; } // Add global symbol // handles NAME_REDEFINITION void SymTable::addGlobal(int clazz, int type, const string& name, int value) { assert(clazz == Symbol::SYM_CONST || clazz == Symbol::SYM_ARRAY || clazz == Symbol::SYM_VAR || clazz == Symbol::SYM_FUNC); if (globalSymbols.count(name)) { handleError(NAME_REDEFINITION, linenumber); return; } Symbol s = Symbol(clazz, type, name); s.value = value; s.global = true; globalSymbols[name] = s; if (clazz == Symbol::SYM_FUNC) { functionLocalSymbols[name] = std::map<string, Symbol>(); functionParams[name] = vector<Symbol>(); } } // Add local symbol if func!="" // handles NAME_REDEFINITION void SymTable::addLocal(const string& func, int clazz, int type, const string& name, int value) { //printf("%s,%s,%d,%d\n", func.c_str(), name.c_str(), clazz, type); if (func == "") { addGlobal(clazz, type, name, value); } else { assert(functionLocalSymbols.count(func)); assert(functionParams.count(func)); assert(clazz == Symbol::SYM_CONST || clazz == Symbol::SYM_ARRAY || clazz == Symbol::SYM_VAR || clazz == Symbol::SYM_PARAM); if (functionLocalSymbols[func].count(name)) { handleError(NAME_REDEFINITION, linenumber); return; } Symbol s = Symbol(clazz, type, name); s.value = value; s.global = false; functionLocalSymbols[func][name] = s; if (clazz == Symbol::SYM_PARAM) { functionParams[func].push_back(s); } } } Symbol* SymTable::getByName(const string& func, const string& name) { if (func == "") { if (globalSymbols.count(name)) { return &globalSymbols[name]; } } else { if (functionLocalSymbols.count(func)) { if (functionLocalSymbols[func].count(name)) { return &functionLocalSymbols[func][name]; } if (globalSymbols.count(name)) { return &globalSymbols[name]; } } } return nullptr; } vector<Symbol>& SymTable::getParams(const string& func) { assert(functionParams.count(func)); return functionParams[func]; } void SymTable::addString(const string& value) { if (stringId.count(value)) { return; } stringPool.push_back(value); stringId[value] = stringPool.size() - 1; } void dumpSymbol(const Symbol& s) { static map<int, string > typeStr = { {Symbol::SYM_ARRAY,"ARRAY"}, {Symbol::SYM_CHAR,"CHAR"}, {Symbol::SYM_CONST,"CONST"}, {Symbol::SYM_FUNC,"FUNC"}, {Symbol::SYM_INT,"INT"}, {Symbol::SYM_PARAM,"PARAM"}, {Symbol::SYM_VAR,"VAR"}, {Symbol::SYM_VOID,"VOID"} }; printf("%s %s %s", s.name.c_str(), typeStr[s.clazz].c_str(), typeStr[s.type].c_str()); if (s.clazz == Symbol::SYM_CONST) { if (s.type == Symbol::SYM_CHAR) { printf(" value=\'%c\'", (char)s.value); } else { printf(" value=%d", s.value); } } else if (s.clazz == Symbol::SYM_ARRAY) { printf(" size=%d", s.size); } printf(" addr=%x", s.addr); printf("\n"); } void SymTable::dump() { printf("----Global\n"); for (const auto& p : globalSymbols) { const Symbol& s = p.second; dumpSymbol(s); } for (const auto& p1 : functionLocalSymbols) { printf("----Function %s\n", p1.first.c_str()); for (const auto& p : functionLocalSymbols[p1.first]) { const Symbol& s = p.second; dumpSymbol(s); } } }
29.331034
131
0.562191
[ "vector" ]
9371e0026323ed950b7e70406216a03cf8f6c60a
10,072
hpp
C++
components/common/cpp/include/ftl/utility/msgpack.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
4
2020-12-28T15:29:15.000Z
2021-06-27T12:37:15.000Z
components/common/cpp/include/ftl/utility/msgpack.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
null
null
null
components/common/cpp/include/ftl/utility/msgpack.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
2
2021-01-13T05:28:39.000Z
2021-05-04T03:37:11.000Z
/** * @file msgpack.hpp * @copyright Copyright (c) 2020 University of Turku, MIT License * @author Sebastian Hahta */ /* Extend msgpack for OpenCV and Eigen types */ #ifndef _FTL_MSGPACK_HPP_ #define _FTL_MSGPACK_HPP_ #ifdef _MSC_VER #include "msgpack_optional.hpp" #endif #include <msgpack.hpp> #include <opencv2/core/mat.hpp> #include <Eigen/Eigen> namespace msgpack { MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) { namespace adaptor { //////////////////////////////////////////////////////////////////////////////// // cv::Size_<T> template<typename T> struct pack<cv::Size_<T>> { template <typename Stream> packer<Stream>& operator()(msgpack::packer<Stream>& o, cv::Size_<T> const& v) const { o.pack_array(2); o.pack(v.width); o.pack(v.height); return o; } }; template<typename T> struct convert<cv::Size_<T>> { msgpack::object const& operator()(msgpack::object const& o, cv::Size_<T>& v) const { if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 2) { throw msgpack::type_error(); } T width = o.via.array.ptr[0].as<T>(); T height = o.via.array.ptr[1].as<T>(); v = cv::Size_<T>(width, height); return o; } }; template <typename T> struct object_with_zone<cv::Size_<T>> { void operator()(msgpack::object::with_zone& o, cv::Size_<T> const& v) const { o.type = type::ARRAY; o.via.array.size = 2; o.via.array.ptr = static_cast<msgpack::object*>( o.zone.allocate_align( sizeof(msgpack::object) * o.via.array.size, MSGPACK_ZONE_ALIGNOF(msgpack::object))); o.via.array.ptr[0] = msgpack::object(v.width, o.zone); o.via.array.ptr[1] = msgpack::object(v.height, o.zone); } }; //////////////////////////////////////////////////////////////////////////////// // cv::Rect_<T> template<typename T> struct pack<cv::Rect_<T>> { template <typename Stream> packer<Stream>& operator()(msgpack::packer<Stream>& o, cv::Rect_<T> const& v) const { o.pack_array(4); o.pack(v.height); o.pack(v.width); o.pack(v.x); o.pack(v.y); return o; } }; template<typename T> struct convert<cv::Rect_<T>> { msgpack::object const& operator()(msgpack::object const& o, cv::Rect_<T> &v) const { if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 4) { throw msgpack::type_error(); } T height = o.via.array.ptr[0].as<T>(); T width = o.via.array.ptr[1].as<T>(); T x = o.via.array.ptr[2].as<T>(); T y = o.via.array.ptr[3].as<T>(); v = cv::Rect_<T>(x, y, width, height); return o; } }; template <typename T> struct object_with_zone<cv::Rect_<T>> { void operator()(msgpack::object::with_zone& o, cv::Rect_<T> const& v) const { o.type = type::ARRAY; o.via.array.size = 4; o.via.array.ptr = static_cast<msgpack::object*>( o.zone.allocate_align( sizeof(msgpack::object) * o.via.array.size, MSGPACK_ZONE_ALIGNOF(msgpack::object))); o.via.array.ptr[0] = msgpack::object(v.heigth, o.zone); o.via.array.ptr[1] = msgpack::object(v.width, o.zone); o.via.array.ptr[2] = msgpack::object(v.x, o.zone); o.via.array.ptr[3] = msgpack::object(v.y, o.zone); } }; //////////////////////////////////////////////////////////////////////////////// // cv::Vec template<typename T, int SIZE> struct pack<cv::Vec<T, SIZE>> { template <typename Stream> packer<Stream>& operator()(msgpack::packer<Stream>& o, cv::Vec<T, SIZE> const& v) const { o.pack_array(SIZE); for (int i = 0; i < SIZE; i++) { o.pack(v[i]); } return o; } }; template<typename T, int SIZE> struct convert<cv::Vec<T, SIZE>> { msgpack::object const& operator()(msgpack::object const& o, cv::Vec<T, SIZE> &v) const { if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != SIZE) { throw msgpack::type_error(); } for (int i = 0; i < SIZE; i++) { v[i] = o.via.array.ptr[i].as<T>(); } return o; } }; template <typename T, int SIZE> struct object_with_zone<cv::Vec<T, SIZE>> { void operator()(msgpack::object::with_zone& o, cv::Vec<T, SIZE> const& v) const { o.type = type::ARRAY; o.via.array.size = SIZE; o.via.array.ptr = static_cast<msgpack::object*>( o.zone.allocate_align( sizeof(msgpack::object) * o.via.array.size, MSGPACK_ZONE_ALIGNOF(msgpack::object))); for (int i = 0; i < SIZE; i++) { o.via.array.ptr[i] = msgpack::object(v[i], o.zone); } } }; //////////////////////////////////////////////////////////////////////////////// // cv::Point_ template<typename T> struct pack<cv::Point_<T>> { template <typename Stream> packer<Stream>& operator()(msgpack::packer<Stream>& o, cv::Point_<T> const& p) const { o.pack_array(2); o.pack(p.x); o.pack(p.y); return o; } }; template<typename T> struct convert<cv::Point_<T>> { msgpack::object const& operator()(msgpack::object const& o, cv::Point_<T> &p) const { if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 2) { throw msgpack::type_error(); } p.x = o.via.array.ptr[0].as<T>(); p.y = o.via.array.ptr[1].as<T>(); return o; } }; template <typename T> struct object_with_zone<cv::Point_<T>> { void operator()(msgpack::object::with_zone& o, cv::Point_<T> const& p) const { o.type = type::ARRAY; o.via.array.size = 2; o.via.array.ptr = static_cast<msgpack::object*>( o.zone.allocate_align( sizeof(msgpack::object) * o.via.array.size, MSGPACK_ZONE_ALIGNOF(msgpack::object))); o.via.array.ptr[0] = msgpack::object(p.x, o.zone); o.via.array.ptr[1] = msgpack::object(p.y, o.zone); } }; //////////////////////////////////////////////////////////////////////////////// // cv::Point3_ template<typename T> struct pack<cv::Point3_<T>> { template <typename Stream> packer<Stream>& operator()(msgpack::packer<Stream>& o, cv::Point3_<T> const& p) const { o.pack_array(3); o.pack(p.x); o.pack(p.y); o.pack(p.z); return o; } }; template<typename T> struct convert<cv::Point3_<T>> { msgpack::object const& operator()(msgpack::object const& o, cv::Point3_<T> &p) const { if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 3) { throw msgpack::type_error(); } p.x = o.via.array.ptr[0].as<T>(); p.y = o.via.array.ptr[1].as<T>(); p.z = o.via.array.ptr[2].as<T>(); return o; } }; template <typename T> struct object_with_zone<cv::Point3_<T>> { void operator()(msgpack::object::with_zone& o, cv::Point3_<T> const& p) const { o.type = type::ARRAY; o.via.array.size = 3; o.via.array.ptr = static_cast<msgpack::object*>( o.zone.allocate_align( sizeof(msgpack::object) * o.via.array.size, MSGPACK_ZONE_ALIGNOF(msgpack::object))); o.via.array.ptr[0] = msgpack::object(p.x, o.zone); o.via.array.ptr[1] = msgpack::object(p.y, o.zone); o.via.array.ptr[2] = msgpack::object(p.z, o.zone); } }; //////////////////////////////////////////////////////////////////////////////// // cv::Mat template<> struct pack<cv::Mat> { template <typename Stream> packer<Stream>& operator()(msgpack::packer<Stream>& o, cv::Mat const& v) const { // TODO: non continuous cv::Mat if (!v.isContinuous()) { throw::msgpack::type_error(); } o.pack_array(3); o.pack(v.type()); o.pack(v.size()); auto size = v.total() * v.elemSize(); o.pack(msgpack::type::raw_ref(reinterpret_cast<char*>(v.data), size)); return o; } }; template<> struct convert<cv::Mat> { msgpack::object const& operator()(msgpack::object const& o, cv::Mat& v) const { if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 3) { throw msgpack::type_error(); } int type = o.via.array.ptr[0].as<int>(); cv::Size size = o.via.array.ptr[1].as<cv::Size>(); v.create(size, type); if (o.via.array.ptr[2].via.bin.size != (v.total() * v.elemSize())) { throw msgpack::type_error(); } memcpy( v.data, reinterpret_cast<const uchar*>(o.via.array.ptr[2].via.bin.ptr), o.via.array.ptr[2].via.bin.size); return o; } }; template <> struct object_with_zone<cv::Mat> { void operator()(msgpack::object::with_zone& o, cv::Mat const& v) const { o.type = type::ARRAY; o.via.array.size = 3; o.via.array.ptr = static_cast<msgpack::object*>( o.zone.allocate_align( sizeof(msgpack::object) * o.via.array.size, MSGPACK_ZONE_ALIGNOF(msgpack::object))); auto size = v.total() * v.elemSize(); o.via.array.ptr[0] = msgpack::object(v.type(), o.zone); o.via.array.ptr[1] = msgpack::object(v.size(), o.zone); // https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_object#conversion // raw_ref not copied to zone (is this a problem?) o.via.array.ptr[2] = msgpack::object( msgpack::type::raw_ref(reinterpret_cast<char*>(v.data), static_cast<uint32_t>(size)), o.zone); } }; //////////////////////////////////////////////////////////////////////////////// // Eigen::Matrix<> template <typename T, int X, int Y> struct pack<Eigen::Matrix<T, X, Y>> { template <typename Stream> packer<Stream>& operator()(msgpack::packer<Stream>& o, Eigen::Matrix<T, X, Y> const& v) const { o.pack_array(X*Y); for (int i = 0; i < X*Y; i++) { o.pack(v.data()[i]); } return o; } }; template<typename T, int X, int Y> struct convert<Eigen::Matrix<T, X, Y>> { msgpack::object const& operator()(msgpack::object const& o, Eigen::Matrix<T, X, Y> &v) const { if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != X*Y) { throw msgpack::type_error(); } for (int i = 0; i < X*Y; i++) { v.data()[i] = o.via.array.ptr[i].as<T>(); } return o; } }; template <typename T, int X, int Y> struct object_with_zone<Eigen::Matrix<T, X, Y>> { void operator()(msgpack::object::with_zone& o, Eigen::Matrix<T, X, Y> const& v) const { o.type = type::ARRAY; o.via.array.size = X*Y; o.via.array.ptr = static_cast<msgpack::object*>( o.zone.allocate_align( sizeof(msgpack::object) * o.via.array.size, MSGPACK_ZONE_ALIGNOF(msgpack::object))); for (int i = 0; i < X*Y; i++) { o.via.array.ptr[i] = msgpack::object(v.data()[i], o.zone); } } }; } } } #endif
28.292135
96
0.603554
[ "object" ]
9378b60c4562fea43aa75d323b8c647c51529047
2,833
cpp
C++
worldengine/source/images/biome_image.cpp
dpaulat/worldengine-cpp
9f7961aaf62db2633fc9d44b6018384812a6704e
[ "MIT" ]
2
2021-06-09T12:44:37.000Z
2021-06-10T21:52:10.000Z
worldengine/source/images/biome_image.cpp
dpaulat/worldengine-cpp
9f7961aaf62db2633fc9d44b6018384812a6704e
[ "MIT" ]
1
2021-06-09T12:49:33.000Z
2021-06-17T15:28:37.000Z
worldengine/source/images/biome_image.cpp
dpaulat/worldengine-cpp
9f7961aaf62db2633fc9d44b6018384812a6704e
[ "MIT" ]
null
null
null
#include "worldengine/images/biome_image.h" namespace WorldEngine { static std::unordered_map<Biome, boost::gil::rgb8_pixel_t> biomeColors_ = { {Biome::Ocean, {23, 94, 145}}, {Biome::Sea, {23, 94, 145}}, {Biome::Ice, {255, 255, 255}}, {Biome::SubpolarDryTundra, {128, 128, 128}}, {Biome::SubpolarMoistTundra, {96, 128, 128}}, {Biome::SubpolarWetTundra, {64, 128, 128}}, {Biome::SubpolarRainTundra, {32, 128, 192}}, {Biome::PolarDesert, {192, 192, 192}}, {Biome::BorealDesert, {160, 160, 128}}, {Biome::CoolTemperateDesert, {192, 192, 128}}, {Biome::WarmTemperateDesert, {224, 224, 128}}, {Biome::SubtropicalDesert, {240, 240, 128}}, {Biome::TropicalDesert, {255, 255, 128}}, {Biome::BorealRainForest, {32, 160, 192}}, {Biome::CoolTemperateRainForest, {32, 192, 192}}, {Biome::WarmTemperateRainForest, {32, 224, 192}}, {Biome::SubtropicalRainForest, {32, 240, 176}}, {Biome::TropicalRainForest, {32, 255, 160}}, {Biome::BorealWetForest, {64, 160, 144}}, {Biome::CoolTemperateWetForest, {64, 192, 144}}, {Biome::WarmTemperateWetForest, {64, 224, 144}}, {Biome::SubtropicalWetForest, {64, 240, 144}}, {Biome::TropicalWetForest, {64, 255, 144}}, {Biome::BorealMoistForest, {96, 160, 128}}, {Biome::CoolTemperateMoistForest, {96, 192, 128}}, {Biome::WarmTemperateMoistForest, {96, 224, 128}}, {Biome::SubtropicalMoistForest, {96, 240, 128}}, {Biome::TropicalMoistForest, {96, 255, 128}}, {Biome::WarmTemperateDryForest, {128, 224, 128}}, {Biome::SubtropicalDryForest, {128, 240, 128}}, {Biome::TropicalDryForest, {128, 255, 128}}, {Biome::BorealDryScrub, {128, 160, 128}}, {Biome::CoolTemperateDesertScrub, {160, 192, 128}}, {Biome::WarmTemperateDesertScrub, {192, 224, 128}}, {Biome::SubtropicalDesertScrub, {208, 240, 128}}, {Biome::TropicalDesertScrub, {224, 255, 128}}, {Biome::CoolTemperateSteppe, {128, 192, 128}}, {Biome::WarmTemperateThornScrub, {160, 224, 128}}, {Biome::SubtropicalThornWoodland, {176, 240, 128}}, {Biome::TropicalThornWoodland, {192, 255, 128}}, {Biome::TropicalVeryDryForest, {192, 255, 128}}, {Biome::BareRock, {96, 96, 96}}}; BiomeImage::BiomeImage(const World& world) : Image(world, false) {} BiomeImage::~BiomeImage() {} void BiomeImage::DrawImage(boost::gil::rgb8_image_t::view_t& target) { const BiomeArrayType& biomes = world_.GetBiomeData(); const uint32_t width = static_cast<uint32_t>(biomes.shape()[1]); const uint32_t height = static_cast<uint32_t>(biomes.shape()[0]); for (uint32_t y = 0; y < height; y++) { for (uint32_t x = 0; x < width; x++) { target(x, y) = biomeColors_[biomes[y][x]]; } } } boost::gil::rgb8_pixel_t BiomeImage::BiomeColor(Biome biome) { return biomeColors_[biome]; } } // namespace WorldEngine
38.808219
75
0.657254
[ "shape" ]
937931d678b23df3f1b365ad5010aa78235917ad
780
hpp
C++
GLFramework/SceneGraph/SceneManager.hpp
Illation/GLFramework
2b9d3d67d4e951e2ff5ace0241750a438d6e743f
[ "MIT" ]
39
2016-03-23T00:39:46.000Z
2022-02-07T21:26:05.000Z
GLFramework/SceneGraph/SceneManager.hpp
Illation/GLFramework
2b9d3d67d4e951e2ff5ace0241750a438d6e743f
[ "MIT" ]
1
2016-03-24T14:39:45.000Z
2016-03-24T17:34:39.000Z
GLFramework/SceneGraph/SceneManager.hpp
Illation/GLFramework
2b9d3d67d4e951e2ff5ace0241750a438d6e743f
[ "MIT" ]
3
2016-08-15T01:27:13.000Z
2021-12-29T01:37:51.000Z
#pragma once #include "../Helper/Singleton.h" #include <string> #include <vector> //Forward Declaration class AbstractScene; class AbstractFramework; class SceneManager : public Singleton<SceneManager> { public: ~SceneManager(); void AddGameScene(AbstractScene* scene); void RemoveGameScene(AbstractScene* scene); void SetActiveGameScene(std::string sceneName); void NextScene(); void PreviousScene(); AbstractScene* GetActiveScene() const { return m_ActiveScene; } private: friend class AbstractFramework; friend class Singleton<SceneManager>; SceneManager(); void Initialize(); void Update(); void Draw(); std::vector<AbstractScene*> m_pSceneVec; bool m_IsInitialized = false; AbstractScene* m_ActiveScene = nullptr , *m_NewActiveScene = nullptr; };
20
64
0.762821
[ "vector" ]
937952c4802562a4f4d57dcf9a5e155788a37fbf
5,443
cpp
C++
tests/src/CSVReaderTests.cpp
Ishiko-Cpp/CSV
239e5ae66877a4bac3abb53e19c28cd4a6991067
[ "MIT" ]
null
null
null
tests/src/CSVReaderTests.cpp
Ishiko-Cpp/CSV
239e5ae66877a4bac3abb53e19c28cd4a6991067
[ "MIT" ]
null
null
null
tests/src/CSVReaderTests.cpp
Ishiko-Cpp/CSV
239e5ae66877a4bac3abb53e19c28cd4a6991067
[ "MIT" ]
null
null
null
/* Copyright (c) 2019-2022 Xavier Leclercq Released under the MIT License See https://github.com/ishiko-cpp/csv/blob/main/LICENSE.txt */ #include "CSVReaderTests.h" #include <Ishiko/CSV/CSVReader.hpp> #include <Ishiko/Errors.hpp> #include <Ishiko/FileSystem.hpp> using namespace boost::filesystem; using namespace Ishiko; using namespace Ishiko::CSV; using namespace Ishiko::Tests; using namespace std; CSVReaderTests::CSVReaderTests(const TestNumber& number, const TestContext& context) : TestSequence(number, "CSVReader tests", context) { append<HeapAllocationErrorsTest>("Constructor test 1", ConstructorTest1); append<HeapAllocationErrorsTest>("open test 1", OpenTest1); append<HeapAllocationErrorsTest>("readLine test 1", ReadLineTest1); append<HeapAllocationErrorsTest>("readLine test 2", ReadLineTest2); append<HeapAllocationErrorsTest>("readLine test 3", ReadLineTest3); append<HeapAllocationErrorsTest>("readLine test 4", ReadLineTest4); append<HeapAllocationErrorsTest>("readAllLines test 1", ReadAllLinesTest1); append<HeapAllocationErrorsTest>("readAllLines test 2", ReadAllLinesTest2); append<HeapAllocationErrorsTest>("forEachLine test 1", ForEachLineTest1); } void CSVReaderTests::ConstructorTest1(Test& test) { CSVReader reader; ISHIKO_TEST_PASS(); } void CSVReaderTests::OpenTest1(Test& test) { path inputPath(test.context().getTestDataPath("empty.csv")); CSVReader reader; Error error; reader.open(inputPath, error); ISHIKO_TEST_FAIL_IF(error) ISHIKO_TEST_PASS(); } void CSVReaderTests::ReadLineTest1(Test& test) { path inputPath(test.context().getTestDataPath("empty.csv")); Error error; CSVReader reader; reader.open(inputPath, error); ISHIKO_TEST_ABORT_IF(error); vector<string> line = reader.readLine(error); ISHIKO_TEST_FAIL_IF_NOT(error); ISHIKO_TEST_FAIL_IF_NEQ(error.condition(), FileSystemErrorCategory::Value::endOfFile); ISHIKO_TEST_FAIL_IF_NEQ(line.size(), 0); ISHIKO_TEST_PASS(); } void CSVReaderTests::ReadLineTest2(Test& test) { path inputPath(test.context().getTestDataPath("CSVReaderTests_ReadLineTest2.csv")); Error error; CSVReader reader; reader.open(inputPath, error); ISHIKO_TEST_ABORT_IF(error); vector<string> line = reader.readLine(error); ISHIKO_TEST_FAIL_IF(error); ISHIKO_TEST_ABORT_IF_NEQ(line.size(), 1); ISHIKO_TEST_FAIL_IF_NEQ(line[0], "Title 1"); ISHIKO_TEST_PASS(); } void CSVReaderTests::ReadLineTest3(Test& test) { path inputPath(test.context().getTestDataPath("CSVReaderTests_ReadLineTest3.csv")); Error error; CSVReader reader; reader.open(inputPath, error); ISHIKO_TEST_ABORT_IF(error); vector<string> line = reader.readLine(error); ISHIKO_TEST_FAIL_IF(error); ISHIKO_TEST_ABORT_IF_NEQ(line.size(), 2); ISHIKO_TEST_FAIL_IF_NEQ(line[0], "Title 1"); ISHIKO_TEST_FAIL_IF_NEQ(line[1], "Title 2"); ISHIKO_TEST_PASS(); } void CSVReaderTests::ReadLineTest4(Test& test) { path inputPath(test.context().getTestDataPath("CSVReaderTests_ReadLineTest4.csv")); Error error; CSVReader reader; reader.open(inputPath, error); ISHIKO_TEST_ABORT_IF(error); vector<string> line = reader.readLine(error); ISHIKO_TEST_FAIL_IF(error); ISHIKO_TEST_ABORT_IF_NEQ(line.size(), 1); ISHIKO_TEST_FAIL_IF_NEQ(line[0], "Title 1"); ISHIKO_TEST_PASS(); } void CSVReaderTests::ReadAllLinesTest1(Test& test) { path inputPath(test.context().getTestDataPath("empty.csv")); Error error; CSVReader reader; reader.open(inputPath, error); ISHIKO_TEST_ABORT_IF(error); vector<vector<string>> lines = reader.readAllLines(error); ISHIKO_TEST_FAIL_IF(error); ISHIKO_TEST_FAIL_IF_NEQ(lines.size(), 0); ISHIKO_TEST_PASS(); } void CSVReaderTests::ReadAllLinesTest2(Test& test) { path inputPath(test.context().getTestDataPath("CSVReaderTests_ReadAllLinesTest2.csv")); Error error; CSVReader reader; reader.open(inputPath, error); ISHIKO_TEST_ABORT_IF(error); vector<vector<string>> lines = reader.readAllLines(error); ISHIKO_TEST_FAIL_IF(error); ISHIKO_TEST_ABORT_IF_NEQ(lines.size(), 2); ISHIKO_TEST_ABORT_IF_NEQ(lines[0].size(), 2); ISHIKO_TEST_FAIL_IF_NEQ(lines[0][0], "Title 1"); ISHIKO_TEST_FAIL_IF_NEQ(lines[0][1], "Title 2"); ISHIKO_TEST_ABORT_IF_NEQ(lines[1].size(), 2); ISHIKO_TEST_FAIL_IF_NEQ(lines[1][0], "value1"); ISHIKO_TEST_FAIL_IF_NEQ(lines[1][1], "234"); ISHIKO_TEST_PASS(); } void CSVReaderTests::ForEachLineTest1(Test& test) { path inputPath(test.context().getTestDataPath("CSVReaderTests_ReadAllLinesTest2.csv")); Error error; CSVReader reader; reader.open(inputPath, error); ISHIKO_TEST_ABORT_IF(error); vector<vector<string>> lines; reader.forEachLine( [&lines](const vector<string>& line) { lines.push_back(line); }, error); ISHIKO_TEST_FAIL_IF(error); ISHIKO_TEST_ABORT_IF_NEQ(lines.size(), 2); ISHIKO_TEST_ABORT_IF_NEQ(lines[0].size(), 2); ISHIKO_TEST_FAIL_IF_NEQ(lines[0][0], "Title 1"); ISHIKO_TEST_FAIL_IF_NEQ(lines[0][1], "Title 2"); ISHIKO_TEST_ABORT_IF_NEQ(lines[1].size(), 2); ISHIKO_TEST_FAIL_IF_NEQ(lines[1][0], "value1"); ISHIKO_TEST_FAIL_IF_NEQ(lines[1][1], "234"); ISHIKO_TEST_PASS(); }
27.215
91
0.720007
[ "vector" ]
937b10e7540aa2e674d1d4642f9ffc9a91f277bc
3,535
cpp
C++
test/code/test_unicode.cpp
shaishasag/jsonland
171a4b3f08193487728b79b089f7cb48168f2380
[ "BSD-3-Clause" ]
null
null
null
test/code/test_unicode.cpp
shaishasag/jsonland
171a4b3f08193487728b79b089f7cb48168f2380
[ "BSD-3-Clause" ]
null
null
null
test/code/test_unicode.cpp
shaishasag/jsonland
171a4b3f08193487728b79b089f7cb48168f2380
[ "BSD-3-Clause" ]
null
null
null
#include "gtest/gtest.h" #include "rapidjson/error/en.h" #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include "nlohmann/json.hpp" #include "jsonland/json_node.h" using namespace jsonland; TEST(Unicode, compare_escape_parse) { const char* json_text = R"({"\uD83C\uDFE1": "house", "post-office" : "\uD83C\uDFE3", "anabanana":"\ud83c\udf4c\t\ud83c\udf4d"})"; rapidjson::Document document; document.Parse(json_text); if (document.IsObject()) { for (rapidjson::Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter){ std::cout << "Rapidjson: " << iter->name.GetString() << " => " << iter->value.GetString() << "\n"; } } nlohmann::json nj = nlohmann::json::parse(json_text); for (nlohmann::json::iterator it = nj.begin(); it != nj.end(); ++it) { std::cout << "Nlohmann: " << it.key() << " => " << it.value() << "\n"; } jsonland::json_doc landoc; int parse_error = landoc.parse(json_text); for (auto& node : landoc) { std::cout << "jsonland: " << node.key() << " => " << node.as_string() << "\n"; } } TEST(Unicode, compare_unescape_parse) { const char* json_text = R"({"🏡": "house", "post-office" : "🏣", "anabanana":"🍌🍍"})"; rapidjson::Document document; document.Parse(json_text); if (document.IsObject()) { for (rapidjson::Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter){ std::cout << "Rapidjson: " << iter->name.GetString() << " => " << iter->value.GetString() << "\n"; } } nlohmann::json nj = nlohmann::json::parse(json_text); for (nlohmann::json::iterator it = nj.begin(); it != nj.end(); ++it) { std::cout << "Nlohmann: " << it.key() << " => " << it.value() << "\n"; } jsonland::json_doc landoc; int parse_error = landoc.parse(json_text); std::cout << "jsonland: " << "house" << " => " << landoc["house"].as_string() << "\n"; std::cout << "jsonland: " << "post-office" << " => " << landoc["post-office"].as_string() << "\n"; } TEST(Unicode, compare_unescaped_initialization) { rapidjson::Document rapido(rapidjson::kObjectType); rapido.AddMember("🏡", "house", rapido.GetAllocator()); rapido.AddMember("post-office", "🏣", rapido.GetAllocator()); rapido.AddMember("Tab", "T'\t'b", rapido.GetAllocator()); rapido.AddMember("T'\t'b", "Tab", rapido.GetAllocator()); if (rapido.IsObject()) { for (rapidjson::Value::ConstMemberIterator iter = rapido.MemberBegin(); iter != rapido.MemberEnd(); ++iter){ std::cout << "Rapidjson: " << iter->name.GetString() << " => " << iter->value.GetString() << "\n"; } } std::cout << "---"; nlohmann::json nj = nlohmann::json::object(); nj["🏡"] = "house"; nj["post-office"] = "🏣"; nj["Tab"] = "T'\t'b"; nj["T'\t'b"] = "Tab"; for (nlohmann::json::iterator it = nj.begin(); it != nj.end(); ++it) { std::cout << "Nlohmann: " << it.key() << " => " << it.value() << "\n"; } std::cout << "---"; jsonland::json_doc landoc(jsonland::node_type::_object); landoc["🏡"] = "🏣"; landoc["🏡"] = "house"; landoc["post-office"] = "🏣"; landoc["Tab"] = "T'\t'b"; landoc["T'\t'b"] = "Tab"; for (auto& node : landoc) { std::cout << "jsonland: " << node.key() << " => " << node.as_string() << "\n"; } }
32.731481
133
0.553041
[ "object" ]
937f2ed71eaa245f1e9ca9c55aea678e69dda4a7
3,828
cpp
C++
src/vulkan-renderer/wrapper/cpu_texture.cpp
MyCatFishSteve/vulkan-renderer
c6a94738419ab4e3567f40ed83547f1216b1a22e
[ "MIT" ]
null
null
null
src/vulkan-renderer/wrapper/cpu_texture.cpp
MyCatFishSteve/vulkan-renderer
c6a94738419ab4e3567f40ed83547f1216b1a22e
[ "MIT" ]
null
null
null
src/vulkan-renderer/wrapper/cpu_texture.cpp
MyCatFishSteve/vulkan-renderer
c6a94738419ab4e3567f40ed83547f1216b1a22e
[ "MIT" ]
null
null
null
#include "inexor/vulkan-renderer/wrapper/cpu_texture.hpp" #define STB_IMAGE_IMPLEMENTATION #include <spdlog/spdlog.h> #include <stb_image.h> #include <array> #include <vector> namespace inexor::vulkan_renderer::wrapper { CpuTexture::CpuTexture() : m_name("default texture") { generate_error_texture_data(); } CpuTexture::CpuTexture(const std::string &file_name, std::string name) : m_name(std::move(name)) { assert(!file_name.empty()); assert(!m_name.empty()); spdlog::debug("Loading texture file {}.", file_name); // Load the texture file using stb_image library. // Force stb_image to load an alpha channel as well. m_texture_data = stbi_load(file_name.c_str(), &m_texture_width, &m_texture_height, nullptr, STBI_rgb_alpha); if (m_texture_data == nullptr) { spdlog::error("Could not load texture file {} using stbi_load! Falling back to error texture.", file_name); generate_error_texture_data(); } else { // TODO: We are currently hard coding the number of channels with STBI_rgb_alpha. // Eventually, we probably need to pass this information into this class from // a higher level class - like a material loader class. // So, as an example, if the material loader is loading a normal map, we know // we need to tell this class to load a 3 channel texture. If it can, great. // If it can not, then this class probably needs to load a 3 channel error texture. m_texture_channels = 4; // TODO: We are currently only supporting 1 mip level. m_mip_levels = 1; spdlog::debug("Texture dimensions: width: {}, height: {}, channels: {} mip levels: {}.", m_texture_width, m_texture_height, m_texture_channels, m_mip_levels); } } CpuTexture::CpuTexture(CpuTexture &&other) noexcept : m_name(std::move(other.m_name)), m_texture_width(other.m_texture_width), m_texture_height(other.m_texture_height), m_texture_channels(other.m_texture_channels), m_mip_levels(other.m_mip_levels), m_texture_data(other.m_texture_data) {} CpuTexture::~CpuTexture() { if (m_texture_data != nullptr) { spdlog::trace("Destroying cpu texture data {}.", m_name); // Discard the texture data. stbi_image_free(m_texture_data); } } void CpuTexture::generate_error_texture_data() { assert(m_texture_data == nullptr); m_texture_width = 512; m_texture_height = 512; m_texture_channels = 4; m_mip_levels = 1; // Create an 8x8 checkerboard pattern of squares. constexpr int SQUARE_DIMENSION{64}; // pink, purple constexpr std::array<std::array<unsigned char, 4>, 2> COLORS{{{0xFF, 0x69, 0xB4, 0xFF}, {0x94, 0x00, 0xD3, 0xFF}}}; const auto get_color = [](int x, int y, int square_dimension, std::size_t colors) -> int { return (std::size_t(x / square_dimension) + std::size_t(y / square_dimension)) % colors; }; // Note: Using the stb library function since we are freeing with stbi_image_free. m_texture_data = static_cast<stbi_uc *>(STBI_MALLOC(data_size())); // Performance could be improved by copying complete rows after one or two rows are created with the loops. for (int y = 0; y < m_texture_height; y++) { for (int x = 0; x < m_texture_width; x++) { const int index = (x + (y * m_texture_width)) * m_texture_channels; const int color_id = get_color(x, y, SQUARE_DIMENSION, COLORS.size()); m_texture_data[index + 0] = COLORS[color_id][0]; m_texture_data[index + 1] = COLORS[color_id][1]; m_texture_data[index + 2] = COLORS[color_id][2]; m_texture_data[index + 3] = COLORS[color_id][3]; } } } } // namespace inexor::vulkan_renderer::wrapper
39.875
120
0.668234
[ "vector" ]
938af27a821585fed17f8371319a00643f105f36
5,323
cpp
C++
core/helpers/Feeder/TCPFeeder/http.cpp
sears-s/fluffi
5f2f6d019041a6268199b69bf2f34487b18b84fe
[ "MIT" ]
96
2019-09-19T10:28:05.000Z
2022-02-28T11:53:06.000Z
core/helpers/Feeder/TCPFeeder/http.cpp
sears-s/fluffi
5f2f6d019041a6268199b69bf2f34487b18b84fe
[ "MIT" ]
123
2019-11-19T09:47:14.000Z
2021-10-19T03:10:51.000Z
core/helpers/Feeder/TCPFeeder/http.cpp
sears-s/fluffi
5f2f6d019041a6268199b69bf2f34487b18b84fe
[ "MIT" ]
23
2019-11-11T06:04:56.000Z
2022-02-11T15:35:26.000Z
/* Copyright 2017-2020 Siemens AG 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. Author(s): Abian Blome, Thomas Riedmaier, Pascal Eckmann */ #include "stdafx.h" #include "http.h" #include "utils.h" std::string getAuthToken() { return "implementme!"; } void performHTTPAuthAndManageSession(std::vector<char>* bytes) { std::cout << "TCPFeeder: called performHTTPAuthAndManageSession" << std::endl; if (bytes->size() == 0) { std::cout << "TCPFeeder: performHTTPAuthAndManageSession wont do anything, as an empty input was passed!" << std::endl; return; } //See if there is an Authorization token to replace std::string authorization = "Authorization: "; std::string fullrequest(bytes->begin(), bytes->begin() + bytes->size()); std::size_t authorizationStartPos = fullrequest.find(authorization); if (authorizationStartPos == std::string::npos) { std::cout << "TCPFeeder: performHTTPAuthAndManageSession could not find Authorization header (1)!" << std::endl; return; } authorizationStartPos += 15; std::size_t authorizationEndPos = fullrequest.find("\r\n", authorizationStartPos); if (authorizationEndPos == std::string::npos) { std::cout << "TCPFeeder: performHTTPAuthAndManageSession could not find Authorization header (2)!" << std::endl; return; } //Getting Authorization token std::string authToken = getAuthToken(); std::string fullrequestWithAuth = fullrequest.substr(0, authorizationStartPos) + authToken + fullrequest.substr(authorizationEndPos); bytes->clear(); std::copy(fullrequestWithAuth.c_str(), fullrequestWithAuth.c_str() + fullrequestWithAuth.length(), std::back_inserter(*bytes)); return; } void fixHTTPContentLength(std::vector<char>* bytes) { std::cout << "TCPFeeder: called fixHTTPContentLength" << std::endl; std::string contentLength = "Content-Length: "; std::string doubleLinebreak = "\r\n\r\n"; std::string singleLinebreak = "\r\n"; std::string fullrequest(bytes->begin(), bytes->begin() + bytes->size()); std::size_t contentLengthPos = fullrequest.find(contentLength); if (contentLengthPos == std::string::npos) { // not found std::cout << "TCPFeeder: fixHTTPContentLength not changing anything as the string \"Content-Length: \" was not found " << std::endl; return; } std::size_t doubleLinebreakPos = fullrequest.find(doubleLinebreak, contentLengthPos); if (doubleLinebreakPos == std::string::npos) { // not found std::cout << "TCPFeeder: fixHTTPContentLength not changing anything as the string \"\\r\\n\\r\\n\" was not found " << std::endl; return; } int realContentLength = static_cast<int>(fullrequest.length()) - static_cast<int>(doubleLinebreakPos) - 4; int specifiedContentLength = atoi(&fullrequest[contentLengthPos + 16]); if (realContentLength >= specifiedContentLength) { //do not change the value if the required amount of bytes is sent std::cout << "TCPFeeder: fixHTTPContentLength not changing anything as realContentLength >= specifiedContentLength " << std::endl; return; } //reduce the value, if not enough bytes are sent in order to avoid hangs (as the webserver will wait until the necessary amount of bytes are received) std::size_t singleLinebreakPos = fullrequest.find(singleLinebreak, contentLengthPos); //Overwrite the original value with spaces for (size_t i = contentLengthPos + 16; i < singleLinebreakPos; i++) { (*bytes)[i] = ' '; } //write the new value (it has less or equal digits as the old value, as it is smaller) WITHPUT A TRAILING NULL char buff[256]; int strlength = snprintf(buff, sizeof(buff), "%d", realContentLength); memcpy_s(&(*bytes)[contentLengthPos + 16], fullrequest.length() - (contentLengthPos + 16), buff, strlength); std::cout << "TCPFeeder: fixHTTPContentLength fixed the content length to :" << realContentLength << std::endl; return; } void dropNoDoubleLinebreak(std::vector<char>* bytes) { std::string doubleLinebreak = "\r\n\r\n"; std::string fullrequest(bytes->begin(), bytes->begin() + bytes->size()); std::size_t doubleLinebreakPos = fullrequest.find(doubleLinebreak); if (doubleLinebreakPos == std::string::npos) { // not found std::cout << "TCPFeeder: dropNoDoubleLinebreak dropping the request as the string \"\\r\\n\\r\\n\" was not found " << std::endl; bytes->clear(); return; } //do nothing if we have a double linebreak return; }
38.854015
151
0.739808
[ "vector" ]
938d3fdc518d640a44ae0e80aceb365bf66ef2f4
2,129
cpp
C++
gwen/src/Gwen/Controls/MenuStrip.cpp
CristianoBeato/SDLGwen
c2440f256d87c472f8e1b7b3d680521b2c0c0837
[ "MIT" ]
1
2019-02-18T09:11:10.000Z
2019-02-18T09:11:10.000Z
gwen/src/Gwen/Controls/MenuStrip.cpp
CristianoBeato/SDLGwen
c2440f256d87c472f8e1b7b3d680521b2c0c0837
[ "MIT" ]
null
null
null
gwen/src/Gwen/Controls/MenuStrip.cpp
CristianoBeato/SDLGwen
c2440f256d87c472f8e1b7b3d680521b2c0c0837
[ "MIT" ]
null
null
null
/* =========================================================================== GWEN Copyright (c) 2010 Facepunch Studios Copyright (c) 2017-2018 Cristiano Beato 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. =========================================================================== */ #include "precompiled.h" #pragma hdrstop #include "Gwen/Gwen.h" #include "Gwen/Controls/MenuStrip.h" using namespace Gwen; using namespace Gwen::Controls; GWEN_CONTROL_CONSTRUCTOR( MenuStrip ) { SetBounds( 0, 0, 200, 22 ); Dock( Pos::Top ); m_InnerPanel->SetPadding( Padding( 5, 0, 0, 0 ) ); } void MenuStrip::Render( Skin::Base* skin ) { skin->DrawMenuStrip( this ); } void MenuStrip::Layout( Skin::Base* /*skin*/ ) { //TODO: We don't want to do vertical sizing the same as Menu, do nothing for now } void MenuStrip::OnAddItem( MenuItem* item ) { item->Dock( Pos::Left ); item->SetTextPadding( Padding( 5, 0, 5, 0 ) ); item->SetPadding( Padding( 10, 0, 10, 0 ) ); item->SizeToContents(); item->SetOnStrip( true ); item->onHoverEnter.Add( this, &Menu::OnHoverItem ); } bool MenuStrip::ShouldHoverOpenMenu() { return IsMenuOpen(); }
30.855072
81
0.697511
[ "render" ]
938d96f8c119ec38c06431593aa693dfda7022b3
3,455
cpp
C++
src/unit_test/sai_infra_unit_test.cpp
Dell-Networking/sonic-sai-common
0ad86ab7f29732d318013e55fe11e7197c7c1246
[ "Apache-2.0" ]
1
2020-07-30T02:53:02.000Z
2020-07-30T02:53:02.000Z
src/unit_test/sai_infra_unit_test.cpp
Dell-Networking/sonic-sai-common
0ad86ab7f29732d318013e55fe11e7197c7c1246
[ "Apache-2.0" ]
null
null
null
src/unit_test/sai_infra_unit_test.cpp
Dell-Networking/sonic-sai-common
0ad86ab7f29732d318013e55fe11e7197c7c1246
[ "Apache-2.0" ]
4
2016-08-12T19:06:03.000Z
2020-07-30T02:53:04.000Z
/* * filename: std_cfg_file_gtest.cpp * (c) Copyright 2014 Dell Inc. All Rights Reserved. */ /* * sai_infra_unit_test.cpp * */ #include <unistd.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "gtest/gtest.h" extern "C" { #include "sai.h" #include "sai_infra_api.h" } #include <iostream> #include <map> typedef std::map<std::string, std::string> sai_kv_pair_t; typedef std::map<std::string, std::string>::iterator kv_iter; static sai_kv_pair_t kvpair; const char* profile_get_value(sai_switch_profile_id_t profile_id, const char* variable) { kv_iter kviter; std::string key; if (variable == NULL) return NULL; key = variable; kviter = kvpair.find(key); if (kviter == kvpair.end()) { return NULL; } return kviter->second.c_str(); } int profile_get_next_value(sai_switch_profile_id_t profile_id, const char** variable, const char** value) { kv_iter kviter; std::string key; if (variable == NULL || value == NULL) { return -1; } if (*variable == NULL) { if (kvpair.size() < 1) { return -1; } kviter = kvpair.begin(); } else { key = *variable; kviter = kvpair.find(key); if (kviter == kvpair.end()) { return -1; } kviter++; if (kviter == kvpair.end()) { return -1; } } *variable = (char *)kviter->first.c_str(); *value = (char *)kviter->second.c_str(); return 0; } void kv_populate(void) { kvpair["SAI_FDB_TABLE_SIZE"] = "16384"; kvpair["SAI_L3_ROUTE_TABLE_SIZE"] = "8192"; kvpair["SAI_NUM_CPU_QUEUES"] = "43"; kvpair["SAI_INIT_CONFIG_FILE"] = "/etc/sonic/init.xml"; kvpair["SAI_NUM_ECMP_MEMBERS"] = "64"; } /* * Pass the service method table and do API intialize. */ TEST(sai_unit_test, api_init) { service_method_table_t sai_service_method_table; kv_populate(); sai_service_method_table.profile_get_value = profile_get_value; sai_service_method_table.profile_get_next_value = profile_get_next_value; ASSERT_EQ(SAI_STATUS_SUCCESS,sai_api_initialize(0, &sai_service_method_table)); } /* *Obtain the method table for the sai switch api. */ TEST(sai_unit_test, api_query) { sai_switch_api_t *sai_switch_api_table = NULL; ASSERT_EQ(NULL,sai_api_query(SAI_API_SWITCH, (static_cast<void**>(static_cast<void*>(&sai_switch_api_table))))); EXPECT_TRUE(sai_switch_api_table->initialize_switch != NULL); EXPECT_TRUE(sai_switch_api_table->shutdown_switch != NULL); EXPECT_TRUE(sai_switch_api_table->connect_switch != NULL); EXPECT_TRUE(sai_switch_api_table->disconnect_switch != NULL); EXPECT_TRUE(sai_switch_api_table->set_switch_attribute != NULL); EXPECT_TRUE(sai_switch_api_table->get_switch_attribute != NULL); } /* *Verify if object_type_query returns OBJECT_TYPE_NULL for invalid object id. */ TEST(sai_unit_test, sai_object_type_query) { sai_object_id_t invalid_obj_id = 0; ASSERT_EQ(SAI_OBJECT_TYPE_NULL,sai_object_type_query(invalid_obj_id)); } /* * Unintialize the SDK and free up the resources. */ TEST(sai_unit_test, api_uninit) { ASSERT_EQ(SAI_STATUS_SUCCESS,sai_api_uninitialize()); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
23.827586
83
0.657887
[ "object" ]
938e686972147b25f2cd98d920a0a65ecc5510df
7,236
cpp
C++
OpenGL-Core/src/GLCore/Util/Trackball.cpp
visioner3d/OpenGL3D
80f58fb1204d2ad3c78476558c3cf9766311a5e5
[ "Apache-2.0" ]
null
null
null
OpenGL-Core/src/GLCore/Util/Trackball.cpp
visioner3d/OpenGL3D
80f58fb1204d2ad3c78476558c3cf9766311a5e5
[ "Apache-2.0" ]
null
null
null
OpenGL-Core/src/GLCore/Util/Trackball.cpp
visioner3d/OpenGL3D
80f58fb1204d2ad3c78476558c3cf9766311a5e5
[ "Apache-2.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // Trackball.cpp // ============= // Trackball class // This class takes the current mouse cursor position (x,y), and map it to the // point (x,y,z) on the trackball(sphere) surface. Since the cursor point is in // screen space, this class depends on the current screen width and height in // order to compute the vector on the sphere. // // There are 2 modes (Arc and Project) to compute the vector on the sphere: Arc // mode is that the length of the mouse position from the centre of screen // becomes arc length moving on the sphere, and Project mode is that directly // projects the mouse position to the sphere. // // The default mode is Arc because it allows negative z-value (a point on the // back of the sphere). On the other hand, Project mode is limited to // front hemisphere rotation (z-value is always positive). // // AUTHOR: Song Ho Ahn (song.ahn@gmail.com) // CREATED: 2011-12-09 // UPDATED: 2016-04-01 // // Copyright (C) 2011. Song Ho Ahn /////////////////////////////////////////////////////////////////////////////// #include "glpch.h" #include "Trackball.h" #include <iostream> namespace GLCore::Utils { /////////////////////////////////////////////////////////////////////////////// // ctor /////////////////////////////////////////////////////////////////////////////// Trackball::Trackball() : radius(0), screenWidth(0), screenHeight(0), halfScreenWidth(0), halfScreenHeight(0), mode(Trackball::ARC) { } Trackball::Trackball(float radius, int width, int height) : radius(radius), screenWidth(width), screenHeight(height), mode(Trackball::ARC) { halfScreenWidth = width * 0.5f; halfScreenHeight = height * 0.5f; } /////////////////////////////////////////////////////////////////////////////// // dtor /////////////////////////////////////////////////////////////////////////////// Trackball::~Trackball() { } /////////////////////////////////////////////////////////////////////////////// // print itself /////////////////////////////////////////////////////////////////////////////// void Trackball::printSelf() const { std::cout << "===== Trackball =====\n" << " Radius: " << radius << "\n" << "Screen Size: (" << screenWidth << ", " << screenHeight << ")\n" << " Mode: " << (mode == ARC ? "ARC\n" : "PROJECT\n") << std::endl; } /////////////////////////////////////////////////////////////////////////////// // setters /////////////////////////////////////////////////////////////////////////////// void Trackball::set(float r, int w, int h) { radius = r; screenWidth = w; screenHeight = h; halfScreenWidth = w * 0.5f; halfScreenHeight = h * 0.5f; } void Trackball::setScreenSize(int w, int h) { screenWidth = w; screenHeight = h; halfScreenWidth = w * 0.5f; halfScreenHeight = h * 0.5f; } /////////////////////////////////////////////////////////////////////////////// // clamp x and y // the params of getVector() must be inside the window: -half < (x,y) < +half /////////////////////////////////////////////////////////////////////////////// float Trackball::clampX(float x) const { if (x <= -halfScreenWidth) x = -halfScreenWidth + 1; else if (x >= halfScreenWidth) x = halfScreenWidth - 1; return x; } float Trackball::clampY(float y) const { if (y <= -halfScreenHeight) y = -halfScreenHeight + 1; else if (y >= halfScreenHeight) y = halfScreenHeight - 1; return y; } /////////////////////////////////////////////////////////////////////////////// // return the point corrds on the sphere /////////////////////////////////////////////////////////////////////////////// glm::vec3 Trackball::getVector(int x, int y) const { if (radius == 0 || screenWidth == 0 || screenHeight == 0) return glm::vec3(0, 0, 0); // compute mouse position from the centre of screen (-half ~ +half) //float mx = x - halfScreenWidth; //float my = halfScreenHeight - y; // OpenGL uses bottom to up orientation float mx = clampX(x - halfScreenWidth); float my = clampY(halfScreenHeight - y); // OpenGL uses bottom to up orientation if (mode == Trackball::PROJECT) return getVectorWithProject(mx, my); else return getVectorWithArc(mx, my); // default mode } /////////////////////////////////////////////////////////////////////////////// // return the point on the sphere as a unit vector /////////////////////////////////////////////////////////////////////////////// glm::vec3 Trackball::getUnitVector(int x, int y) const { glm::vec3 vec = getVector(x, y); vec = glm::normalize(vec); return vec; } /////////////////////////////////////////////////////////////////////////////// // use the mouse distance from the centre of screen as arc length on the sphere // x = R * sin(a) * cos(b) // y = R * sin(a) * sin(b) // z = R * cos(a) // where a = angle on x-z plane, b = angle on x-y plane // // NOTE: the calculation of arc length is an estimation using linear distance // from screen center (0,0) to the cursor position /////////////////////////////////////////////////////////////////////////////// glm::vec3 Trackball::getVectorWithArc(float x, float y) const { float arc = sqrtf(x*x + y * y); // legnth between cursor and screen center float a = arc / radius; // arc = r * a float b = atan2f(y, x); // angle on x-y plane float x2 = radius * sinf(a); // x rotated by "a" on x-z plane glm::vec3 vec; vec.x = x2 * cosf(b); vec.y = x2 * sinf(b); vec.z = radius * cosf(a); return vec; } /////////////////////////////////////////////////////////////////////////////// // project the mouse coords to the sphere to find the point coord // return the point on the sphere using hyperbola where x^2 + y^2 > r^2/2 /////////////////////////////////////////////////////////////////////////////// glm::vec3 Trackball::getVectorWithProject(float x, float y) const { /* glm::vec3 vec = glm::vec3(x, y, 0); float d = x*x + y*y; float rr = radius * radius; if(d <= rr) { vec.z = sqrtf(rr - d); } else { vec.z = 0; // put (x,y) on the sphere radius vec.normalize(); vec *= radius; } return vec; */ glm::vec3 vec = glm::vec3(x, y, 0); float d = x * x + y * y; float rr = radius * radius; // use sphere if d<=0.5*r^2: z = sqrt(r^2 - (x^2 + y^2)) if (d <= (0.5f * rr)) { vec.z = sqrtf(rr - d); } // use hyperbolic sheet if d>0.5*r^2: z = (r^2 / 2) / sqrt(x^2 + y^2) // referenced from trackball.c by Gavin Bell at SGI else { // compute z first using hyperbola vec.z = 0.5f * rr / sqrtf(d); // scale x and y down, so the vector can be on the sphere // y = ax => x^2 + (ax)^2 + z^2 = r^2 => (1 + a^2)*x^2 = r^2 - z^2 // => x = sqrt((r^2 - z^2) / (1 - a^2) float x2, y2, a; if (x == 0.0f) // avoid dividing by 0 { x2 = 0.0f; y2 = sqrtf(rr - vec.z*vec.z); if (y < 0) // correct sign y2 = -y2; } else { a = y / x; x2 = sqrtf((rr - vec.z*vec.z) / (1 + a * a)); if (x < 0) // correct sign x2 = -x2; y2 = a * x2; } vec.x = x2; vec.y = y2; } return vec; } }
29.534694
85
0.470149
[ "vector" ]
9396689da8fefcc075bbb7b84a4d9bd5b8ed9e81
11,705
cpp
C++
source/menus/submenu/allocation_distribution_menu.cpp
BeenEncoded/Budget_Management_Program
8b9b63695c5dc03c681843af472d5f9a53b36c87
[ "MIT" ]
null
null
null
source/menus/submenu/allocation_distribution_menu.cpp
BeenEncoded/Budget_Management_Program
8b9b63695c5dc03c681843af472d5f9a53b36c87
[ "MIT" ]
null
null
null
source/menus/submenu/allocation_distribution_menu.cpp
BeenEncoded/Budget_Management_Program
8b9b63695c5dc03c681843af472d5f9a53b36c87
[ "MIT" ]
null
null
null
#include <vector> #include <utility> #include <string> #include <sstream> #include <iostream> #include "allocation_distribution_menu.hpp" #include "data/budget_data.hpp" #include "utility/scroll_display.hpp" #include "common/common.hpp" #include "utility/user_input.hpp" namespace { template<typename type1, typename type2> inline type2 conv(const type1& t) { type2 t2; std::stringstream ss; ss<< t; ss>> t2; return t2; } } namespace { void create_alloc_display(const std::vector<data::money_alloc_data>&, std::vector<std::string>&); std::string allocation_display(const data::money_alloc_data&); data::distribution_data::percent_t percent_left(const data::budget_data&); void access_alloc_money(data::money_alloc_data&, data::money_t*&); bool access_alloc_percentage(data::money_alloc_data&, unsigned int&); bool get_user_percent(data::distribution_data::percent_t&); /** * @brief Constructs a string to display a single allocation for a * window_data_class. This displays percent alongside the alloc name. * @param alloc the allocation. * @return a string. */ inline std::string allocation_display(const data::money_alloc_data& alloc) { using common::fit_str; constexpr unsigned int name_size{20}; std::string temps{(fit_str(alloc.name, name_size) + std::string((name_size - fit_str(alloc.name, name_size).size()), ' '))}; if(alloc.meta_data != nullptr) { if(alloc.meta_data->dist_data.enabled) { temps += ("%" + std::to_string(alloc.meta_data->dist_data.percent_value)); } else { temps += "[DISABLED]"; } } else { temps += "[nullptr]"; } return temps; } /** * @brief Creates a display for scrollDisplay::window_data_class<data::money_alloc_data> * with name and percentage. */ inline void create_alloc_display(const std::vector<data::money_alloc_data>& allocs, std::vector<std::string>& disp) { disp.erase(disp.begin(), disp.end()); for(std::vector<data::money_alloc_data>::const_iterator it{allocs.begin()}; it != allocs.end(); ++it) { disp.push_back(std::move(allocation_display(*it))); } } /** * @brief Returns the remaining percentage that can be assigned in the budget. */ inline data::distribution_data::percent_t percent_left(const data::budget_data& b) { data::money_t money{0}; for(std::vector<data::money_alloc_data>::const_iterator it{b.allocs.begin()}; it != b.allocs.end(); ++it) { if(it->meta_data->dist_data.enabled) { money += ((b.total_money / 100) * it->meta_data->dist_data.percent_value); } else { money += it->value; } } return (100 - (data::distribution_data::percent_t)(((long double)money / b.total_money) * (long double)100)); } /** * @brief This function is used in the distribution algorithm and modifies * its second argument so that it points to a.value. */ inline void access_alloc_money(data::money_alloc_data& a, data::money_t*& m) { m = (&(a.value)); } /** * @brief This function is used in the percentage distribution algorithm and * modifies its second argument to equal that of a.meta_data->dist_data.percent_value * if (a.meta_data != nullptr). * @return True if the data::alloc_statistics_data is not null and distribution * is enabled for the allocation. */ inline bool access_alloc_percentage(data::money_alloc_data& a, unsigned int& perc) { perc = 0; if(a.meta_data != nullptr) { perc = a.meta_data->dist_data.percent_value; return a.meta_data->dist_data.enabled; } return false; } /** * @brief Allows he user to input a percentage. * @param perc The number to store the input into. * @return true if the user entered a valid number for a percentage. */ inline bool get_user_percent(data::distribution_data::percent_t& perc) { bool valid{false}, pressed_enter{false}; std::string temps{std::move(std::to_string(perc))}; do { pressed_enter = common::get_user_str(temps); valid = (common::str_is_num(temps) && (conv<std::string, data::distribution_data::percent_t>(temps) <= 100) && (conv<std::string, data::distribution_data::percent_t>(temps) >= (-100))); }while(!valid && pressed_enter); if(pressed_enter && valid) perc = conv<std::string, data::distribution_data::percent_t>(temps); return (pressed_enter && valid); } } namespace submenu { /** * @brief Allows the user to distribute money in a budget based on user-defined * percentages given to each allocation. * @param b The budget. * @return true if the user modified and did not cancel. */ bool distribute_by_percent(data::budget_data& b) { using scrollDisplay::window_data_class; using scrollDisplay::display_window; using std::cout; using std::endl; using keyboard::key_code_data; if(b.allocs.empty()) return false; /* When we initialize window_data_class, the display creation function is called * (in this case, create_alloc_display). create_alloc_display references * alloc_statistics_data in the budget, so that needs to be initialized: */ data::generate_meta_data(b); window_data_class<data::money_alloc_data> display{b.allocs, create_alloc_display}; bool finished{false}, canceled{false}, modified{false}; key_code_data key; display.win().window_size() = 6; user_input::cl(); do { common::cls(); cout<< endl; common::center("Distribution by Percentage:"); for(unsigned int x{0}; x < 2; ++x) cout<< endl; display_window(display); cout<< endl<< endl; cout<< "Percentage left: %"<< percent_left(b)<< endl<< endl<< endl; cout<< " [ENTER] - Set percentage"<< endl; cout<< " [TAB] - Toggle inclusion"<< endl; cout<< endl; cout<< " [SPCE] - Distribute"<< endl; cout<< " [BCKSPCE] - Cancel"<< endl; key = std::move(user_input::getch_funct()); if(keyboard::is_listed_control(key)) { using keyboard::keys; using namespace keyboard::code; if(key == keys[up::value]) display.win().mv_up(); else if(key == keys[down::value]) display.win().mv_down(); else if(key == keys[home::value]) while(display.win().mv_up()); else if(key == keys[end::value]) while(display.win().mv_down()); else if(key == keys[backspace::value]) { if(common::prompt_user("Are you sure you want to cancel percentage distribution?")) { canceled = true; finished = true; } } } else if(!key.control_d.empty()) { switch(std::tolower((char)key.control_d[0])) { case '\n': { common::cls(); for(unsigned int x{0}; x < 11; ++x) cout<< endl; cout<< "Enter a percentage for \""<< display.selected().name<< "\": %"; cout.flush(); if(get_user_percent(display.selected().meta_data->dist_data.percent_value)) modified = true; } break; case '\t': { if(display.selected().meta_data != nullptr) { display.selected().meta_data->dist_data.enabled = !display.selected().meta_data->dist_data.enabled; } } break; case ' ': { if(common::prompt_user("Are you sure this is how you want to distribute your money?")) { modified = true; common::distribute_by_percent(b.total_money, b.allocs, access_alloc_money, access_alloc_percentage); finished = true; } } break; default: { } break; } } }while(!finished); return (modified && !canceled); } /** * @brief Allows the user to choose a method of distribution. * @param b The budget. * @return true if the budget eas modified. */ bool distribution_selection(data::budget_data& b) { using keyboard::key_code_data; using std::cout; using std::endl; if(b.allocs.empty()) { common::cls(); for(unsigned int x{0}; x < v_center::value; ++x) cout<< endl; common::center("There are no allocations!"); common::wait(); common::cls(); return false; } bool finished{false}, modified{false}; key_code_data key; user_input::cl(); do { common::cls(); cout<< endl; common::center("Choose Distribution type: "); for(unsigned int x{0}; x < 4; ++x) cout<< endl; cout<< " 1 - By percent"<< endl; cout<< " 2 - Equally"<< endl; cout<< endl; cout<< " c - Cancel"<< endl; key = std::move(user_input::getch_funct()); if(!keyboard::is_listed_control(key)) { if(!key.control_d.empty()) { switch(std::tolower((char)key.control_d[0])) { case '1': { finished = true; modified = distribute_by_percent(b); } break; case '2': { finished = true; common::distribute_equally(b.total_money, b.allocs, access_alloc_money); modified = true; } break; case 'c': { finished = true; } break; default: { } break; } } } }while(!finished); return modified; } }
34.528024
128
0.494319
[ "vector" ]
9398116c9080c3ccbad7617fdf2197ba413ee473
20,475
cpp
C++
scripts/training/MGIZA/src/model3_viterbi.cpp
noisychannel/joshua
cabf0a30b717ade61a3b8e2d2d65b0cb61f7cf36
[ "BSD-2-Clause" ]
null
null
null
scripts/training/MGIZA/src/model3_viterbi.cpp
noisychannel/joshua
cabf0a30b717ade61a3b8e2d2d65b0cb61f7cf36
[ "BSD-2-Clause" ]
null
null
null
scripts/training/MGIZA/src/model3_viterbi.cpp
noisychannel/joshua
cabf0a30b717ade61a3b8e2d2d65b0cb61f7cf36
[ "BSD-2-Clause" ]
null
null
null
/* EGYPT Toolkit for Statistical Machine Translation Written by Yaser Al-Onaizan, Jan Curin, Michael Jahr, Kevin Knight, John Lafferty, Dan Melamed, David Purdy, Franz Och, Noah Smith, and David Yarowsky. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "model3.h" #include "utility.h" #include "Globals.h" #include "AlignTables.h" #ifdef WIN32 typedef hash_map<Vector<WordIndex>, LogProb, hashmyalignment > alignment_hash; #else typedef hash_map<Vector<WordIndex>, LogProb, hashmyalignment, equal_to_myalignment > alignment_hash; #endif LogProb model3::prob_of_target_and_alignment_given_source(Vector<WordIndex>& A, Vector<WordIndex>& Fert, tmodel<COUNT, PROB>& tTable, Vector<WordIndex>& fs, Vector<WordIndex>& es) { LogProb total = 1.0; LogProb temp = 0.0; const LogProb zero = 0.0; WordIndex l = es.size()-1, m = fs.size()-1; WordIndex i, j; total *= pow(double(1-p1), m-2.0 * Fert[0]) * pow(double(p1), double(Fert[0])); if (total == 0) return (zero); for (i = 1; i <= Fert[0]; i++) { // loop caculates m-fert[0] choose fert[0] total *= double(m - Fert[0] - i + 1) / i; if (total == 0) return (zero); } for (i = 1; i <= l; i++) { // this loop calculates fertilities term total *= double(nTable.getValue(es[i], Fert[i])) * (LogProb) factorial(Fert[i]); if (total == 0) return (zero); } for (j = 1; j <= m; j++) { // temp = tTable.getValue(es[A[j]], fs[j]) ; temp = double(tTable.getProb(es[A[j]], fs[j])); total *= temp; if (0 != A[j]) total *= double(dTable.getValue(j, A[j], l, m)); if (total == 0) return (zero); } return (total); } LogProb model3::prob_of_target_given_source(tmodel<COUNT, PROB>& tTable, Vector<WordIndex>& fs, Vector<WordIndex>& es) { WordIndex x, y; LogProb total = 0; // WordIndex l = es.size(), m = fs.size(); WordIndex l = es.size()-1, m = fs.size()-1; Vector<WordIndex> A(fs.size(),/*-1*/0); Vector<WordIndex> Fert(es.size(),0); WordIndex i, j; for (x = 0; x < pow(l+1.0, double(m)) ; x++) { // For all possible alignmets A y = x; // for (j = 1 ; j < m ; j++){ for (j = 1; j <= m; j++) { A[j] = y % (l+1); y /= (l+1); } // for(i = 0 ; i < l ; i++) for (i = 0; i <= l; i++) Fert[i] = 0; // for (j = 1 ; j < m ; j++) for (j = 1; j <= m; j++) Fert[A[j]]++; // if (2 * Fert[0] < m){ if (2 * Fert[0] <= m) { /* consider alignments that has Fert[0] less than half the length of french sentence */ total += prob_of_target_and_alignment_given_source(A, Fert, tTable, fs, es); } } return (total); } LogProb model3::scoreOfMove(Vector<WordIndex>& es, Vector<WordIndex>& fs, Vector<WordIndex>& A, Vector<WordIndex>& Fert, tmodel<COUNT, PROB>& tTable, WordIndex j, WordIndex i) // returns the scaling factor of the original score if A[j] is linked to // i, no change is really made to A // but the score is calculated if the move is to be taken (i.e. // no side effects on Alignment A nor its Fertility Fert // If the value of the scaling factor is: // 1: then the score of the new alignment if the move is taken will // not change. // 0.5: the new score is half the score of the original alignment. // 2.0: the new score will be twice as much. // { // LogProb score; LogProb change; WordIndex m, l; m = fs.size() - 1; l = es.size() - 1; if (A[j] == i) // return(original_score); return (1); else if (A[j] == 0) { // a move from position zero to something else change = double(p0*p0)/p1 * (double((Fert[0]*(m-Fert[0]+1))) / ((m-2*Fert[0]+1)*(m-2*Fert[0] +2))) * (Fert[i]+1) * double(nTable.getValue(es[i], Fert[i]+1)) / double(nTable.getValue(es[i], Fert[i])) * double(tTable.getProb(es[i], fs[j])) / double(tTable.getProb(es[A[j]], fs[j])) * double(dTable.getValue(j, i, l, m)); } else if (i == 0) { // a move to position zero change= ((double(p1) / (p0*p0)) * (double((m-2*Fert[0])*(m-2*Fert[0]-1))/((Fert[0]+1)*(m-Fert[0]))) * (double(1)/Fert[A[j]]) * double(nTable.getValue(es[A[j]], Fert[A[j]]-1)) / double(nTable.getValue(es[A[j]], Fert[A[j]]))* double(tTable.getProb(es[i], fs[j])) / double(tTable.getProb(es[A[j]], fs[j])) * 1.0 / double(dTable.getValue(j, A[j], l, m))); } else { // a move that does not involve position zero change = ((double(Fert[i]+1)/Fert[A[j]]) * double(nTable.getValue(es[A[j]], Fert[A[j]]-1)) / double(nTable.getValue(es[A[j]], Fert[A[j]])) * double(nTable.getValue(es[i], Fert[i]+1)) / double(nTable.getValue(es[i], Fert[i])) * double(tTable.getProb(es[i], fs[j]))/ double(tTable.getProb(es[A[j]], fs[j])) * double(dTable.getValue(j, i, l, m))/ double(dTable.getValue(j, A[j], l, m))); } return (change); } LogProb model3::scoreOfSwap(Vector<WordIndex>& es, Vector<WordIndex>& fs, Vector<WordIndex>& A, tmodel<COUNT, PROB>& tTable, int j1, int j2) // returns the scaling factor of the original score if the swap to // take place, // No side effects here (none of the parameters passed is changed! // (i.e. the alignment A is not really changed) // If the value of the scaling factor is: // 1: then the score of the new alignment if the move is taken will // not change. // 0.5: the new score is half the score of the original alignment. // 2.0: the new score will be twice as much. // { LogProb score; WordIndex i1, i2, m, l; m = fs.size() - 1; l = es.size() - 1; if (j1 == j2 || A[j1] == A[j2]) // if swapping same position return ratio 1 return (1); else { i1 = A[j1]; i2 = A[j2]; score = double(tTable.getProb(es[i2], fs[j1]))/double(tTable.getProb(es[i1], fs[j1])) * double(tTable.getProb(es[i1], fs[j2]))/double(tTable.getProb(es[i2], fs[j2])); if (i1 != 0) { score *= double(dTable.getValue(j2, i1, l, m))/double(dTable.getValue(j1, i1, l, m)); } if (i2 != 0) { score *= double(dTable.getValue(j1, i2, l, m))/double(dTable.getValue(j2, i2, l, m)); } return (score); } } void model3::hillClimb(Vector<WordIndex>& es, Vector<WordIndex>& fs, Vector<WordIndex>& A, Vector<WordIndex>& Fert, LogProb& best_score, tmodel<COUNT, PROB>& tTable, int = -1, int j_peg = -1) // Hill climbing given alignment A . // Alignment A will be updated and also best_score // if no pegging is needed i_peg == -1, and j_peg == -1 { WordIndex i, j, l, m, j1, old_i; LogProb change; bool local_minima; int level = 0; LogProb best_change_so_far, best_change; Vector<WordIndex> A_so_far; Vector<WordIndex> Fert_so_far; l = es.size() - 1; m = fs.size() - 1; best_change = 1; // overall scaling factor (i.e. from the begining of climb do { best_change_so_far = 1; // best scaling factor of this level of hill climb local_minima = true; for (j = 1; j <= m; j++) { if (int(j) != j_peg) { // make sure not to change the pegged link for (j1 = j + 1; j1 <= m; j1++) { // for all possible swaps // make sure you are not swapping at same position if ((A[j] != A[j1]) && (int(j1) != j_peg)) { // change = scoreOfSwap(es, fs, A, best_score, tTable, j, j1); change = scoreOfSwap(es, fs, A, tTable, j, j1); if (change > best_change_so_far) { // if better alignment found, keep it local_minima = false; best_change_so_far = change; A_so_far = A; Fert_so_far = Fert; old_i = A_so_far[j]; A_so_far[j] = A_so_far[j1]; A_so_far[j1] = old_i; } // end of if (change > best_change_so_far) } // end of if (A[j] != A[j1] ..) } // of for (j1 = j+1 ....) // for (i = 0 ; i < l ; i++){ // all possible moves for (i = 0; i <= l; i++) { // all possible moves if (i != A[j]) { // make sure not to move to same position if (i != 0 || (m >= 2 * (Fert[0]+1))) { // if moving to NULL word // (pos 0), make sure not to violate the fertility restriction // i.e. NULL can not take more than half the target words // change = scoreOfMove(es, fs, A, Fert, best_score, tTable, j, i); change = scoreOfMove(es, fs, A, Fert, tTable, j, i); if (change > best_change_so_far) { // if better alignment found, keep it best_change_so_far = change; local_minima = false; A_so_far = A; Fert_so_far = Fert; old_i = A_so_far[j]; A_so_far[j] = i; Fert_so_far[old_i]--; Fert_so_far[i]++; } // end of if (change > best_change_so_far) } // end of if ((i!=0) ... } // end of if (i != A[j] ) } // end of for (i = 0 ; ....) } // end of if(j != j_peg) } // end of for (j = 1 ; ...) level++; if (!local_minima) { if (best_change_so_far > 1) { // if current chage is improving A = A_so_far; Fert = Fert_so_far; best_change *= best_change_so_far; } else { local_minima = true; } } // end of if(!local_minima) if (level> 15) cerr << "."; } while (local_minima == false); if (level > 15) cerr << "\nHill Climb Level: " << level << " score: scaling old: " <<(best_score*best_change); best_score = prob_of_target_and_alignment_given_source(A, Fert, tTable, fs, es); if (level>15) cerr << " using new calc: " << best_score << '\n'; } void model3::findBestAlignment(Vector<WordIndex>& es, Vector<WordIndex>& fs, Vector<WordIndex>& A, Vector<WordIndex>& Fert, LogProb& best_score, /*tmodel<COUNT, PROB>& tTable, amodel<PROB>& aTable, */ int i_peg = -1, int j_peg = -1) // This finds the best Model2 alignment (i.e. no fertilities stuff) in A // for the given sentence pair. Its score is returned in A. Its fertility // info in Fert. // if j_peg == -1 && i_peg == -1 then No pegging is performed. { WordIndex i, j, l, m, best_i=0; LogProb temp, score, ss; l = es.size() - 1; m = fs.size() - 1; for (i=0; i <= l; i++) Fert[i] = 0; ss = 1; if ((j_peg != -1) && (i_peg != -1)) { // if you're doing pegging A[j_peg] = i_peg; Fert[i_peg] = 1; ss *= double(tTable.getProb(es[i_peg], fs[j_peg])) * double(aTable.getValue(i_peg, j_peg, l, m)); } for (j = 1; j <= m; j++) { if (int(j) != j_peg) { score = 0; for (i = 0; i <= l; i++) { // first make sure that connecting target word at pos j to source word // at pos i will not lead to a violation on Fertility restrictions // (e.g. maximum fertility for a word, max fertility for NULL word, etc) if ((Fert[i]+1 < MAX_FERTILITY) && ((i == 0 && (m >= 2*(Fert[0] +1))) || (i != 0))) { temp = double(tTable.getProb(es[i], fs[j])) * double(aTable.getValue(i, j, l, m)); if (temp > score) { best_i = i; score = temp; } // end of if (temp > score) } // end of if (((i == 0 ...) } // end of for (i= 0 ...) if (score == 0) { cerr << "WARNING: In searching for model2 best alignment\n "; cerr << "Nothing was set for target token " << fs[j] << "at position j: " << j << "\n"; for (i = 0; i <= l; i++) { cerr << "i: " << i << "ttable("<<es[i]<<", "<<fs[j]<<") = " << tTable.getProb(es[i], fs[j]) << " atable(" << i <<", "<<j<<", "<< l<<", "<<m<<") = " << aTable.getValue(i, j, l, m) << " product " << double(tTable.getProb(es[i], fs[j])) * double(aTable.getValue(i, j, l, m)) << '\n'; if ((Fert[i]+1 < MAX_FERTILITY) && ((i == 0 && (m >= 2 *(Fert[0]+1))) || (i != 0))) cerr <<"Passed fertility condition \n"; else cerr <<"Failed fertility condition \n"; } } // end of if (score == 0) else { Fert[best_i]++; A[j] = best_i; } ss *= score; } // end of if (j != j_peg) } // end of for (j == 1 ; ...) if (ss <= 0) { cerr << "WARNING: Model2 viterbi alignment has zero score for sentence pair:\n"; printSentencePair(es, fs, cerr); } best_score = prob_of_target_and_alignment_given_source(A, Fert, tTable, fs, es); } void model3::collectCountsOverAlignement(const Vector<WordIndex>& es, const Vector<WordIndex>& fs, const Vector<WordIndex>& A, LogProb score, float count) { WordIndex j, i, l, m; Vector<WordIndex> Fert(es.size(),0); l = es.size() - 1; m = fs.size() - 1; score *= LogProb(count); COUNT temp = COUNT(score) ; for (i=0; i <= l; i++) Fert[i] = 0; for (j = 1; j <= m; j++) { Fert[A[j]]++; tTable.incCount(es[A[j]], fs[j], temp); // tCountTable.getRef(es[A[j]], fs[j])+=score; if (A[j]) dCountTable.addValue(j, A[j], l, m, temp); aCountTable.addValue(A[j], j, l, m, temp); } for (i = 0; i <= l; i++) nCountTable.addValue(es[i], Fert[i], temp); // p1_count += score * (LogProb) (Fert[0]) ; // p0_count += score * (LogProb) ((m - 2 * Fert[0])) ; p1_count += temp * (Fert[0]); p0_count += temp * ((m - 2 * Fert[0])); } void model3::findAlignmentsNeighborhood(Vector<WordIndex>& es, Vector<WordIndex>& fs, LogProb&align_total_count, alignmodel&neighborhood, int i_peg = -1, int j_peg = -1) // Finding the Neigborhood of a best viterbi alignment after hill climbing // if (i_peg == -1 and j_peg == -1, then No Pegging is done. { LogProb best_score, score; WordIndex i, j, l, m, old_i, j1; Vector<WordIndex> A(fs.size(),0); Vector<WordIndex> Fert(es.size(),0); time_t it_st; best_score = 0; l = es.size() - 1; m = fs.size() - 1; findBestAlignment(es, fs, A, Fert, best_score, /*tTable, aTable,*/i_peg, j_peg); if (best_score == 0) { cerr << "WARNING: viterbi alignment score is zero for the following pair\n"; printSentencePair(es, fs, cerr); } hillClimb(es, fs, A, Fert, best_score, tTable, i_peg, j_peg); if (best_score <= 0) { cerr << "WARNING: Hill Climbing yielded a zero score viterbi alignment for the following pair:\n"; printSentencePair(es, fs, cerr); } else { // best_score > 0 // if (2 * Fert[0] < m ){ if (2*Fert[0] <= m) { /* consider alignments that has Fert[0] less than half the number of words in French sentence */ if (neighborhood.insert(A, best_score)) { align_total_count += best_score; } } else { // else part is added for debugging / Yaser cerr << "WARNING:Best Alignment found violates Fertility requiremnets !!\n"; for (i = 0; i <= l; i++) cerr << "Fert["<<i<<"] = "<< Fert[i] << "\n"; for (j = 1; j <= m; j++) { cerr << "A["<<j<<"] = "<< A[j] <<"\n"; } cerr << "Condition violated : 2 * Fert[0] <= m " << 2*Fert[0] <<"?" << m << "\n"; } // end of added code for debugging // Yaser it_st = time(NULL) ; // Now find add all neighbors of the best alignmet to the collection for (j = 1; j <= m; j++) { for (j1 = j + 1; j1 <= m; j1++) { // all possible swaps if (A[j] != A[j1]) {// make sure you are not swapping at same position // score = best_score * scoreOfSwap(es, fs, A, best_score, tTable, j, j1); score = best_score * scoreOfSwap(es, fs, A, tTable, j, j1); // ADD A and its score to list of alig. to collect counts over if (2 * Fert[0] <= m && score > 0) { /* consider alignments that has Fert[0] less than half the number of words in French sentence */ old_i = A[j]; A[j] = A[j1]; A[j1] = old_i; if (neighborhood.insert(A, score)) { align_total_count += score; } // restore original alignment old_i = A[j]; A[j] = A[j1]; A[j1] = old_i; } } } for (i = 0; i <= l; i++) { // all possible moves if (i != A[j]) { // make sure not to move to same position if ((Fert[i]+1 < MAX_FERTILITY) && ((i == 0 && (m >= 2 *(Fert[0]+1))) || (i != 0))) { // consider legal alignments only score = best_score * scoreOfMove(es, fs, A, Fert, tTable, j, i); // ADD A and its score to list of alig. to collect counts over if (score > 0) { old_i = A[j]; A[j] = i; Fert[old_i]--; Fert[i]++; // add to list of alignemts here ****************** if (neighborhood.insert(A, score)) { align_total_count += score; } // now resotre alignment and fertilities to previoud values A[j] = old_i; Fert[old_i]++; Fert[i]--; } // end of if (score > 0) } // end of if (i == 0 ...) } // end of if (i != A[j]) }// end of for(i = 0 ; ...) }// end of for (j = 1 ; ...) } // of else best_score <= 0 } void model3::viterbi_loop(Perplexity& perp, Perplexity& viterbiPerp, sentenceHandler& sHandler1, bool dump_files, const char* alignfile, bool collect_counts, string model) { WordIndex i, j, l, m; ofstream of2; int pair_no; LogProb temp; if (dump_files) of2.open(alignfile); pair_no = 0; // sentence pair number // for each sentence pair in the corpus perp.clear() ; // clears cross_entrop & perplexity viterbiPerp.clear(); sentPair sent; while (sHandler1.getNextSentence(sent)) { Vector<WordIndex>& es = sent.eSent; Vector<WordIndex>& fs = sent.fSent; const float count = sent.getCount(); if ((sent.sentenceNo % 1000) == 0) cerr <<sent.sentenceNo << '\n'; time_t sent_s = time(NULL) ; pair_no++; l = es.size() - 1; m = fs.size() - 1; LogProb align_total_count=0; // LogProb best_score; Vector<WordIndex> viterbi_alignment; LogProb viterbi_score; alignmodel neighborhood; neighborhood.clear(); align_total_count = 0; findAlignmentsNeighborhood( /*tTable, aTable,*//*p1_count, p0_count,*/es, fs, align_total_count, neighborhood) ; if (Peg) { for (i = 0; i <= l; i++) for (j = 1; j <= m; j++) { if ( (tTable.getProb(es[i], fs[j]) > PROB_SMOOTH) && (aTable.getValue(i, j, l, m) > PROB_SMOOTH) && (dTable.getValue(j, i, l, m) > PROB_SMOOTH)) findAlignmentsNeighborhood(/*tTable, aTable,*//*p1_count, p0_count, */es, fs, align_total_count, neighborhood, i, j); } } // Now Collect counts over saved neighborhoods viterbi_score = 0; if (Verbose) cerr << "\nCollecting counts over found alignments, total prob: " << align_total_count << "\n"; alignment_hash::iterator align; int acount = 0; if (align_total_count == 0) { cerr << " WARNINIG: For the following sentence pair : \n"; printSentencePair(es, fs, cerr); cerr << "The collection of alignments found have 0 probability!!\n"; cerr << "No counts will be collected of it \n"; } else { if (collect_counts) { for (align = neighborhood.begin(); align != neighborhood.end(); align++) { temp = (*align).second/align_total_count; collectCountsOverAlignement(/*tTable, aCountTable, */es, fs, /*p1_count, p0_count ,*/((*align).first), temp, count); acount++; if (viterbi_score < temp) { viterbi_alignment = ((*align).first); viterbi_score = temp; } } } // end of if (collect_counts) perp.addFactor(log(double(align_total_count)), count, l, m, 0); viterbiPerp.addFactor(log(double(viterbi_score)), count, l, m, 0); if (Verbose) { cerr << "Collected counts over "<<acount <<" (of " << pow( double(m), double(l+1)) <<") differnet alignments\n"; cerr << "Bucket count of alignments hash: " << neighborhood.getHash().bucket_count()<< ", size " << neighborhood.getHash().size() << "\n"; } } // end of else // write best alignment (viterbi) for this sentence pair to alignment file if (collect_counts) { if (viterbi_score <= 0) { cerr << "Viterbi Alignment for this pair have score zero!!\n"; of2 << "\n\n"; } else { if (dump_files) printAlignToFile(es, fs, Elist.getVocabList(), Flist.getVocabList(), of2, viterbi_alignment, pair_no, viterbi_score); addAL(viterbi_alignment, sent.sentenceNo, l); } } // end of if (collect_counts) double period = difftime(time(NULL), sent_s); if (Verbose) cerr << "processing this sentence pair took : " << period << " seconds\n"; } /* of sentence pair E, F */ sHandler1.rewind(); errorReportAL(cerr, model); perp.record(model); viterbiPerp.record(model); if (dump_files) of2.close(); }
36.111111
386
0.59707
[ "vector", "model" ]
939bf1bf4088acd8e8fd9bb5b2cc673114839528
10,345
cc
C++
SimG4CMS/Calo/src/HGCSD.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
SimG4CMS/Calo/src/HGCSD.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
SimG4CMS/Calo/src/HGCSD.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // File: HGCSD.cc // Description: Sensitive Detector class for Combined Forward Calorimeter /////////////////////////////////////////////////////////////////////////////// #include "DataFormats/Math/interface/FastMath.h" #include "SimG4CMS/Calo/interface/HGCSD.h" #include "SimG4Core/Notification/interface/TrackInformation.h" #include "SimDataFormats/CaloTest/interface/HGCalTestNumbering.h" #include "DetectorDescription/Core/interface/DDFilter.h" #include "DetectorDescription/Core/interface/DDFilteredView.h" #include "DetectorDescription/Core/interface/DDLogicalPart.h" #include "DetectorDescription/Core/interface/DDMaterial.h" #include "DetectorDescription/Core/interface/DDValue.h" #include "FWCore/Utilities/interface/Exception.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/EventSetup.h" #include "Geometry/Records/interface/IdealGeometryRecord.h" #include "Geometry/HGCalCommonData/interface/HGCalDDDConstants.h" #include "Geometry/HGCalCommonData/interface/HGCalGeometryMode.h" #include "G4LogicalVolumeStore.hh" #include "G4LogicalVolume.hh" #include "G4Step.hh" #include "G4Track.hh" #include "G4ParticleTable.hh" #include "G4VProcess.hh" #include "G4Trap.hh" #include <iostream> #include <fstream> #include <iomanip> //#define EDM_ML_DEBUG HGCSD::HGCSD(G4String name, const DDCompactView & cpv, const SensitiveDetectorCatalog & clg, edm::ParameterSet const & p, const SimTrackManager* manager) : CaloSD(name, cpv, clg, p, manager, (float)(p.getParameter<edm::ParameterSet>("HGCSD").getParameter<double>("TimeSliceUnit")), p.getParameter<edm::ParameterSet>("HGCSD").getParameter<bool>("IgnoreTrackID")), numberingScheme(0), mouseBite_(0), slopeMin_(0), levelT_(99) { edm::ParameterSet m_HGC = p.getParameter<edm::ParameterSet>("HGCSD"); eminHit = m_HGC.getParameter<double>("EminHit")*CLHEP::MeV; storeAllG4Hits_ = m_HGC.getParameter<bool>("StoreAllG4Hits"); rejectMB_ = m_HGC.getParameter<bool>("RejectMouseBite"); waferRot_ = m_HGC.getParameter<bool>("RotatedWafer"); angles_ = m_HGC.getUntrackedParameter<std::vector<double>>("WaferAngles"); double waferSize = m_HGC.getUntrackedParameter<double>("WaferSize")*CLHEP::mm; double mouseBite = m_HGC.getUntrackedParameter<double>("MouseBite")*CLHEP::mm; mouseBiteCut_ = waferSize*tan(30.0*CLHEP::deg) - mouseBite; //this is defined in the hgcsens.xml G4String myName(this->nameOfSD()); myFwdSubdet_= ForwardSubdetector::ForwardEmpty; nameX = "HGCal"; if (myName.find("HitsEE")!=std::string::npos) { myFwdSubdet_ = ForwardSubdetector::HGCEE; nameX = "HGCalEESensitive"; } else if (myName.find("HitsHEfront")!=std::string::npos) { myFwdSubdet_ = ForwardSubdetector::HGCHEF; nameX = "HGCalHESiliconSensitive"; } else if (myName.find("HitsHEback")!=std::string::npos) { myFwdSubdet_ = ForwardSubdetector::HGCHEB; nameX = "HGCalHEScintillatorSensitive"; } #ifdef EDM_ML_DEBUG edm::LogInfo("HGCSim")<< "**************************************************" << "\n" << "* *" << "\n" << "* Constructing a HGCSD with name " << name << "\n" << "* *" << "\n" << "**************************************************"; #endif edm::LogInfo("HGCSim") << "HGCSD:: Threshold for storing hits: " << eminHit << " for " << nameX << " subdet " << myFwdSubdet_; edm::LogInfo("HGCSim") << "Flag for storing individual Geant4 Hits " << storeAllG4Hits_; edm::LogInfo("HGCSim") << "Reject MosueBite Flag: " << rejectMB_ << " Size of wafer " << waferSize << " Mouse Bite " << mouseBite << ":" << mouseBiteCut_ << " along " << angles_.size() << " axes"; } HGCSD::~HGCSD() { if (numberingScheme) delete numberingScheme; if (mouseBite_) delete mouseBite_; } bool HGCSD::ProcessHits(G4Step * aStep, G4TouchableHistory * ) { NaNTrap( aStep ) ; if (aStep == NULL) { return true; } else { double r = aStep->GetPreStepPoint()->GetPosition().perp(); double z = std::abs(aStep->GetPreStepPoint()->GetPosition().z()); #ifdef EDM_ML_DEBUG G4int parCode = aStep->GetTrack()->GetDefinition()->GetPDGEncoding(); bool notaMuon = (parCode == mupPDG || parCode == mumPDG ) ? false : true; G4LogicalVolume* lv = aStep->GetPreStepPoint()->GetPhysicalVolume()->GetLogicalVolume(); edm::LogInfo("HGCSim") << "HGCSD: Hit from standard path from " << lv->GetName() << " for Track " << aStep->GetTrack()->GetTrackID() << " (" << aStep->GetTrack()->GetDefinition()->GetParticleName() << ":" << notaMuon << ") R = " << r << " Z = " << z << " slope = " << r/z << ":" << slopeMin_; #endif // Apply fiducial cuts if (r/z >= slopeMin_) { if (getStepInfo(aStep)) { if ((storeAllG4Hits_ || (hitExists() == false)) && (edepositEM+edepositHAD>0.)) currentHit = createNewHit(); } } return true; } } double HGCSD::getEnergyDeposit(G4Step* aStep) { double wt1 = getResponseWt(aStep->GetTrack()); double wt2 = aStep->GetTrack()->GetWeight(); double destep = wt1*(aStep->GetTotalEnergyDeposit()); if (wt2 > 0) destep *= wt2; return destep; } uint32_t HGCSD::setDetUnitId(G4Step * aStep) { G4StepPoint* preStepPoint = aStep->GetPreStepPoint(); const G4VTouchable* touch = preStepPoint->GetTouchable(); //determine the exact position in global coordinates in the mass geometry G4ThreeVector hitPoint = preStepPoint->GetPosition(); float globalZ=touch->GetTranslation(0).z(); int iz( globalZ>0 ? 1 : -1); //convert to local coordinates (=local to the current volume): G4ThreeVector localpos = touch->GetHistory()->GetTopTransform().TransformPoint(hitPoint); //get the det unit id with ForwardSubdetector subdet = myFwdSubdet_; int layer(0), module(0), cell(0); if (m_mode == HGCalGeometryMode::Square) { layer = touch->GetReplicaNumber(0); module = touch->GetReplicaNumber(1); } else { if (touch->GetHistoryDepth() == levelT_) { layer = touch->GetReplicaNumber(0); module = -1; cell = -1; #ifdef EDM_ML_DEBUG edm::LogInfo("HGCSim") << "Depths: " << touch->GetHistoryDepth() << " name " << touch->GetVolume(0)->GetName() << " layer:module:cell " << layer << ":" << module << ":" << cell << std::endl; #endif } else { layer = touch->GetReplicaNumber(2); module = touch->GetReplicaNumber(1); cell = touch->GetReplicaNumber(0); } #ifdef EDM_ML_DEBUG edm::LogInfo("HGCSim") << "Depths: " << touch->GetHistoryDepth() <<" name " << touch->GetVolume(0)->GetName() << ":" << touch->GetReplicaNumber(0) << " " << touch->GetVolume(1)->GetName() << ":" << touch->GetReplicaNumber(1) << " " << touch->GetVolume(2)->GetName() << ":" << touch->GetReplicaNumber(2) << " " << " layer:module:cell " << layer << ":" << module << ":" << cell <<" Material " << mat->GetName()<<":" << aStep->GetPreStepPoint()->GetMaterial()->GetRadlen() << std::endl; #endif if (aStep->GetPreStepPoint()->GetMaterial()->GetRadlen() > 100000.) return 0; } uint32_t id = setDetUnitId (subdet, layer, module, cell, iz, localpos); if (rejectMB_ && m_mode != HGCalGeometryMode::Square && id != 0) { int det, z, lay, wafer, type, ic; HGCalTestNumbering::unpackHexagonIndex(id, det, z, lay, wafer, type, ic); #ifdef EDM_ML_DEBUG edm::LogInfo("HGCSim") << "ID " << std::hex << id << std::dec << " Decode " << det << ":" << z << ":" << lay << ":" << wafer << ":" << type << ":" << ic << std::endl; #endif if (mouseBite_->exclude(hitPoint, z, wafer)) id = 0; } return id; } void HGCSD::update(const BeginOfJob * job) { const edm::EventSetup* es = (*job)(); edm::ESHandle<HGCalDDDConstants> hdc; es->get<IdealGeometryRecord>().get(nameX,hdc); if (hdc.isValid()) { const HGCalDDDConstants* hgcons = hdc.product(); m_mode = hgcons->geomMode(); slopeMin_ = hgcons->minSlope(); levelT_ = hgcons->levelTop(); numberingScheme = new HGCNumberingScheme(*hgcons,nameX); if (rejectMB_) mouseBite_ = new HGCMouseBite(*hgcons,angles_,mouseBiteCut_,waferRot_); } else { edm::LogError("HGCSim") << "HCalSD : Cannot find HGCalDDDConstants for " << nameX; throw cms::Exception("Unknown", "HGCSD") << "Cannot find HGCalDDDConstants for " << nameX << "\n"; } #ifdef EDM_ML_DEBUG edm::LogInfo("HGCSim") << "HGCSD::Initialized with mode " << m_mode << " Slope cut " << slopeMin_ << " top Level " << levelT_ << std::endl; #endif } void HGCSD::initRun() { G4ParticleTable * theParticleTable = G4ParticleTable::GetParticleTable(); G4String particleName; mumPDG = theParticleTable->FindParticle(particleName="mu-")->GetPDGEncoding(); mupPDG = theParticleTable->FindParticle(particleName="mu+")->GetPDGEncoding(); #ifdef EDM_ML_DEBUG edm::LogInfo("HGCSim") << "HGCSD: Particle code for mu- = " << mumPDG << " for mu+ = " << mupPDG; #endif } bool HGCSD::filterHit(CaloG4Hit* aHit, double time) { return ((time <= tmaxHit) && (aHit->getEnergyDeposit() > eminHit)); } uint32_t HGCSD::setDetUnitId (ForwardSubdetector &subdet, int layer, int module, int cell, int iz, G4ThreeVector &pos) { uint32_t id = numberingScheme ? numberingScheme->getUnitID(subdet, layer, module, cell, iz, pos) : 0; return id; } int HGCSD::setTrackID (G4Step* aStep) { theTrack = aStep->GetTrack(); double etrack = preStepPoint->GetKineticEnergy(); TrackInformation * trkInfo = (TrackInformation *)(theTrack->GetUserInformation()); int primaryID = trkInfo->getIDonCaloSurface(); if (primaryID == 0) { #ifdef EDM_ML_DEBUG edm::LogInfo("HGCSim") << "HGCSD: Problem with primaryID **** set by " << "force to TkID **** " <<theTrack->GetTrackID(); #endif primaryID = theTrack->GetTrackID(); } if (primaryID != previousID.trackID()) resetForNewPrimary(preStepPoint->GetPosition(), etrack); return primaryID; }
39.037736
102
0.627066
[ "geometry", "vector" ]
939ceb597d80be671aa08a28758facc1072ca0e8
1,227
cpp
C++
ch10/ex10_07.cpp
regconfi/Cpp-Primer
6e59f24f4c7f3be4f679b7d29084d9d859a463d9
[ "CC0-1.0" ]
3
2015-02-01T09:23:42.000Z
2015-03-24T01:40:34.000Z
ch10/ex10_07.cpp
lafener/Cpp-Primer
8cf1568f2d27622bce2d41493158f58527e5072f
[ "CC0-1.0" ]
null
null
null
ch10/ex10_07.cpp
lafener/Cpp-Primer
8cf1568f2d27622bce2d41493158f58527e5072f
[ "CC0-1.0" ]
1
2018-09-12T03:00:53.000Z
2018-09-12T03:00:53.000Z
// // ex10_07.cpp // Exercise 10.7 // // Created by pezy on 12/9/14. // Copyright (c) 2014 pezy. All rights reserved. // // @Brief Determine if there are any errors in the following programs and, if so, correct the error(s) #include <iostream> #include <vector> #include <list> #include <algorithm> using std::vector; using std::cout; using std::endl; using std::list; using std::cin; using std::fill_n; template<typename Sequence> void print(Sequence const& seq) { for (const auto& i : seq) cout << i << " "; cout << endl; } int main() { // (a) vector<int> vec; list<int> lst; int i; while (cin >> i) lst.push_back(i); vec.resize(lst.size()); // ^ Fixed: added this statement // Cause Algorithms that write to a destination iterator assume // the destination is large enough to hold the number of elements being written. copy(lst.cbegin(), lst.cend(), vec.begin()); // (b) vector<int> v; v.reserve(10); fill_n(v.begin(), 10, 0); // ^ (b)No error, but not any sense. v.size() still equal zero. // Fixed: 1. use `v.resize(10);` // or 2. use `fill_n(std::back_inserter(v), 10, 0)` print(v); print(vec); }
24.54
104
0.604727
[ "vector" ]
4d34646d6bbafdb71b2997eba8aa16d333815b91
28,880
cpp
C++
service/_obsolete/oldold Process.cpp
zukisoft/vm
8da577329a295449ed1517bbf27cb489531b18ac
[ "MIT" ]
2
2017-02-02T13:32:14.000Z
2017-08-20T07:58:49.000Z
service/_obsolete/oldold Process.cpp
zukisoft/vm
8da577329a295449ed1517bbf27cb489531b18ac
[ "MIT" ]
null
null
null
service/_obsolete/oldold Process.cpp
zukisoft/vm
8da577329a295449ed1517bbf27cb489531b18ac
[ "MIT" ]
2
2017-03-09T02:41:25.000Z
2019-07-10T03:22:23.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2015 Michael G. Brehm // // 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 "stdafx.h" #include "Process.h" #pragma warning(push, 4) // INTERPRETER_SCRIPT_MAGIC // // Magic number present at the head of an interpreter script static uint8_t INTERPRETER_SCRIPT_MAGIC[] = { 0x23, 0x21 }; // "#!" // Process::Create<Architecture::x86> // // Explicit Instantiation of template function template std::shared_ptr<Process> Process::Create<Architecture::x86>(const std::shared_ptr<VirtualMachine>&, uapi::pid_t pid, const FileSystem::AliasPtr&, const FileSystem::AliasPtr&, const FileSystem::HandlePtr&, const uapi::char_t**, const uapi::char_t**, const tchar_t*, const tchar_t*); #ifdef _M_X64 // Process::Create<Architecture::x86_64> // // Explicit Instantiation of template function template std::shared_ptr<Process> Process::Create<Architecture::x86_64>(const std::shared_ptr<VirtualMachine>&, uapi::pid_t pid, const FileSystem::AliasPtr&, const FileSystem::AliasPtr&, const FileSystem::HandlePtr&, const uapi::char_t**, const uapi::char_t**, const tchar_t*, const tchar_t*); #endif //----------------------------------------------------------------------------- // Process Constructor // // Arguments: // // TODO: DOCUMENT THEM Process::Process(::Architecture architecture, std::unique_ptr<Host>&& host, std::shared_ptr<Thread>&& thread, uapi::pid_t pid, const FileSystem::AliasPtr& rootdir, const FileSystem::AliasPtr& workingdir, std::unique_ptr<TaskState>&& taskstate, const void* ldt, Bitmap&& ldtslots, const std::shared_ptr<ProcessHandles>& handles, const std::shared_ptr<SignalActions>& sigactions, const void* programbreak) : m_architecture(architecture), m_host(std::move(host)), m_pid(pid), m_rootdir(rootdir), m_workingdir(workingdir), m_taskstate(std::move(taskstate)), m_ldt(ldt), m_handles(handles), m_sigactions(sigactions), m_programbreak(programbreak), m_ldtslots(std::move(ldtslots)) { m_nativethreadproc = nullptr; // Add the initial process thread to the collection m_threads[thread->ThreadId] = std::move(thread); } //----------------------------------------------------------------------------- // Process::CheckHostArchitecture<x86> (static, private) // // Verifies that the created host process is 32-bit // // Arguments: // // process - Handle to the created host process template <> inline void Process::CheckHostArchitecture<Architecture::x86>(HANDLE process) { BOOL result; // Result from IsWow64Process // 32-bit systems can only create 32-bit processes; nothing to worry about if(SystemInformation::ProcessorArchitecture == SystemInformation::Architecture::Intel) return; // 64-bit system; verify that the process is running under WOW64 if(!IsWow64Process(process, &result)) throw Win32Exception(); if(!result) throw Exception(E_PROCESSINVALIDX86HOST); } //----------------------------------------------------------------------------- // Process::CheckHostArchitecture<x86_64> (static, private) // // Verifies that the created host process is 64-bit // // Arguments: // // process - Handle to the created host process #ifdef _M_X64 template <> inline void Process::CheckHostArchitecture<Architecture::x86_64>(HANDLE process) { BOOL result; // Result from IsWow64Process // 64-bit system; verify that the process is not running under WOW64 if(!IsWow64Process(process, &result)) throw Win32Exception(); if(result) throw Exception(E_PROCESSINVALIDX64HOST); } #endif //----------------------------------------------------------------------------- // Process::Clone // // Clones the running process into a new child process // // Arguments: // // TODO std::shared_ptr<Process> Process::Clone(const std::shared_ptr<VirtualMachine>& vm, uint32_t flags, void* taskstate, size_t taskstatelen) { // need parent process to set that up, see CLONE_PARENT flag as well std::unique_ptr<TaskState> ts = TaskState::Create(m_architecture, taskstate, taskstatelen); std::shared_ptr<Process> child; uapi::pid_t pid = 0; m_host->Suspend(); // Suspend the parent process try { // Create the new host process std::unique_ptr<Host> host = Host::Create(vm->GetProperty(VirtualMachine::Properties::HostProcessBinary32).c_str(), vm->GetProperty(VirtualMachine::Properties::HostProcessArguments).c_str(), nullptr, 0); try { host->CloneMemory(m_host); // Clone the address space of the existing process // TODO: If CLONE_VM then the memory gets shared, not cloned pid = vm->AllocatePID(); // Allocate a new process identifier for the child try { // Create the file system handle collection for the child process, which may be shared or duplicated (CLONE_FILES) std::shared_ptr<ProcessHandles> childhandles = (flags & LINUX_CLONE_FILES) ? m_handles : ProcessHandles::Duplicate(m_handles); // Create the signal actions collection for the child process, which may be shared or duplicated (CLONE_SIGHAND) std::shared_ptr<SignalActions> childactions = (flags & LINUX_CLONE_SIGHAND) ? m_sigactions : SignalActions::Duplicate(m_sigactions); Bitmap ldtslots(m_ldtslots); // todo: Architecture is hard-coded /// removed temporarily ///std::shared_ptr<Thread> thread = Thread::FromHandle<Architecture::x86>(host->ProcessHandle, pid, host->ThreadHandle, host->ThreadId); //child = std::make_shared<Process>(m_architecture, std::move(host), std::move(thread), pid, m_rootdir, m_workingdir, std::move(ts), m_ldt, std::move(ldtslots), childhandles, childactions, m_programbreak); child = std::make_shared<Process>(m_architecture, std::move(host), nullptr, pid, m_rootdir, m_workingdir, std::move(ts), m_ldt, std::move(ldtslots), childhandles, childactions, m_programbreak); } catch(...) { vm->ReleasePID(pid); throw; } } // todo: Terminate expects a LINUX error code, not a Windows one! catch(std::exception& ex) { host->Terminate(E_FAIL); throw; (ex); /* TODO */ } } // Ensure that the parent process is resumed in the event of an exception catch(...) { m_host->Resume(); throw; } // TESTING CHILDREN m_children.insert(std::make_pair(pid, child)); m_host->Resume(); // Resume execution of the parent process child->Start(); // Start execution of the child process return child; } //----------------------------------------------------------------------------- // Process::Create (static) // // Constructs a new process instance from an ELF binary // // Arguments: // // vm - Reference to the VirtualMachine instance // rootdir - Initial process root directory alias // workingdir - Initial process working directory alias // handle - Open FileSystem::Handle against the ELF binary to load // argv - ELF command line arguments from caller // envp - ELF environment variables from caller // hostpath - Path to the external host to load // hostargs - Command line arguments to pass to the host template <Architecture architecture> std::shared_ptr<Process> Process::Create(const std::shared_ptr<VirtualMachine>& vm, uapi::pid_t pid, const FileSystem::AliasPtr& rootdir, const FileSystem::AliasPtr& workingdir, const FileSystem::HandlePtr& handle, const uapi::char_t** argv, const uapi::char_t** envp, const tchar_t* hostpath, const tchar_t* hostargs) { using elf = elf_traits<architecture>; std::unique_ptr<ElfImage> executable; // The main ELF binary image to be loaded std::unique_ptr<ElfImage> interpreter; // Optional interpreter image specified by executable uint8_t random[16]; // 16-bytes of random data for AT_RANDOM auxvec // Create the external host process (suspended by default) and verify the class/architecture // as this will all go south very quickly if it's not the expected architecture std::unique_ptr<Host> host = Host::Create(hostpath, hostargs, nullptr, 0); CheckHostArchitecture<architecture>(host->ProcessHandle); try { // The ELF loader requires the file handle to be at position zero handle->Seek(0, LINUX_SEEK_SET); // Generate the AT_RANDOM data to be associated with this process Random::Generate(random, 16); // Attempt to load the binary image into the process, then check for an interpreter executable = ElfImage::Load<architecture>(handle, host); if(executable->Interpreter) { // Acquire a handle to the interpreter binary and attempt to load that into the process bool absolute = (*executable->Interpreter == '/'); FileSystem::HandlePtr interphandle = vm->OpenExecutable(rootdir, (absolute) ? rootdir : workingdir, executable->Interpreter); interpreter = ElfImage::Load<architecture>(interphandle, host); } // Construct the ELF arguments stack image for the hosted process ElfArguments args(argv, envp); (LINUX_AT_EXECFD); // 2 - TODO if(executable->ProgramHeaders) { args.AppendAuxiliaryVector(LINUX_AT_PHDR, executable->ProgramHeaders); // 3 args.AppendAuxiliaryVector(LINUX_AT_PHENT, sizeof(typename elf::progheader_t)); // 4 args.AppendAuxiliaryVector(LINUX_AT_PHNUM, executable->NumProgramHeaders); // 5 } args.AppendAuxiliaryVector(LINUX_AT_PAGESZ, SystemInformation::PageSize); // 6 if(interpreter) args.AppendAuxiliaryVector(LINUX_AT_BASE, interpreter->BaseAddress); // 7 args.AppendAuxiliaryVector(LINUX_AT_FLAGS, 0); // 8 args.AppendAuxiliaryVector(LINUX_AT_ENTRY, executable->EntryPoint); // 9 (LINUX_AT_NOTELF); // 10 - NOT IMPLEMENTED (LINUX_AT_UID); // 11 - TODO (LINUX_AT_EUID); // 12 - TODO (LINUX_AT_GID); // 13 - TODO (LINUX_AT_EGID); // 14 - TODO args.AppendAuxiliaryVector(LINUX_AT_PLATFORM, elf::platform); // 15 (LINUX_AT_HWCAP); // 16 - TODO (LINUX_AT_CLKTCK); // 17 - TODO args.AppendAuxiliaryVector(LINUX_AT_SECURE, 0); // 23 (LINUX_AT_BASE_PLATFORM); // 24 - NOT IMPLEMENTED args.AppendAuxiliaryVector(LINUX_AT_RANDOM, random, 16); // 25 (LINUX_AT_HWCAP2); // 26 - TODO (LINUX_AT_EXECFN); // 31 - TODO -- WHATEVER WAS PASSED INTO EXECVE() GOES HERE (LINUX_AT_SYSINFO); // 32 - TODO MAY NOT IMPLEMENT? //args.AppendAuxiliaryVector(LINUX_AT_SYSINFO_EHDR, vdso->BaseAddress); // 33 - TODO NEEDS VDSO // Allocate the stack for the process, using the currently set initial stack size for the Virtual Machine //// TODO: NEED TO GET STACK LENGTH FROM RESOURCE LIMITS SET FOR VIRTUAL MACHINE size_t stacklen = 2 MiB; const void* stack = host->AllocateMemory(stacklen, PAGE_READWRITE); // Place guard pages at the beginning and the end of the stack host->ProtectMemory(stack, SystemInformation::PageSize, PAGE_READONLY | PAGE_GUARD); host->ProtectMemory(reinterpret_cast<void*>(uintptr_t(stack) + stacklen - SystemInformation::PageSize), SystemInformation::PageSize, PAGE_READONLY | PAGE_GUARD); // Write the ELF arguments into the read/write portion of the process stack section and get the resultant pointer const void* stack_pointer = args.GenerateProcessStack<architecture>(host->ProcessHandle, reinterpret_cast<void*>(uintptr_t(stack) + SystemInformation::PageSize), stacklen - (SystemInformation::PageSize * 2)); // Load the remainder of the StartupInfo structure with the necessary information to get the ELF binary running const void* entry_point = (interpreter) ? interpreter->EntryPoint : executable->EntryPoint; const void* program_break = executable->ProgramBreak; // TODO LDT TEST // SIZE IS BASED ON CLASS (32 v 64) const void* ldt = host->AllocateMemory(LINUX_LDT_ENTRIES * sizeof(uapi::user_desc32), PAGE_READWRITE); // Create the main thread for the process, the initial thread's TID will always match the process PID /// removed temporarily //std::shared_ptr<Thread> thread = Thread::FromHandle<architecture>(host->ProcessHandle, pid, host->ThreadHandle, host->ThreadId); // this should abort on bad handle for now // TODO TESTING NEW STARTUP INFORMATION std::unique_ptr<TaskState> ts = TaskState::Create(architecture, entry_point, stack_pointer); std::shared_ptr<ProcessHandles> handles = ProcessHandles::Create(); std::shared_ptr<SignalActions> actions = SignalActions::Create(); // Create the Process object, transferring the host, startup information and allocated memory sections //return std::make_shared<Process>(architecture, std::move(host), std::move(thread), pid, rootdir, workingdir, std::move(ts), ldt, Bitmap(LINUX_LDT_ENTRIES), handles, actions, program_break); return std::make_shared<Process>(architecture, std::move(host), nullptr, pid, rootdir, workingdir, std::move(ts), ldt, Bitmap(LINUX_LDT_ENTRIES), handles, actions, program_break); } // Terminate the host process on exception since it doesn't get killed by the Host destructor // TODO: should be LinuxException wrapping the underlying one? Only case right now where // that wouldn't be true is interpreter's OpenExec() call which should already throw LinuxExceptions // TODO: exit code should be a LINUX exit code, not a Windows one catch(...) { host->Terminate(E_FAIL); throw; } } //----------------------------------------------------------------------------- // Process::Execute // // Executes a new binary by replacing the contents of this process // void Process::Execute(const std::shared_ptr<VirtualMachine>& vm, const char_t* filename, const char_t* const& argv, const char_t* const& envp) { (argv); (envp); (filename); (vm); m_host->Suspend(); // Suspend the native process try { // If the architecture is the same, can re-use the host process otherwise // a new host process will need to be constructed // Kill all threads // ? do they need to be signaled // Remove all file handles that are set for close-on-exec m_handles->RemoveCloseOnExecute(); // Release all allocated memory m_host->ClearMemory(); // TODO: Actually implement this } catch(...) { m_host->Resume(); throw; } } //----------------------------------------------------------------------------- // Process::FindNativeThread // // Locates a thread within this process based on its native thread identifier // // Arguments: // // nativetid - Native thread identifier std::shared_ptr<Thread> Process::FindNativeThread(DWORD nativetid) { thread_map_lock_t::scoped_lock_read reader(m_threadslock); _ASSERTE(false); // Iterate over the collection to find the native thread //for(const auto iterator : m_threads) // if(iterator.second->NativeThreadId == nativetid) return iterator.second; // Specified thread is not a thread within this process return nullptr; } //----------------------------------------------------------------------------- // Process::FindThread // // Locates a thread within this process based on its thread identifier // // Arguments: // // tid - Thread identifier std::shared_ptr<Thread> Process::FindThread(uapi::pid_t tid) { thread_map_lock_t::scoped_lock_read reader(m_threadslock); // Locate the thread within the collection const auto found = m_threads.find(tid); return (found != m_threads.end()) ? found->second : nullptr; } //----------------------------------------------------------------------------- // Process::GetInitialTaskState // // Gets a copy of the original task state information for the process, the // contents of which varies based on if the process is 32 or 64-bit // // Arguments: // // taskstate - Pointer to receive the task state information // length - Length of the startup information buffer void Process::GetInitialTaskState(void* startinfo, size_t length) { return m_taskstate->CopyTo(startinfo, length); } //----------------------------------------------------------------------------- // Process::getLocalDescriptorTable // // Gets the address of the local descriptor table in the process const void* Process::getLocalDescriptorTable(void) const { return m_ldt; } //----------------------------------------------------------------------------- // Process::MapMemory // // Creates a memory mapping for the process // // Arguments: // // address - Optional fixed address to use for the mapping // length - Length of the requested mapping // prot - Memory protection flags // flags - Memory mapping flags, must include MAP_PRIVATE // fd - Optional file descriptor from which to map // offset - Optional offset into fd from which to map const void* Process::MapMemory(const void* address, size_t length, int prot, int flags, int fd, uapi::loff_t offset) { FileSystem::HandlePtr handle = nullptr; // Handle to the file object _ASSERTE(m_host); _ASSERTE(m_host->ProcessHandle); // MAP_HUGETLB is not currently supported, but may be possible in the future if(flags & LINUX_MAP_HUGETLB) throw LinuxException(LINUX_EINVAL); // MAP_GROWSDOWN is not supported if(flags & LINUX_MAP_GROWSDOWN) throw LinuxException(LINUX_EINVAL); // Suggested base addresses are not supported, switch the address to NULL if MAP_FIXED is not set if((flags & LINUX_MAP_FIXED) == 0) address = nullptr; // Non-anonymous mappings require a valid file descriptor to be specified if(((flags & LINUX_MAP_ANONYMOUS) == 0) && (fd <= 0)) throw LinuxException(LINUX_EBADF); if(fd > 0) handle = GetHandle(fd)->Duplicate(LINUX_O_RDONLY); // Attempt to allocate the process memory and adjust address to that base if it was NULL const void* base = m_host->AllocateMemory(address, length, uapi::LinuxProtToWindowsPageFlags(prot)); if(address == nullptr) address = base; // If a file handle was specified, copy data from the file into the allocated region, // private mappings need not be concerned with writing this data back to the file if(handle != nullptr) { uintptr_t dest = uintptr_t(address); // Easier pointer math as uintptr_t size_t read; // Bytes read from the source file SIZE_T written; // Result from NtWriteVirtualMemory // TODO: Both tempfs and hostfs should be able to handle memory mappings now with // the introduction of sections; this would be much more efficient that way. Such // a call would need to fail for FS that can't support it, and fall back to this // type of implementation. Also evaluate the same in ElfImage, mapping the source // file would be better than having to read it from a stream HeapBuffer<uint8_t> buffer(SystemInformation::AllocationGranularity); // 64K buffer // Seek the file handle to the specified offset if(handle->Seek(offset, LINUX_SEEK_SET) != offset) throw LinuxException(LINUX_EINVAL); do { // Copy the next chunk of bytes from the source file into the process' memory space read = handle->Read(buffer, min(length, buffer.Size)); NTSTATUS result = NtApi::NtWriteVirtualMemory(m_host->ProcessHandle, reinterpret_cast<void*>(dest), buffer, read, &written); if(result != NtApi::STATUS_SUCCESS) throw LinuxException(LINUX_EACCES, StructuredException(result)); dest += written; // Increment destination pointer length -= read; // Decrement remaining bytes to be copied } while((length > 0) && (read > 0)); }; // MAP_LOCKED - Attempt to lock the memory into the process working set if(flags & LINUX_MAP_LOCKED) { // Make an attempt to satisfy this request, but don't throw an exception if it fails void* lockaddress = const_cast<void*>(address); SIZE_T locklength = length; NtApi::NtLockVirtualMemory(m_host->ProcessHandle, &lockaddress, &locklength, NtApi::MAP_PROCESS); } return address; } //----------------------------------------------------------------------------- // Process::getNativeHandle // // Gets the native operating system handle for the process HANDLE Process::getNativeHandle(void) const { return m_host->ProcessHandle; } //----------------------------------------------------------------------------- // Process::getNativeProcessId // // Gets the native operating system process identifier DWORD Process::getNativeProcessId(void) const { return m_host->ProcessId; } //----------------------------------------------------------------------------- // Process::getNativeThreadProc // // Gets the address of the native thread entry point for the process void* Process::getNativeThreadProc(void) const { return m_nativethreadproc; } //----------------------------------------------------------------------------- // Process::getNativeThreadProc // // Gets the address of the native thread entry point for the process void Process::putNativeThreadProc(void* value) { #ifdef _M_X64 if((m_architecture == Architecture::x86) && (uintptr_t(value) > UINT32_MAX)) throw Exception(E_PROCESSINVALIDTHREADPROC); #endif m_nativethreadproc = value; } //----------------------------------------------------------------------------- // Process::getParentProcessId uapi::pid_t Process::getParentProcessId(void) const { // If the parent process is still alive, return that identifier, otherwise // the parent process becomes the init process (id 1) std::shared_ptr<Process> parent = m_parent.lock(); return (parent) ? parent->ProcessId : VirtualMachine::PROCESSID_INIT; } //----------------------------------------------------------------------------- // Process::SetLocalDescriptor // // Creates or updates an entry in the process local descriptor table // // Arguments: // // u_info - user_desc structure describing the LDT to be updated void Process::SetLocalDescriptor(uapi::user_desc32* u_info) { // Grab the requested slot number from the user_desc structure uint32_t slot = u_info->entry_number; ldt_lock_t::scoped_lock writer(m_ldtlock); if(slot == -1) { // Attempt to locate a free slot in the LDT allocation bitmap slot = m_ldtslots.FindClear(); if(slot == Bitmap::NotFound) throw LinuxException(LINUX_ESRCH); // From the caller's perspective, the slot will have bit 13 (0x1000) set // to help ensure that a real LDT won't get accessed slot |= LINUX_LDT_ENTRIES; } // The slot number must fall between LINUX_LDT_ENTRIES and (LINUX_LDT_ENTRIES << 1) if((slot < LINUX_LDT_ENTRIES) || (slot >= (LINUX_LDT_ENTRIES << 1))) throw LinuxException(LINUX_EINVAL); // Attempt to update the entry in the process local descriptor table memory region uintptr_t destination = uintptr_t(m_ldt) + ((slot & ~LINUX_LDT_ENTRIES) * sizeof(uapi::user_desc32)); m_host->WriteMemory(reinterpret_cast<void*>(destination), u_info, sizeof(uapi::user_desc32)); // Provide the allocated/updated slot number back to the caller in the user_desc structure u_info->entry_number = slot; // Track the slot allocation in the zero-based LDT allocation bitmap m_ldtslots.Set(slot & ~LINUX_LDT_ENTRIES); } //----------------------------------------------------------------------------- // Process::SetProgramBreak // // Adjusts the program break address by increasing or decreasing the number // of allocated pages immediately following the loaded binary image // // Arguments: // // address - Requested program break address const void* Process::SetProgramBreak(const void* address) { // NULL can be passed in as the address to retrieve the current program break if(address == nullptr) return m_programbreak; // The real break address must be aligned to a page boundary const void* oldbreak = align::up(m_programbreak, SystemInformation::PageSize); const void* newbreak = align::up(address, SystemInformation::PageSize); // If the aligned addresses are not the same, the actual break must be changed if(oldbreak != newbreak) { // Calculate the delta between the current and requested address intptr_t delta = intptr_t(newbreak) - intptr_t(oldbreak); try { // Allocate or release program break address space based on the calculated delta. if(delta > 0) m_host->AllocateMemory(oldbreak, delta, PAGE_READWRITE); else m_host->ReleaseMemory(newbreak, delta); } // Return the previously set program break address if it could not be adjusted, // this operation is not intended to return any error codes catch(...) { return m_programbreak; } } // Store and return the requested address, not the page-aligned address m_programbreak = address; return m_programbreak; } //----------------------------------------------------------------------------- // Process::SetSignalAction // // Adds or updates a signal action entry for the process // // Arguments: // // signal - Signal to be added or updated // action - Specifies the new signal action structure // oldaction - Optionally receives the previously set signal action structure void Process::SetSignalAction(int signal, const uapi::sigaction* action, uapi::sigaction* oldaction) { // SignalActions has a convenience function for exactly this purpose m_sigactions->Set(signal, action, oldaction); } //----------------------------------------------------------------------------- // Process::Signal // // Sends a signal to the process // // Arguments: // // signal - The signal to send to the process void Process::Signal(int signal) { // most of this is moving to Thread /// README: // http://www.linuxprogrammingblog.com/all-about-linux-signals?page=show /// if(signal > LINUX__NSIG) throw LinuxException(LINUX_EINVAL); // Retrieve the currently action for this signal uapi::sigaction action = m_sigactions->Get(signal); m_threads.at(m_pid)->BeginSignal(signal, action); //// SIGKILL cannot be masked //if(signal == LINUX_SIGKILL) { //} //// SIGSTOP cannot be masked //else if(signal == LINUX_SIGSTOP) { //} //// SIGCONT ? //// SIGCHLD also special //// Real-time signals range from SIGRTMIN to SIGRTMAX, behavior is different //// If the signal has been set to IGNORE don't do anything //if(action.sa_handler == LINUX_SIG_IGN) return; //// If the signal has been set to DEFAULT, use default behaviors //if(action.sa_handler == LINUX_SIG_DFL) return; //{ } //----------------------------------------------------------------------------- // Process::Start // // Starts the process // // Arguments: // // NONE void Process::Start(void) { return m_host->Resume(); } //----------------------------------------------------------------------------- // Process::UnmapMemory // // Releases a memory region allocated with MapMemory // // Arguments: // // address - Base address of the region to be released // length - Length of the region to be released void Process::UnmapMemory(void* address, size_t length) { m_host->ReleaseMemory(address, length); } uapi::pid_t Process::RegisterThread_TEST(DWORD nativeid) { // JUST A TEST - THIS IS GARBAGE m_threadid_TEST = nativeid; return 400; } uapi::pid_t Process::WaitChild_TEST(uapi::pid_t pid, int* status) { // JUST A TEST - THIS IS GARBAGE (pid); uapi::pid_t waitpid = 0; std::vector<HANDLE> handles; for(auto iterator : m_children) { std::shared_ptr<Process> child = iterator.second.lock(); if(child) waitpid = child->ProcessId; if(child) handles.push_back(child->m_host->ProcessHandle); } if(handles.size() == 0) { return -LINUX_ECHILD; } // this will also need to clean up zombie processes/threads WaitForMultipleObjects(handles.size(), handles.data(), FALSE, INFINITE); int x = 123; (x); // reproduce status for WIFxxx macros here // 0x0000 = terminated normally if(status) *status = 0; return waitpid; } //----------------------------------------------------------------------------- // Process::getZombie bool Process::getZombie(void) const { // If the host process has terminated, this process is a zombie return (WaitForSingleObject(m_host->ProcessHandle, 0) == WAIT_OBJECT_0); } //----------------------------------------------------------------------------- #pragma warning(pop)
37.900262
209
0.679986
[ "object", "vector" ]
4d36b295fdcda339002607f6321d72a9a6d9b1a6
2,572
cpp
C++
geopdf/src/ossimGeoPdfPluginInit.cpp
dardok/ossim-plugins
3406ffed9fcab88fe4175b845381611ac4122c81
[ "MIT" ]
12
2016-09-09T01:24:12.000Z
2022-01-09T21:45:58.000Z
geopdf/src/ossimGeoPdfPluginInit.cpp
dardok/ossim-plugins
3406ffed9fcab88fe4175b845381611ac4122c81
[ "MIT" ]
5
2016-02-04T16:10:40.000Z
2021-06-29T05:00:29.000Z
geopdf/src/ossimGeoPdfPluginInit.cpp
dardok/ossim-plugins
3406ffed9fcab88fe4175b845381611ac4122c81
[ "MIT" ]
20
2015-11-17T11:46:22.000Z
2021-11-12T19:23:54.000Z
//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file // // Author: Mingjie Su // // Description: OSSIM GeoPdf plugin initialization // code. // //---------------------------------------------------------------------------- // $Id: ossimGeoPdfPluginInit.cpp 20935 2012-05-18 14:19:30Z dburken $ #include <ossim/plugin/ossimSharedObjectBridge.h> #include <ossim/plugin/ossimPluginConstants.h> #include <ossim/imaging/ossimImageHandlerRegistry.h> #include <ossim/imaging/ossimOverviewBuilderFactoryRegistry.h> #include <ossim/support_data/ossimInfoFactoryRegistry.h> #include "ossimGeoPdfReaderFactory.h" #include "ossimGeoPdfInfoFactory.h" static void setGeoPdfDescription(ossimString& description) { description = "GeoPdf reader plugin\n\n"; } extern "C" { ossimSharedObjectInfo myGeoPdfInfo; ossimString theGeoPdfDescription; std::vector<ossimString> theGeoPdfObjList; const char* getGeoPdfDescription() { return theGeoPdfDescription.c_str(); } int getGeoPdfNumberOfClassNames() { return (int)theGeoPdfObjList.size(); } const char* getGeoPdfClassName(int idx) { if(idx < (int)theGeoPdfObjList.size()) { return theGeoPdfObjList[idx].c_str(); } return (const char*)0; } /* Note symbols need to be exported on windoze... */ OSSIM_PLUGINS_DLL void ossimSharedLibraryInitialize( ossimSharedObjectInfo** info) { myGeoPdfInfo.getDescription = getGeoPdfDescription; myGeoPdfInfo.getNumberOfClassNames = getGeoPdfNumberOfClassNames; myGeoPdfInfo.getClassName = getGeoPdfClassName; *info = &myGeoPdfInfo; /* Register the readers... */ ossimImageHandlerRegistry::instance()-> registerFactory(ossimGeoPdfReaderFactory::instance(), false); /* Register GeoPdf info objects... */ ossimInfoFactoryRegistry::instance()-> registerFactory(ossimGeoPdfInfoFactory::instance()); setGeoPdfDescription(theGeoPdfDescription); ossimGeoPdfReaderFactory::instance()->getTypeNameList(theGeoPdfObjList); theGeoPdfObjList.push_back("ossimGeoPdfInfo"); } /* Note symbols need to be exported on windoze... */ OSSIM_PLUGINS_DLL void ossimSharedLibraryFinalize() { ossimImageHandlerRegistry::instance()-> unregisterFactory(ossimGeoPdfReaderFactory::instance()); ossimInfoFactoryRegistry::instance()-> unregisterFactory(ossimGeoPdfInfoFactory::instance()); } }
29.906977
78
0.66874
[ "vector" ]
4d36b9b4ee2f418b64ad9fa4ea6ae25b4e7b55d7
7,787
cpp
C++
src/LORE/Scene/IO/ModelLoader.cpp
MemoryDealer/LORE
2ce0c6cf03c119e5d1b0b90f3ee044901353283a
[ "MIT" ]
2
2021-07-14T06:05:48.000Z
2021-07-14T18:07:18.000Z
src/LORE/Scene/IO/ModelLoader.cpp
MemoryDealer/LORE
2ce0c6cf03c119e5d1b0b90f3ee044901353283a
[ "MIT" ]
null
null
null
src/LORE/Scene/IO/ModelLoader.cpp
MemoryDealer/LORE
2ce0c6cf03c119e5d1b0b90f3ee044901353283a
[ "MIT" ]
null
null
null
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // // The MIT License (MIT) // This source file is part of LORE // ( Lightweight Object-oriented Rendering Engine ) // // Copyright (c) 2017-2021 Jordan Sparks // // 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 "ModelLoader.h" #include <LORE/Resource/Material.h> #include <LORE/Resource/Sprite.h> #include <LORE/Resource/ResourceController.h> #include <LORE/Util/FileUtils.h> // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // using namespace Lore; // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // ModelLoader::ModelLoader( const string& resourceGroupName ) : _resourceGroupName( resourceGroupName ) { } // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // ModelPtr ModelLoader::load( const string& path, const bool loadTextures ) { const string adjustedPath = Resource::GetWorkingDirectory() + path; _loadTextures = loadTextures; Assimp::Importer importer; const aiScene* scene = importer.ReadFile( adjustedPath, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace | aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph | aiProcess_SortByPType | aiProcess_JoinIdenticalVertices ); if ( !scene || ( scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE ) || !scene->mRootNode ) { throw Exception( "Failed to load model at " + adjustedPath + ": " + importer.GetErrorString() ); } _name = FileUtil::GetFileName( adjustedPath ); _directory = FileUtil::GetFileDir( adjustedPath ); // Allocate a model, processed meshes will be attached to this. _model = Resource::CreateModel( _name, Mesh::Type::Custom, _resourceGroupName ); _processNode( scene->mRootNode, scene ); return _model; } // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // void ModelLoader::_processNode( aiNode* node, const aiScene* scene ) { // Convert all of this node's meshes to a Lore mesh. for ( uint32_t i = 0; i < node->mNumMeshes; ++i ) { aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; _processMesh( mesh, scene ); } // Process all node's children. for ( uint32_t i = 0; i < node->mNumChildren; ++i ) { _processNode( node->mChildren[i], scene ); } } // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // void ModelLoader::_processMesh( aiMesh* mesh, const aiScene* scene ) { Mesh::CustomMeshData data; // Process mesh data. for ( uint32_t i = 0; i < mesh->mNumVertices; ++i ) { Mesh::Vertex vertex; // Vertices. vertex.position = glm::vec3( mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z ); // Normals. vertex.normal = glm::vec3( mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z ); // Texture coordinates. if ( mesh->mTextureCoords[0] ) { // Flip Y coordinate value to account for STBI flipping during load. vertex.texCoords = glm::vec2( mesh->mTextureCoords[0][i].x, -mesh->mTextureCoords[0][i].y ); } // Tangents and bitangents. vertex.tangent = glm::vec3( mesh->mTangents[i].x, mesh->mTangents[i].y, mesh->mTangents[i].z ); vertex.bitangent = glm::vec3( mesh->mBitangents[i].x, mesh->mBitangents[i].y, mesh->mBitangents[i].z ); data.verts.push_back( vertex ); } // Gather indices by walking through the mesh faces. for ( uint32_t i = 0; i < mesh->mNumFaces; ++i ) { const aiFace face = mesh->mFaces[i]; // Retrieve all indices of this face. for ( uint32_t j = 0; j < face.mNumIndices; ++j ) { data.indices.push_back( face.mIndices[j] ); } } // Create a LORE mesh and attach it to the model. auto loreMesh = Resource::CreateMesh( _name + "." + mesh->mName.C_Str(), Mesh::Type::Custom, _resourceGroupName ); loreMesh->init( data ); _model->attachMesh( loreMesh ); // Process material and load the associated textures. if ( mesh->mMaterialIndex >= 0 ) { aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex]; // Add custom per-mesh material settings. aiColor4D diffuse; material->Get( AI_MATKEY_COLOR_DIFFUSE, diffuse ); float opacity = 1.0f; material->Get( AI_MATKEY_OPACITY, opacity ); MaterialPtr loreMat = loreMesh->_material; loreMat->diffuse.r = diffuse.r; loreMat->diffuse.g = diffuse.g; loreMat->diffuse.b = diffuse.b; loreMat->diffuse.a = opacity; loreMat->opacity = opacity; if ( _loadTextures ) { _processTexture( material, aiTextureType_DIFFUSE, loreMesh ); _processTexture( material, aiTextureType_SPECULAR, loreMesh ); _processTexture( material, aiTextureType_NORMALS, loreMesh ); } } } // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // void ModelLoader::_processTexture( aiMaterial* material, const aiTextureType type, MeshPtr mesh ) { auto ConvertTextureType = [] ( const aiTextureType type ) { switch ( type ) { default: case aiTextureType_DIFFUSE: return Texture::Type::Diffuse; case aiTextureType_SPECULAR: return Texture::Type::Specular; case aiTextureType_NORMALS: return Texture::Type::Normal; } }; for ( uint32_t i = 0; i < material->GetTextureCount( type ); ++i ) { aiString str; material->GetTexture( type, i, &str ); // Load the texture into the resource group. const string texturePath = str.C_Str(); const string textureName = FileUtil::GetFileName( texturePath ); auto rc = Resource::GetResourceController(); if ( !rc->resourceExists<Texture>( textureName, _resourceGroupName ) ) { // Create the LORE texture and add it to the provided material's sprite. auto texture = rc->create<Texture>( textureName, _resourceGroupName ); const auto loreTextureType = ConvertTextureType( type ); // Load texture and specify SRGB only for diffuse maps. texture->loadFromFile( _directory + "/" + texturePath, ( Texture::Type::Diffuse == loreTextureType ) ? true : false ); mesh->getSprite()->addTexture( loreTextureType, texture ); LogWrite( Info, "Texture %s loaded for model %s", textureName.c_str(), _name.c_str() ); } else { LogWrite( Warning, "Tried loading texture %s which already exists, using existing one", textureName.c_str() ); const auto loreTextureType = ConvertTextureType( type ); // Load texture and specify SRGB only for diffuse maps. auto texture = rc->get<Texture>( textureName, _resourceGroupName ); mesh->getSprite()->addTexture( loreTextureType, texture ); } } } // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
38.549505
188
0.633492
[ "mesh", "object", "model" ]
4d3b4de2f53afbcec8a8e487649e32a690ea2ad9
15,197
hxx
C++
opencascade/BRep_Tool.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
37
2020-01-20T21:50:21.000Z
2022-02-09T13:01:09.000Z
opencascade/BRep_Tool.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/BRep_Tool.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
22
2020-04-03T21:59:52.000Z
2022-03-06T18:43:35.000Z
// Created on: 1993-07-07 // Created by: Remi LEQUETTE // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRep_Tool_HeaderFile #define _BRep_Tool_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <GeomAbs_Shape.hxx> #include <Geom_Surface.hxx> #include <Geom_Curve.hxx> #include <Geom2d_Curve.hxx> #include <gp_Pnt2d.hxx> #include <gp_Pnt.hxx> #include <Poly_Triangulation.hxx> #include <Poly_Polygon3D.hxx> #include <Poly_Polygon2D.hxx> #include <Poly_PolygonOnTriangulation.hxx> #include <TopAbs_ShapeEnum.hxx> class TopoDS_Shape; class TopoDS_Face; class TopLoc_Location; class TopoDS_Edge; class TopoDS_Vertex; //! Provides class methods to access to the geometry //! of BRep shapes. class BRep_Tool { public: DEFINE_STANDARD_ALLOC //! If S is Shell, returns True if it has no free boundaries (edges). //! If S is Wire, returns True if it has no free ends (vertices). //! (Internal and External sub-shepes are ignored in these checks) //! If S is Edge, returns True if its vertices are the same. //! For other shape types returns S.Closed(). Standard_EXPORT static Standard_Boolean IsClosed (const TopoDS_Shape& S); //! Returns the geometric surface of the face. Returns //! in <L> the location for the surface. Standard_EXPORT static const Handle(Geom_Surface)& Surface (const TopoDS_Face& F, TopLoc_Location& L); //! Returns the geometric surface of the face. It can //! be a copy if there is a Location. Standard_EXPORT static Handle(Geom_Surface) Surface (const TopoDS_Face& F); //! Returns the Triangulation of the face. It is a //! null handle if there is no triangulation. Standard_EXPORT static const Handle(Poly_Triangulation)& Triangulation (const TopoDS_Face& F, TopLoc_Location& L); //! Returns the tolerance of the face. Standard_EXPORT static Standard_Real Tolerance (const TopoDS_Face& F); //! Returns the NaturalRestriction flag of the face. Standard_EXPORT static Standard_Boolean NaturalRestriction (const TopoDS_Face& F); //! Returns True if <F> has a surface, false otherwise. Standard_EXPORT static Standard_Boolean IsGeometric (const TopoDS_Face& F); //! Returns True if <E> is a 3d curve or a curve on //! surface. Standard_EXPORT static Standard_Boolean IsGeometric (const TopoDS_Edge& E); //! Returns the 3D curve of the edge. May be a Null //! handle. Returns in <L> the location for the curve. //! In <First> and <Last> the parameter range. Standard_EXPORT static const Handle(Geom_Curve)& Curve (const TopoDS_Edge& E, TopLoc_Location& L, Standard_Real& First, Standard_Real& Last); //! Returns the 3D curve of the edge. May be a Null handle. //! In <First> and <Last> the parameter range. //! It can be a copy if there is a Location. Standard_EXPORT static Handle(Geom_Curve) Curve (const TopoDS_Edge& E, Standard_Real& First, Standard_Real& Last); //! Returns the 3D polygon of the edge. May be a Null //! handle. Returns in <L> the location for the polygon. Standard_EXPORT static const Handle(Poly_Polygon3D)& Polygon3D (const TopoDS_Edge& E, TopLoc_Location& L); //! Returns the curve associated to the edge in the //! parametric space of the face. Returns a NULL //! handle if this curve does not exist. Returns in //! <First> and <Last> the parameter range. //! If the surface is a plane the curve can be not stored but created a new //! each time. The flag pointed by <theIsStored> serves to indicate storage status. //! It is valued if the pointer is non-null. Standard_EXPORT static Handle(Geom2d_Curve) CurveOnSurface (const TopoDS_Edge& E, const TopoDS_Face& F, Standard_Real& First, Standard_Real& Last, Standard_Boolean* theIsStored = NULL); //! Returns the curve associated to the edge in the //! parametric space of the surface. Returns a NULL //! handle if this curve does not exist. Returns in //! <First> and <Last> the parameter range. //! If the surface is a plane the curve can be not stored but created a new //! each time. The flag pointed by <theIsStored> serves to indicate storage status. //! It is valued if the pointer is non-null. Standard_EXPORT static Handle(Geom2d_Curve) CurveOnSurface(const TopoDS_Edge& E, const Handle(Geom_Surface)& S, const TopLoc_Location& L, Standard_Real& First, Standard_Real& Last, Standard_Boolean* theIsStored = NULL); //! For the planar surface builds the 2d curve for the edge //! by projection of the edge on plane. //! Returns a NULL handle if the surface is not planar or //! the projection failed. Standard_EXPORT static Handle(Geom2d_Curve) CurveOnPlane (const TopoDS_Edge& E, const Handle(Geom_Surface)& S, const TopLoc_Location& L, Standard_Real& First, Standard_Real& Last); //! Returns in <C>, <S>, <L> a 2d curve, a surface and //! a location for the edge <E>. <C> and <S> are null //! if the edge has no curve on surface. Returns in //! <First> and <Last> the parameter range. Standard_EXPORT static void CurveOnSurface (const TopoDS_Edge& E, Handle(Geom2d_Curve)& C, Handle(Geom_Surface)& S, TopLoc_Location& L, Standard_Real& First, Standard_Real& Last); //! Returns in <C>, <S>, <L> the 2d curve, the surface //! and the location for the edge <E> of rank <Index>. //! <C> and <S> are null if the index is out of range. //! Returns in <First> and <Last> the parameter range. Standard_EXPORT static void CurveOnSurface (const TopoDS_Edge& E, Handle(Geom2d_Curve)& C, Handle(Geom_Surface)& S, TopLoc_Location& L, Standard_Real& First, Standard_Real& Last, const Standard_Integer Index); //! Returns the polygon associated to the edge in the //! parametric space of the face. Returns a NULL //! handle if this polygon does not exist. Standard_EXPORT static Handle(Poly_Polygon2D) PolygonOnSurface (const TopoDS_Edge& E, const TopoDS_Face& F); //! Returns the polygon associated to the edge in the //! parametric space of the surface. Returns a NULL //! handle if this polygon does not exist. Standard_EXPORT static Handle(Poly_Polygon2D) PolygonOnSurface (const TopoDS_Edge& E, const Handle(Geom_Surface)& S, const TopLoc_Location& L); //! Returns in <C>, <S>, <L> a 2d curve, a surface and //! a location for the edge <E>. <C> and <S> are null //! if the edge has no polygon on surface. Standard_EXPORT static void PolygonOnSurface (const TopoDS_Edge& E, Handle(Poly_Polygon2D)& C, Handle(Geom_Surface)& S, TopLoc_Location& L); //! Returns in <C>, <S>, <L> the 2d curve, the surface //! and the location for the edge <E> of rank <Index>. //! <C> and <S> are null if the index is out of range. Standard_EXPORT static void PolygonOnSurface (const TopoDS_Edge& E, Handle(Poly_Polygon2D)& C, Handle(Geom_Surface)& S, TopLoc_Location& L, const Standard_Integer Index); //! Returns the polygon associated to the edge in the //! parametric space of the face. Returns a NULL //! handle if this polygon does not exist. Standard_EXPORT static const Handle(Poly_PolygonOnTriangulation)& PolygonOnTriangulation (const TopoDS_Edge& E, const Handle(Poly_Triangulation)& T, const TopLoc_Location& L); //! Returns in <P>, <T>, <L> a polygon on triangulation, a //! triangulation and a location for the edge <E>. //! <P> and <T> are null if the edge has no //! polygon on triangulation. Standard_EXPORT static void PolygonOnTriangulation (const TopoDS_Edge& E, Handle(Poly_PolygonOnTriangulation)& P, Handle(Poly_Triangulation)& T, TopLoc_Location& L); //! Returns in <P>, <T>, <L> a polygon on //! triangulation, a triangulation and a location for //! the edge <E> for the range index. <C> and <S> are //! null if the edge has no polygon on triangulation. Standard_EXPORT static void PolygonOnTriangulation (const TopoDS_Edge& E, Handle(Poly_PolygonOnTriangulation)& P, Handle(Poly_Triangulation)& T, TopLoc_Location& L, const Standard_Integer Index); //! Returns True if <E> has two PCurves in the //! parametric space of <F>. i.e. <F> is on a closed //! surface and <E> is on the closing curve. Standard_EXPORT static Standard_Boolean IsClosed (const TopoDS_Edge& E, const TopoDS_Face& F); //! Returns True if <E> has two PCurves in the //! parametric space of <S>. i.e. <S> is a closed //! surface and <E> is on the closing curve. Standard_EXPORT static Standard_Boolean IsClosed (const TopoDS_Edge& E, const Handle(Geom_Surface)& S, const TopLoc_Location& L); //! Returns True if <E> has two arrays of indices in //! the triangulation <T>. Standard_EXPORT static Standard_Boolean IsClosed (const TopoDS_Edge& E, const Handle(Poly_Triangulation)& T, const TopLoc_Location& L); //! Returns the tolerance for <E>. Standard_EXPORT static Standard_Real Tolerance (const TopoDS_Edge& E); //! Returns the SameParameter flag for the edge. Standard_EXPORT static Standard_Boolean SameParameter (const TopoDS_Edge& E); //! Returns the SameRange flag for the edge. Standard_EXPORT static Standard_Boolean SameRange (const TopoDS_Edge& E); //! Returns True if the edge is degenerated. Standard_EXPORT static Standard_Boolean Degenerated (const TopoDS_Edge& E); //! Gets the range of the 3d curve. Standard_EXPORT static void Range (const TopoDS_Edge& E, Standard_Real& First, Standard_Real& Last); //! Gets the range of the edge on the pcurve on the //! surface. Standard_EXPORT static void Range (const TopoDS_Edge& E, const Handle(Geom_Surface)& S, const TopLoc_Location& L, Standard_Real& First, Standard_Real& Last); //! Gets the range of the edge on the pcurve on the face. Standard_EXPORT static void Range (const TopoDS_Edge& E, const TopoDS_Face& F, Standard_Real& First, Standard_Real& Last); //! Gets the UV locations of the extremities of the edge. Standard_EXPORT static void UVPoints (const TopoDS_Edge& E, const Handle(Geom_Surface)& S, const TopLoc_Location& L, gp_Pnt2d& PFirst, gp_Pnt2d& PLast); //! Gets the UV locations of the extremities of the edge. Standard_EXPORT static void UVPoints (const TopoDS_Edge& E, const TopoDS_Face& F, gp_Pnt2d& PFirst, gp_Pnt2d& PLast); //! Sets the UV locations of the extremities of the edge. Standard_EXPORT static void SetUVPoints (const TopoDS_Edge& E, const Handle(Geom_Surface)& S, const TopLoc_Location& L, const gp_Pnt2d& PFirst, const gp_Pnt2d& PLast); //! Sets the UV locations of the extremities of the edge. Standard_EXPORT static void SetUVPoints (const TopoDS_Edge& E, const TopoDS_Face& F, const gp_Pnt2d& PFirst, const gp_Pnt2d& PLast); //! Returns True if the edge is on the surfaces of the //! two faces. Standard_EXPORT static Standard_Boolean HasContinuity (const TopoDS_Edge& E, const TopoDS_Face& F1, const TopoDS_Face& F2); //! Returns the continuity. Standard_EXPORT static GeomAbs_Shape Continuity (const TopoDS_Edge& E, const TopoDS_Face& F1, const TopoDS_Face& F2); //! Returns True if the edge is on the surfaces. Standard_EXPORT static Standard_Boolean HasContinuity (const TopoDS_Edge& E, const Handle(Geom_Surface)& S1, const Handle(Geom_Surface)& S2, const TopLoc_Location& L1, const TopLoc_Location& L2); //! Returns the continuity. Standard_EXPORT static GeomAbs_Shape Continuity (const TopoDS_Edge& E, const Handle(Geom_Surface)& S1, const Handle(Geom_Surface)& S2, const TopLoc_Location& L1, const TopLoc_Location& L2); //! Returns True if the edge has regularity on some //! two surfaces Standard_EXPORT static Standard_Boolean HasContinuity (const TopoDS_Edge& E); //! Returns the max continuity of edge between some surfaces or GeomAbs_C0 if there no such surfaces. Standard_EXPORT static GeomAbs_Shape MaxContinuity (const TopoDS_Edge& theEdge); //! Returns the 3d point. Standard_EXPORT static gp_Pnt Pnt (const TopoDS_Vertex& V); //! Returns the tolerance. Standard_EXPORT static Standard_Real Tolerance (const TopoDS_Vertex& V); //! Finds the parameter of <theV> on <theE>. //! @param theV [in] input vertex //! @param theE [in] input edge //! @param theParam [out] calculated parameter on the curve //! @return TRUE if done Standard_EXPORT static Standard_Boolean Parameter (const TopoDS_Vertex& theV, const TopoDS_Edge& theE, Standard_Real &theParam); //! Returns the parameter of <V> on <E>. //! Throws Standard_NoSuchObject if no parameter on edge Standard_EXPORT static Standard_Real Parameter (const TopoDS_Vertex& V, const TopoDS_Edge& E); //! Returns the parameters of the vertex on the //! pcurve of the edge on the face. Standard_EXPORT static Standard_Real Parameter (const TopoDS_Vertex& V, const TopoDS_Edge& E, const TopoDS_Face& F); //! Returns the parameters of the vertex on the //! pcurve of the edge on the surface. Standard_EXPORT static Standard_Real Parameter (const TopoDS_Vertex& V, const TopoDS_Edge& E, const Handle(Geom_Surface)& S, const TopLoc_Location& L); //! Returns the parameters of the vertex on the face. Standard_EXPORT static gp_Pnt2d Parameters (const TopoDS_Vertex& V, const TopoDS_Face& F); //! Returns the maximum tolerance of input shape subshapes. //@param theShape - Shape to search tolerance. //@param theSubShape - Search subshape, only Face, Edge or Vertex are supported. Standard_EXPORT static Standard_Real MaxTolerance (const TopoDS_Shape& theShape, const TopAbs_ShapeEnum theSubShape); }; #endif // _BRep_Tool_HeaderFile
52.403448
211
0.690465
[ "geometry", "shape", "3d" ]
4d57647cb3950b4f108afbfbd4b59b8f91e2cfd4
5,925
hpp
C++
taskflow/core/worker.hpp
dandycheung/taskflow
96620cce7cf3bb67e039dad4ecd556ba61347787
[ "MIT" ]
3,457
2018-06-09T15:36:42.000Z
2020-06-01T22:09:25.000Z
taskflow/core/worker.hpp
dandycheung/taskflow
96620cce7cf3bb67e039dad4ecd556ba61347787
[ "MIT" ]
146
2018-06-11T04:11:22.000Z
2020-06-01T20:59:21.000Z
taskflow/core/worker.hpp
dandycheung/taskflow
96620cce7cf3bb67e039dad4ecd556ba61347787
[ "MIT" ]
426
2018-06-06T18:01:16.000Z
2020-06-01T05:26:17.000Z
#pragma once #include "declarations.hpp" #include "tsq.hpp" #include "notifier.hpp" /** @file worker.hpp @brief worker include file */ namespace tf { // ---------------------------------------------------------------------------- // Class Definition: Worker // ---------------------------------------------------------------------------- /** @class Worker @brief class to create a worker in an executor The class is primarily used by the executor to perform work-stealing algorithm. Users can access a worker object and alter its property (e.g., changing the thread affinity in a POSIX-like system) using tf::WorkerInterface. */ class Worker { friend class Executor; friend class WorkerView; public: /** @brief queries the worker id associated with its parent executor A worker id is a unsigned integer in the range <tt>[0, N)</tt>, where @c N is the number of workers spawned at the construction time of the executor. */ inline size_t id() const { return _id; } /** @brief acquires a pointer access to the underlying thread */ inline std::thread* thread() const { return _thread; } /** @brief queries the size of the queue (i.e., number of enqueued tasks to run) associated with the worker */ inline size_t queue_size() const { return _wsq.size(); } /** @brief queries the current capacity of the queue */ inline size_t queue_capacity() const { return static_cast<size_t>(_wsq.capacity()); } private: size_t _id; size_t _vtm; Executor* _executor; std::thread* _thread; Notifier::Waiter* _waiter; std::default_random_engine _rdgen { std::random_device{}() }; TaskQueue<Node*> _wsq; }; // ---------------------------------------------------------------------------- // Class Definition: PerThreadWorker // ---------------------------------------------------------------------------- /** @private */ //struct PerThreadWorker { // // Worker* worker; // // PerThreadWorker() : worker {nullptr} {} // // PerThreadWorker(const PerThreadWorker&) = delete; // PerThreadWorker(PerThreadWorker&&) = delete; // // PerThreadWorker& operator = (const PerThreadWorker&) = delete; // PerThreadWorker& operator = (PerThreadWorker&&) = delete; //}; /** @private */ //inline PerThreadWorker& this_worker() { // thread_local PerThreadWorker worker; // return worker; //} // ---------------------------------------------------------------------------- // Class Definition: WorkerView // ---------------------------------------------------------------------------- /** @class WorkerView @brief class to create an immutable view of a worker in an executor An executor keeps a set of internal worker threads to run tasks. A worker view provides users an immutable interface to observe when a worker runs a task, and the view object is only accessible from an observer derived from tf::ObserverInterface. */ class WorkerView { friend class Executor; public: /** @brief queries the worker id associated with its parent executor A worker id is a unsigned integer in the range <tt>[0, N)</tt>, where @c N is the number of workers spawned at the construction time of the executor. */ size_t id() const; /** @brief queries the size of the queue (i.e., number of pending tasks to run) associated with the worker */ size_t queue_size() const; /** @brief queries the current capacity of the queue */ size_t queue_capacity() const; private: WorkerView(const Worker&); WorkerView(const WorkerView&) = default; const Worker& _worker; }; // Constructor inline WorkerView::WorkerView(const Worker& w) : _worker{w} { } // function: id inline size_t WorkerView::id() const { return _worker._id; } // Function: queue_size inline size_t WorkerView::queue_size() const { return _worker._wsq.size(); } // Function: queue_capacity inline size_t WorkerView::queue_capacity() const { return static_cast<size_t>(_worker._wsq.capacity()); } // ---------------------------------------------------------------------------- // Class Definition: WorkerInterface // ---------------------------------------------------------------------------- /** @brief class WorkerInterface The tf::WorkerInterface class lets users to interact with the executor to customize the thread behavior, such as calling custom methods before and after a worker enters and leaves the loop. When you create an executor, it spawns a set of workers to run tasks. The interaction between the executor and its spawned workers looks like the following: for(size_t n=0; n<num_workers; n++) { create_thread([](Worker& worker) // pre-processing executor-specific worker information // ... // enter the scheduling loop // Here, WorkerInterface::scheduler_prologue is invoked, if any while(1) { perform_work_stealing_algorithm(); if(stop) { break; } } // leaves the scheduling loop and joins this worker thread // Here, WorkerInterface::scheduler_epilogue is invoked, if any ); } @note Methods defined in tf::WorkerInterface are not thread-safe and may be be invoked by multiple workers concurrently. */ class WorkerInterface { public: /** @brief default destructor */ virtual ~WorkerInterface() = default; /** @brief method to call before a worker enters the scheduling loop @param worker a reference to the worker */ virtual void scheduler_prologue(Worker& worker) = 0; /** @brief method to call after a worker leaves the scheduling loop @param worker a reference to the worker @param ptr an pointer to the exception thrown by the scheduling loop */ virtual void scheduler_epilogue(Worker& worker, std::exception_ptr ptr) = 0; }; } // end of namespact tf -----------------------------------------------------
24.6875
89
0.61384
[ "object" ]
4d5ef0d08ae67b23d1476177d725fd4c8aa22da3
1,448
cpp
C++
src/parsers/helpers/buildCategoryHirachyRecursively.cpp
bencabrera/wikiMainPath
a42e81a8fbe119e858548045653b2a22068a34f8
[ "MIT" ]
null
null
null
src/parsers/helpers/buildCategoryHirachyRecursively.cpp
bencabrera/wikiMainPath
a42e81a8fbe119e858548045653b2a22068a34f8
[ "MIT" ]
null
null
null
src/parsers/helpers/buildCategoryHirachyRecursively.cpp
bencabrera/wikiMainPath
a42e81a8fbe119e858548045653b2a22068a34f8
[ "MIT" ]
null
null
null
#include "buildCategoryHirachyRecursively.h" #include <iostream> #include <algorithm> #include "cycleDetectorVisitor.h" void build_category_hirachy_graph_recursively(CategoryHirachyGraph& graph, std::vector<boost::container::flat_set<std::size_t>>& category_has_article) { // check if there are no cycles left std::vector<std::vector<CategoryHirachyGraph::vertex_descriptor>> cycles; CycleDetectorDfsVisitor vis(cycles); boost::depth_first_search(graph, boost::visitor(vis)); if(cycles.size() > 0) throw std::logic_error("There are cycles left in CategoryHirachyGraph"); // do the following until all vertices are isolated bool allIsolated = false; while(!allIsolated) { allIsolated = true; for(std::size_t v = 0; v < boost::num_vertices(graph); v++) { if(boost::out_degree(v,graph) == 0 && boost::in_degree(v,graph) == 0) continue; // if algo reaches this point then not all vertices are isolated allIsolated = false; // has no outgoing edges => starting point to insert categories into each other if(boost::out_degree(v,graph) == 0) { for(auto e : boost::make_iterator_range(boost::in_edges(v,graph))) { std::size_t parentIdx = boost::source(e,graph); std::size_t childIdx = boost::target(e,graph); category_has_article[parentIdx].insert(category_has_article[childIdx].begin(), category_has_article[childIdx].end()); } boost::clear_vertex(v, graph); } } } }
32.177778
150
0.718232
[ "vector" ]
4d5fac3bab2a78300e9c70e313ca9544ae235af1
3,476
hpp
C++
include/Passion/Render/Vector.hpp
necrophcodr/Passion
816448d62d714d704c31f59464b08a5d93e8d36a
[ "Zlib" ]
2
2015-12-14T05:47:23.000Z
2016-05-10T16:38:30.000Z
include/Passion/Render/Vector.hpp
necrophcodr/Passion
816448d62d714d704c31f59464b08a5d93e8d36a
[ "Zlib" ]
null
null
null
include/Passion/Render/Vector.hpp
necrophcodr/Passion
816448d62d714d704c31f59464b08a5d93e8d36a
[ "Zlib" ]
null
null
null
//////////////////////////////////////////////////////////// // // Copyright (C) 2010 Alexander Overvoorde (overv161@gmail.com) // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// #ifndef PASSION_VECTOR_HPP #define PASSION_VECTOR_HPP #include <cmath> namespace Passion { class Matrix; class Vector { public: Vector( float X = 0.0f, float Y = 0.0f, float Z = 0.0f ) { x = X; y = Y; z = Z; } Vector operator+( Vector vec ); Vector operator-( Vector vec ); Vector operator-(); Vector operator*( float n ); Vector operator*( Matrix m ); Vector operator/( float n ); void operator+=( Vector v ); void operator-=( Vector v ); void operator*=( float n ); void operator/=( float n ); bool operator==( Vector v ); bool operator<( Vector v ); float Distance( Vector v ); float Length(); float LengthSqr(); float Dot( Vector v ); Vector Cross( Vector v ); Vector Normal(); void Normalize(); float x, y, z; }; inline Vector Vector::operator+( Vector vec ) { return Vector( x + vec.x, y + vec.y, z + vec.z ); } inline Vector Vector::operator-( Vector vec ) { return Vector( x - vec.x, y - vec.y, z - vec.z ); } inline Vector Vector::operator-() { return Vector( -x, -y, -z ); } inline Vector Vector::operator*( float n ) { return Vector( x * n, y * n, z * n ); } inline Vector Vector::operator/( float n ) { return Vector( x / n, y / n, z / n ); } inline void Vector::operator+=( Vector v ) { x += v.x; y += v.y; z += v.z; } inline void Vector::operator-=( Vector v ) { x -= v.x; y -= v.y; z -= v.z; } inline void Vector::operator*=( float n ) { x *= n; y *= n; z *= n; } inline void Vector::operator/=( float n ) { x /= n; y /= n; z /= n; } inline bool Vector::operator==( Vector v ) { return LengthSqr() == v.LengthSqr(); } inline bool Vector::operator<( Vector v ) { return LengthSqr() < v.LengthSqr(); } inline float Vector::Distance( Vector v ) { return ( *this - v ).Length(); } inline float Vector::Length() { return sqrt( x*x + y*y + z*z ); } inline float Vector::LengthSqr() { return x*x + y*y + z*z; } inline float Vector::Dot( Vector v ) { return x * v.x + y * v.y + z * v.z; } inline Vector Vector::Cross( Vector v ) { return Vector( y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x ); } inline Vector Vector::Normal() { float length = Length(); return Vector( x / length, y / length, z / length ); } inline void Vector::Normalize() { float length = Length(); x /= length; y/= length; z /= length; } } #endif
22
83
0.600403
[ "vector" ]
4d61bf9cdbd687100be749bdce9b2c3bb9ae7c3a
611
cc
C++
L9/8 - P45829 - Camps/ex8.cc
angelgomezsa/Cplusplus
9fd1ed5b1beffcf253019e8376b2bd41dac6e449
[ "MIT" ]
null
null
null
L9/8 - P45829 - Camps/ex8.cc
angelgomezsa/Cplusplus
9fd1ed5b1beffcf253019e8376b2bd41dac6e449
[ "MIT" ]
null
null
null
L9/8 - P45829 - Camps/ex8.cc
angelgomezsa/Cplusplus
9fd1ed5b1beffcf253019e8376b2bd41dac6e449
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; typedef vector< vector<int> > Matriu; int main() { int rows,cols; while (cin >> rows >> cols) { Matriu camp(rows,vector<int>(cols)); int count=0; for (int i=0;i<rows;i++) { for (int j=0;j<cols;j++) { cin >> camp[i][j]; if (camp[i][j] != 0) { if (i == 0 and j == 0) count++; else if (i == 0) { if (camp[i][j-1] == 0) count++; } else if (j == 0) { if (camp[i-1][j] == 0) count++; } else if (camp[i-1][j] == 0 and camp[i][j-1] == 0) count++; } } } cout << count << endl; } }
18.515152
63
0.477905
[ "vector" ]
4d63b2ff3c93f92d99b20b3417b1336b0f973691
4,649
cc
C++
topcoder/673/BearCavalry.cc
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
1
2019-05-12T23:41:00.000Z
2019-05-12T23:41:00.000Z
topcoder/673/BearCavalry.cc
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
topcoder/673/BearCavalry.cc
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; using vi = vector<int>; using vvi = vector<vi>; using ii = pair<int,int>; using vii = vector<ii>; using l = long long; using vl = vector<l>; using vvl = vector<vl>; using lu = unsigned long long; using vb = vector<bool>; using vvb = vector<vb>; using vd = vector<double>; using vvd = vector<vd>; const int INF = numeric_limits<int>::max(); const double EPS = 1e-10; const l e5 = 100000, e6 = 1000000, e7 = 10000000, e9 = 1000000000; const l MOD = 1000000007; class BearCavalry { void add(l& a, l b) { a = (a + b) % MOD; } public: int countAssignments(vector <int> warriors, vector <int> horses) { sort(horses.begin(), horses.end()); l n = warriors.size(); sort(warriors.begin() + 1, warriors.end()); reverse(warriors.begin() + 1, warriors.end()); l answer = 0; for (l i = 0; i < n; i++) { l cap = warriors[0] * horses[i]; vector<bool> mask(n); mask[i] = true; l m = 1; for (l j = 1; j < n; j++) { l k = n - 1; while (k >= 0 && (mask[k] || (horses[k] * warriors[j] >= cap))) k--; l t = 0; for (l q = 0; q <= k; q++) if (!mask[q]) t++; m = (m * t) % MOD; if (m == 0) break; mask[k] = true; // cerr << t << endl; } // cerr << m << endl; add(answer, m); } // cerr << "---" << endl; return answer; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {5,8,4,8}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {19,40,25,20}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; verify_case(0, Arg2, countAssignments(Arg0, Arg1)); } void test_case_1() { int Arr0[] = {1,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; verify_case(1, Arg2, countAssignments(Arg0, Arg1)); } void test_case_2() { int Arr0[] = {10,2,10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {100,150,200}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; verify_case(2, Arg2, countAssignments(Arg0, Arg1)); } void test_case_3() { int Arr0[] = {10,20}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 1; verify_case(3, Arg2, countAssignments(Arg0, Arg1)); } void test_case_4() { int Arr0[] = {20,20,25,23,24,24,21}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {20,25,25,20,25,23,20}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; verify_case(4, Arg2, countAssignments(Arg0, Arg1)); } void test_case_5() { int Arr0[] = {970,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800, 800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800,800}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000, 1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000, 1000,1000,1000,1000,1000,1000,1000,1000,1000,1000}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 318608048; verify_case(5, Arg2, countAssignments(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { BearCavalry ___test; ___test.run_test(-1); } // END CUT HERE
61.986667
316
0.577759
[ "vector" ]
4d65394b59820615416688060053a5e293299fc9
2,053
hpp
C++
plat2d/lvl.hpp
skiesel/search
b9bb14810a85d6a486d603b3d81444c9d0b246b0
[ "MIT" ]
28
2015-02-10T04:06:16.000Z
2022-03-11T11:51:38.000Z
plat2d/lvl.hpp
skiesel/search
b9bb14810a85d6a486d603b3d81444c9d0b246b0
[ "MIT" ]
3
2016-11-03T12:03:28.000Z
2020-07-13T17:35:40.000Z
plat2d/lvl.hpp
skiesel/search
b9bb14810a85d6a486d603b3d81444c9d0b246b0
[ "MIT" ]
9
2015-10-22T20:22:45.000Z
2020-06-30T20:11:31.000Z
// Copyright © 2013 the Search Authors under the MIT license. See AUTHORS for the list of authors. #pragma once #include "body.hpp" #include "tile.hpp" #include <cstdio> #include <vector> struct Image; struct Lvl { // This constructor creates an empty level. Lvl(unsigned int, unsigned int); // This constructor loads a level from a file. Lvl(FILE*); ~Lvl(); // width returns the width of the level in number of blocks. unsigned int width() const { return w; } // height returns the height of the level in number of // blocks. unsigned int height() const { return h; } // draw draws the level on an image. void draw(Image&) const; // isect returns intersection information for a bounding // box moving at a given velocity through the level. Isect isect(const Bbox&, const geom2d::Pt&) const; struct Blk { Blk() : tile(0) { } unsigned int tile; }; // Blkinfo contains information on a specific level block. struct Blkinfo { Blkinfo(const Blk &b, unsigned int i, unsigned int j) : blk(b), tile(tiles[b.tile]), x(i), y(j) { } const Blk &blk; const Tile &tile; unsigned int x, y; }; // blocked returns true if the level block at the given coordinate // is collidable. bool blocked(unsigned int x, unsigned int y) const { return tiles[blks[ind(x, y)].tile].flags & Tile::Collide; } // at returns the block information structure for the // level block at the given grid coordinate. Blkinfo at(unsigned int x, unsigned int y) const { return Blkinfo(blks[ind(x, y)], x, y); } // majorblk returns the block information struct for the level // block that contains a majority of the rectangle. Blkinfo majorblk(const Bbox &r) const { const geom2d::Pt &c = r.center(); return at(c.x / Tile::Width, c.y / Tile::Height); } private: void read(FILE*); void readtile(FILE*, unsigned int, unsigned int); unsigned int ind(unsigned int x, unsigned int y) const { return x * h + y; } Blk *blk(unsigned int x, unsigned int y) { return blks + ind(x, y); } unsigned int w, h; Blk *blks; };
24.440476
98
0.684364
[ "vector" ]
4d670052a0aa683b59e2b33c1ae85ca98916431c
15,650
cpp
C++
Source/AllProjects/Drivers/iTunesRepoTM/Server/iTunesRepoTMS_DriverImpl.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/Drivers/iTunesRepoTM/Server/iTunesRepoTMS_DriverImpl.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/Drivers/iTunesRepoTM/Server/iTunesRepoTMS_DriverImpl.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: iTunesRepoTMS_DriverImpl.cpp // // AUTHOR: Dean Roddey // // CREATED: 10/16/2012 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the main implementation file of the driver. // // CAVEATS/GOTCHAS: // // LOG: // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "iTunesRepoTMS_.hpp" // --------------------------------------------------------------------------- // Magic macros // --------------------------------------------------------------------------- RTTIDecls(TiTunesRepoTMSDriver,TCQCServerBase) // --------------------------------------------------------------------------- // CLASS: iTunesRepoTMSDriver // PREFIX: drv // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // iTunesRepoSDriver: Constructors and Destructor // --------------------------------------------------------------------------- TiTunesRepoTMSDriver::TiTunesRepoTMSDriver(const TCQCDriverObjCfg& cqcdcToLoad) : TCQCServerBase(cqcdcToLoad) , m_c4FldId_DBSerialNum(kCIDLib::c4MaxCard) , m_c4FldId_Loaded(kCIDLib::c4MaxCard) , m_c4FldId_LoadStatus(kCIDLib::c4MaxCard) , m_c4FldId_Status(kCIDLib::c4MaxCard) , m_c4FldId_ReloadDB(kCIDLib::c4MaxCard) , m_c4FldId_TitleCnt(kCIDLib::c4MaxCard) , m_porbcTray(nullptr) { } TiTunesRepoTMSDriver::~TiTunesRepoTMSDriver() { } // --------------------------------------------------------------------------- // TiTunesRepoTMSDriver: Public, inherited methods // --------------------------------------------------------------------------- // // These are all just passthroughs to the tray app, which just returns the // info in the same form that we would have. // tCIDLib::TBoolean TiTunesRepoTMSDriver::bQueryData(const TString& strQType , const TString& strDName , tCIDLib::TCard4& c4Bytes , THeapBuf& mbufToFill) { CheckConnected(); tCIDLib::TBoolean bRet = kCIDLib::False; try { bRet = m_porbcTray->bQueryData(strQType, strDName, c4Bytes, mbufToFill); } catch(TError& errToCatch) { if (eVerboseLevel() > tCQCKit::EVerboseLvls::High) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } } return bRet; } tCIDLib::TBoolean TiTunesRepoTMSDriver::bQueryData2( const TString& strQType , tCIDLib::TCard4& c4IOBytes , THeapBuf& mbufIO) { CheckConnected(); tCIDLib::TBoolean bRet = kCIDLib::False; try { bRet = m_porbcTray->bQueryData2(strQType, c4IOBytes, mbufIO); } catch(TError& errToCatch) { if (eVerboseLevel() > tCQCKit::EVerboseLvls::High) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } } return bRet; } tCIDLib::TBoolean TiTunesRepoTMSDriver::bQueryTextVal(const TString& strQType , const TString& strDName , TString& strToFill) { CheckConnected(); tCIDLib::TBoolean bRet = kCIDLib::False; try { bRet = m_porbcTray->bQueryTextVal(strQType, strDName, strToFill); } catch(TError& errToCatch) { if (eVerboseLevel() > tCQCKit::EVerboseLvls::High) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } } return bRet; } tCIDLib::TCard4 TiTunesRepoTMSDriver::c4QueryVal(const TString& strValId) { CheckConnected(); tCIDLib::TCard4 c4Ret = 0; try { c4Ret = m_porbcTray->c4QueryVal(strValId); } catch(TError& errToCatch) { if (eVerboseLevel() > tCQCKit::EVerboseLvls::High) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } } return c4Ret; } tCIDLib::TBoolean TiTunesRepoTMSDriver::bSendData(const TString& strSType , TString& strDName , tCIDLib::TCard4& c4Bytes , THeapBuf& mbufToSend) { CheckConnected(); tCIDLib::TBoolean bRet = kCIDLib::False; try { bRet = m_porbcTray->bQueryData(strSType, strDName, c4Bytes, mbufToSend); } catch(TError& errToCatch) { if (eVerboseLevel() > tCQCKit::EVerboseLvls::High) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } } return bRet; } tCIDLib::TCard4 TiTunesRepoTMSDriver::c4SendCmd(const TString& strCmd, const TString& strParms) { CheckConnected(); tCIDLib::TCard4 c4Ret = 0; try { c4Ret = m_porbcTray->c4SendCmd(strCmd, strParms); } catch(TError& errToCatch) { if (eVerboseLevel() > tCQCKit::EVerboseLvls::High) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } } return c4Ret; } // --------------------------------------------------------------------------- // TiTunesRepoTMSDriver: Protected, inherited methods // --------------------------------------------------------------------------- // Try to create a client proxy for the tray monitor tCIDLib::TBoolean TiTunesRepoTMSDriver::bGetCommResource(TThread&) { try { // See if we can find the object id, with a pretty short timeout const tCIDLib::TEncodedTime enctEnd = TTime::enctNowPlusSecs(2); TOrbObjId ooidTray; if (facCIDOrbUC().bGetNSObject(m_strBinding, ooidTray, enctEnd)) m_porbcTray = new TiTRepoIntfClientProxy(ooidTray, m_strBinding); } catch(TError& errToCatch) { if (eVerboseLevel() > tCQCKit::EVerboseLvls::High) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } } // If we got the client proxy allocated, we succeeded return (m_porbcTray != 0); } // Nothing to do. The tray loads the database tCIDLib::TBoolean TiTunesRepoTMSDriver::bWaitConfig(TThread&) { return kCIDLib::True; } tCQCKit::ECommResults TiTunesRepoTMSDriver::eBoolFldValChanged(const TString& strName , const tCIDLib::TCard4 c4FldId , const tCIDLib::TBoolean bNewValue) { // If not connected to the tray monitor, then reject CheckConnected(); if (c4FldId == m_c4FldId_ReloadDB) { if (m_porbcTray->bReloadDB()) { LogMsg ( L"The Tray Monitor rejected the reload command" , tCQCKit::EVerboseLvls::Low , CID_FILE , CID_LINE ); IncFailedWriteCounter(); return tCQCKit::ECommResults::ValueRejected; } } else { IncUnknownWriteCounter(); return tCQCKit::ECommResults::FieldNotFound; } return tCQCKit::ECommResults::Success; } tCQCKit::ECommResults TiTunesRepoTMSDriver::eConnectToDevice(TThread& thrCaller) { // // We have already really connected, in the getting of the comm resource, // but we will do an initial query of the status of the tray monitor's // iTunes interface and get that stored. // return tCQCKit::ECommResults::Success; } tCQCKit::EDrvInitRes TiTunesRepoTMSDriver::eInitializeImpl() { // // Make sure that we were configured for a socket connection. Otherwise, // its a bad configuration. // const TCQCDriverObjCfg& cqcdcOurs = cqcdcThis(); if (cqcdcOurs.conncfgReal().clsIsA() != TCQCOtherConnCfg::clsThis()) { // Note that we are throwing a CQCKit error here! facCQCKit().ThrowErr ( CID_FILE , CID_LINE , kKitErrs::errcDrv_BadConnCfgType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Config , cqcdcOurs.conncfgReal().clsIsA() , clsIsA() , TCQCOtherConnCfg::clsThis() ); } SetPollTimes(2000, 5000); // Set up the binding we expect to find the tray monitor at m_strBinding = TiTRepoIntfClientProxy::strImplBinding; m_strBinding.eReplaceToken(TSysInfo::strIPHostName(), kCIDLib::chLatin_b); // // And set up our device fields. The bulk of what this driver does is // via the media interface, and this driver doesn't control any device // or app, so there are just a few. // TVector<TCQCFldDef> colFlds(8); TCQCFldDef flddNew; TString strFldDBSerialNum(L"DBSerialNum"); TString strFldLoaded(L"Loaded"); TString strFldReloadDB(L"ReloadDB"); TString strFldLoadStatus(L"LoadStatus"); TString strFldStatus(L"Status"); TString strFldTitleCnt(L"TitleCount"); const tCIDLib::TBoolean bV2(c4ArchVersion() > 1); // // If V2, prepend the device class prefix to the fields used in V2. Else, // set up any V1 only fields. // if (bV2) { const TString& strPref(L"MREPO#"); strFldDBSerialNum.Prepend(strPref); strFldLoadStatus.Prepend(strPref); strFldReloadDB.Prepend(strPref); strFldStatus.Prepend(strPref); strFldTitleCnt.Prepend(strPref); } else { flddNew.Set ( strFldLoaded , tCQCKit::EFldTypes::Boolean , tCQCKit::EFldAccess::Read ); colFlds.objAdd(flddNew); } // // These are the same, the V2 ones just have the device class prefix. // The DBSerialNum and LoadStatus fields weren't there in V1 but it // doesn't hurt anything to include them V1 drivers, and it makes things // simpler since we don't have to special case them. // flddNew.Set ( strFldDBSerialNum , tCQCKit::EFldTypes::String , tCQCKit::EFldAccess::Read ); colFlds.objAdd(flddNew); flddNew.Set ( strFldLoadStatus , tCQCKit::EFldTypes::String , tCQCKit::EFldAccess::Read , L"Enum: Initializing, Loading, Ready, Error" ); colFlds.objAdd(flddNew); flddNew.Set ( strFldReloadDB , tCQCKit::EFldTypes::Boolean , tCQCKit::EFldAccess::Write ); colFlds.objAdd(flddNew); flddNew.Set ( strFldStatus , tCQCKit::EFldTypes::String , tCQCKit::EFldAccess::Read ); colFlds.objAdd(flddNew); flddNew.Set ( strFldTitleCnt , tCQCKit::EFldTypes::Card , tCQCKit::EFldAccess::Read ); colFlds.objAdd(flddNew); // // Now register our fields with the base driver class, and go back // and look up the ids. // SetFields(colFlds); m_c4FldId_DBSerialNum = pflddFind(strFldDBSerialNum, kCIDLib::True)->c4Id(); m_c4FldId_LoadStatus = pflddFind(strFldLoadStatus, kCIDLib::True)->c4Id(); m_c4FldId_ReloadDB = pflddFind(strFldReloadDB, kCIDLib::True)->c4Id(); m_c4FldId_Status = pflddFind(strFldStatus, kCIDLib::True)->c4Id(); m_c4FldId_TitleCnt = pflddFind(strFldTitleCnt, kCIDLib::True)->c4Id(); if (!bV2) m_c4FldId_Loaded = pflddFind(strFldLoaded, kCIDLib::True)->c4Id(); // // Init the status field to indicate not loaded. The loaded field will have // a default initial value of false, which is what we want. And set the load // status field to loading. // bStoreStringFld ( m_c4FldId_Status , faciTunesRepoTMS().strMsg(kiTunesTMMsgs::midStatus_NotLoaded) , kCIDLib::True ); bStoreStringFld ( m_c4FldId_LoadStatus, L"Initializing", kCIDLib::True ); // We'll try to get a first load of the database before we come online return tCQCKit::EDrvInitRes::WaitCommRes; } tCQCKit::ECommResults TiTunesRepoTMSDriver::ePollDevice(TThread& thrCaller) { // // Just ping it for the status, and update the status field with the // new status. If we lose connection, restart the connection. // try { tCIDLib::TCard4 c4TitleCnt; tCQCMedia::ELoadStatus eCurStatus; tCQCMedia::ELoadStatus eLoadStatus; m_porbcTray->QueryStatus(eCurStatus, eLoadStatus, m_strPollTmp, c4TitleCnt); bStoreStringFld ( m_c4FldId_Status , tCQCMedia::strXlatELoadStatus(eCurStatus) , kCIDLib::True ); bStoreStringFld ( m_c4FldId_LoadStatus , tCQCMedia::strXlatELoadStatus(eLoadStatus) , kCIDLib::True ); bStoreStringFld(m_c4FldId_DBSerialNum, m_strPollTmp, kCIDLib::True); bStoreCardFld(m_c4FldId_TitleCnt, c4TitleCnt, kCIDLib::True); } catch(TError& errToCatch) { if (eVerboseLevel() > tCQCKit::EVerboseLvls::High) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } // // Assume the worst and recylce our client proxy. Note in this // case we can't test if there is a loss of connection, since // the server may still be there, but not the server side // interface for this client proxy. The iTunes interface is // configurable and it could get removed. // return tCQCKit::ECommResults::LostCommRes; } return tCQCKit::ECommResults::Success; } tCIDLib::TVoid TiTunesRepoTMSDriver::ReleaseCommResource() { // Free the client proxy if we have one if (m_porbcTray) { try { delete m_porbcTray; } catch(TError& errToCatch) { if (eVerboseLevel() > tCQCKit::EVerboseLvls::High) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } } m_porbcTray = 0; } } tCIDLib::TVoid TiTunesRepoTMSDriver::TerminateImpl() { } // --------------------------------------------------------------------------- // TiTunesRepoTMSDriver: Private, non-virtual methods // --------------------------------------------------------------------------- // // Called by the backdoor handler methods, to see if we are connected and // throws if not. Generally shouldn't happen, since the client should check // if we are ready. But there's a window of opportunity for it to happen if // we go offline after they check and dispatch a command. // tCIDLib::TVoid TiTunesRepoTMSDriver::CheckConnected() { if (!m_porbcTray || m_porbcTray->bCheckForLostConnection()) { faciTunesRepoTMS().ThrowErr ( CID_FILE , CID_LINE , kiTunesTMErrs::errcProto_NotReady , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotReady ); } }
27.748227
84
0.567093
[ "object" ]
4d6e7ef90baebfa642a319ecadfa6152865d2007
2,902
hpp
C++
external/include/mapnik/image_filter_grammar.hpp
Wujingli/OpenWebGlobeDataProcessing
932eaa00c81fc0571122bc618ade010fa255735e
[ "MIT" ]
null
null
null
external/include/mapnik/image_filter_grammar.hpp
Wujingli/OpenWebGlobeDataProcessing
932eaa00c81fc0571122bc618ade010fa255735e
[ "MIT" ]
null
null
null
external/include/mapnik/image_filter_grammar.hpp
Wujingli/OpenWebGlobeDataProcessing
932eaa00c81fc0571122bc618ade010fa255735e
[ "MIT" ]
2
2019-06-08T15:59:26.000Z
2021-02-06T08:13:01.000Z
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2012 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_IMAGE_FILITER_GRAMMAR_HPP #define MAPNIK_IMAGE_FILITER_GRAMMAR_HPP // boost #include <boost/spirit/include/qi.hpp> #include <boost/fusion/include/adapt_struct.hpp> // mapnik #include <mapnik/css_color_grammar.hpp> #include <mapnik/image_filter.hpp> // stl #include <vector> BOOST_FUSION_ADAPT_STRUCT( mapnik::filter::color_stop, (mapnik::color, color ) (double, offset) ) namespace mapnik { namespace qi = boost::spirit::qi; struct percent_offset_impl { template <typename T> struct result { typedef double type; }; double operator() (double val) const { double result = std::abs(val/100.0); if (result > 1.0) result = 1.0; return result; } }; template <typename Iterator, typename ContType> struct image_filter_grammar : qi::grammar<Iterator, ContType(), qi::ascii::space_type> { image_filter_grammar(); qi::rule<Iterator, ContType(), qi::ascii::space_type> start; qi::rule<Iterator, ContType(), qi::ascii::space_type> filter; qi::rule<Iterator, qi::locals<int,int>, void(ContType&), qi::ascii::space_type> agg_blur_filter; //qi::rule<Iterator, qi::locals<double,double,double,double,double,double,double,double>, // void(ContType&), qi::ascii::space_type> hsla_filter; qi::rule<Iterator, qi::locals<mapnik::filter::colorize_alpha, mapnik::filter::color_stop>, void(ContType&), qi::ascii::space_type> colorize_alpha_filter; qi::rule<Iterator, qi::ascii::space_type> no_args; qi::uint_parser< unsigned, 10, 1, 3 > radius_; css_color_grammar<Iterator> css_color_; qi::rule<Iterator,void(mapnik::filter::color_stop &),qi::ascii::space_type> color_stop_offset; phoenix::function<percent_offset_impl> percent_offset; }; } #endif // MAPNIK_IMAGE_FILITER_PARSER_HPP
34.963855
158
0.656788
[ "vector" ]
4d75c26d48ef2ffcadfe8453f18f532c45ae0f1d
5,592
cpp
C++
src/modules/CameraCalibration.cpp
attila-fenyvesi/TrafficMapper
b11c027b401d519d5082617939a6bc347c6a1b8c
[ "MIT" ]
null
null
null
src/modules/CameraCalibration.cpp
attila-fenyvesi/TrafficMapper
b11c027b401d519d5082617939a6bc347c6a1b8c
[ "MIT" ]
null
null
null
src/modules/CameraCalibration.cpp
attila-fenyvesi/TrafficMapper
b11c027b401d519d5082617939a6bc347c6a1b8c
[ "MIT" ]
null
null
null
#include "CameraCalibration.hpp" #include <TrafficMapper/Media/MediaPlayer> #include <opencv2/calib3d.hpp> #include <opencv2/core/types.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/videoio.hpp> #include <QPainter> // ====================================================================== // CONSTRUCTORS // ====================================================================== CameraCalibration::CameraCalibration(QQuickItem * parent) : QQuickPaintedItem(parent), m_pointSet(0), m_distance_0(0.f), m_distance_1(0.f) {} // ====================================================================== // SETTERS & GETTERS // ====================================================================== const cv::Mat & CameraCalibration::getHomographyMatrix() const { return m_homography_i2p; } // ====================================================================== // PUBLIC FUNCTIONS // ====================================================================== Q_INVOKABLE void CameraCalibration::calculateHomography() { const double ratio_X = MediaPlayer::m_videoMeta.getWIDTH() / (float) property("width").toFloat(); const double ratio_Y = MediaPlayer::m_videoMeta.getHEIGHT() / (float) property("height").toFloat(); std::vector<cv::Point2d> planePoints = { cv::Point2d(0, 0), cv::Point2d(m_distance_0, 0), cv::Point2d(m_distance_0, m_distance_1), cv::Point2d(0, m_distance_1) }; std::vector<cv::Point2d> imgPoints = { cv::Point2d(m_point_0.x() * ratio_X, m_point_0.y() * ratio_Y), cv::Point2d(m_point_1.x() * ratio_X, m_point_1.y() * ratio_Y), cv::Point2d(m_point_2.x() * ratio_X, m_point_2.y() * ratio_Y), cv::Point2d(m_point_3.x() * ratio_X, m_point_3.y() * ratio_Y) }; m_homography_p2i = cv::findHomography(planePoints, imgPoints); m_homography_i2p = cv::findHomography(imgPoints, planePoints); } Q_INVOKABLE void CameraCalibration::loadRandomFrame() { cv::Mat frame; MediaPlayer::getRandomFrame(frame); cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB); m_image = QImage((uchar *) frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888).scaled(QSize(960, 540)); } void CameraCalibration::paint(QPainter * painter) { painter->setRenderHint(QPainter::Antialiasing); painter->drawImage(QPoint(0, 0), m_image); switch (m_pointSet) { case 1: drawRect1(painter); break; case 2: drawRect2(painter); break; case 3: drawRect3(painter); break; case 4: drawRect4(painter); drawPlanePoints(painter); } } // ====================================================================== // PRIVATE FUNCTIONS // ====================================================================== inline void CameraCalibration::drawRect1(QPainter * painter) { QPen pen; pen.setWidth(3); pen.setCapStyle(Qt::RoundCap); pen.setColor(QColor("#CD5555")); painter->setPen(pen); painter->drawLine(m_point_0, m_point_hover); } inline void CameraCalibration::drawRect2(QPainter * painter) { QPen pen; pen.setWidth(3); pen.setCapStyle(Qt::RoundCap); pen.setColor(QColor("#CD5555")); painter->setPen(pen); painter->drawLine(m_point_0, m_point_1); pen.setColor(QColor("#336699")); painter->setPen(pen); painter->drawLine(m_point_0, m_point_hover); painter->drawLine(m_point_1, m_point_hover); } inline void CameraCalibration::drawRect3(QPainter * painter) { QPen pen; pen.setWidth(3); pen.setCapStyle(Qt::RoundCap); pen.setColor(QColor("#CD5555")); painter->setPen(pen); painter->drawLine(m_point_0, m_point_1); painter->drawLine(m_point_2, m_point_hover); pen.setColor(QColor("#336699")); painter->setPen(pen); painter->drawLine(m_point_1, m_point_2); painter->drawLine(m_point_0, m_point_hover); } inline void CameraCalibration::drawRect4(QPainter * painter) { QPen pen; pen.setWidth(3); pen.setCapStyle(Qt::RoundCap); pen.setColor(QColor("#CD5555")); painter->setPen(pen); painter->drawLine(m_point_0, m_point_1); painter->drawLine(m_point_2, m_point_3); pen.setColor(QColor("#336699")); painter->setPen(pen); painter->drawLine(m_point_1, m_point_2); painter->drawLine(m_point_0, m_point_3); } inline void CameraCalibration::drawPlanePoints(QPainter * painter) { std::vector<cv::Point2f> planePoints; std::vector<cv::Point2f> imagePoints; generatePlanePoints(planePoints); cv::perspectiveTransform(planePoints, imagePoints, m_homography_p2i); const float ratio_X = property("width").toFloat() / MediaPlayer::m_videoMeta.getWIDTH(); const float ratio_Y = property("height").toFloat() / MediaPlayer::m_videoMeta.getHEIGHT(); QPen pen; pen.setWidth(3); pen.setColor(QColor("yellow")); painter->setPen(pen); for (const auto & point : imagePoints) painter->drawPoint(QPoint(point.x * ratio_X, point.y * ratio_Y)); } inline void CameraCalibration::generatePlanePoints(std::vector<cv::Point2f> & input) { for (int x(-m_distance_0); x < 2 * m_distance_0; ++x) { for (int y(-m_distance_1); y < 2 * m_distance_1; ++y) { input.push_back(cv::Point2f(x, y)); } } }
30.557377
118
0.573498
[ "vector" ]
4d7d5e6047ed8685f9d800d2569d75dfccebdd24
719
hpp
C++
PnC/ValkyriePnC/ValkyrieTask/SelectedJointTask.hpp
BharathMasetty/PnC
3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f
[ "MIT" ]
null
null
null
PnC/ValkyriePnC/ValkyrieTask/SelectedJointTask.hpp
BharathMasetty/PnC
3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f
[ "MIT" ]
null
null
null
PnC/ValkyriePnC/ValkyrieTask/SelectedJointTask.hpp
BharathMasetty/PnC
3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f
[ "MIT" ]
null
null
null
#pragma once #include <PnC/WBC/Task.hpp> class RobotSystem; class SelectedJointTask : public Task { public: SelectedJointTask(RobotSystem* robot, const std::vector<int>& joint_indices); virtual ~SelectedJointTask(); protected: /* Update pos_err, vel_des, acc_des * * pos_des_ = [q_i, q_i+1, ..., q_i+n] * vel_des_ = [dq_i, dq_i+1, ..., dq_i+n] * acc_des_ = [ddq_i, dq_i+1, ..., ddq_i+n] */ virtual bool _UpdateCommand(const Eigen::VectorXd& pos_des, const Eigen::VectorXd& vel_des, const Eigen::VectorXd& acc_des); virtual bool _UpdateTaskJacobian(); virtual bool _UpdateTaskJDotQdot(); std::vector<int> joint_indices_; };
26.62963
79
0.636996
[ "vector" ]
4d9c619fc0dc3ddbde81c90e33137bb84fa213bd
3,143
cpp
C++
Strings/Slowest-Key-1629.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
38
2021-10-14T09:36:53.000Z
2022-01-27T02:36:19.000Z
Strings/Slowest-Key-1629.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
null
null
null
Strings/Slowest-Key-1629.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
4
2021-12-06T15:47:12.000Z
2022-02-04T04:25:00.000Z
// A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. // You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the // testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was // released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key // was pressed at the exact time the previous key was released. // The tester wants to know the key of the keypress that had the longest duration. The ith keypress had // a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0]. // Note that the same key could have been pressed multiple times during the test, and these multiple presses of // the same key may not have had the same duration. // Return the key of the keypress that had the longest duration. If there are multiple such keypresses, // return the lexicographically largest key of the keypresses. // Example 1: // Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd" // Output: "c" // Explanation: The keypresses were as follows: // Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9). // Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29). // Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49). // Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50). // The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20. // 'c' is lexicographically larger than 'b', so the answer is 'c'. // Example 2: // Input: releaseTimes = [12,23,36,46,62], keysPressed = "spuda" // Output: "a" // Explanation: The keypresses were as follows: // Keypress for 's' had a duration of 12. // Keypress for 'p' had a duration of 23 - 12 = 11. // Keypress for 'u' had a duration of 36 - 23 = 13. // Keypress for 'd' had a duration of 46 - 36 = 10. // Keypress for 'a' had a duration of 62 - 46 = 16. // The longest of these was the keypress for 'a' with duration 16. // Constraints: // releaseTimes.length == n // keysPressed.length == n // 2 <= n <= 1000 // 1 <= releaseTimes[i] <= 109 // releaseTimes[i] < releaseTimes[i+1] // keysPressed contains only lowercase English letters. class Solution { public: char slowestKey(vector<int>& releaseTimes, string keysPressed) { int m = releaseTimes[0]; char s = keysPressed[0]; for(int i=1; i<releaseTimes.size(); i++) { int diff = releaseTimes[i]-releaseTimes[i-1]; if(diff == m) { s = max(s, keysPressed[i]); } if(diff > m) { m = diff; s = keysPressed[i]; } }return s; } };
49.109375
147
0.650016
[ "vector" ]
4d9fd3f69edbbeacd05e16538db1873cd951f717
15,120
cpp
C++
RayTracingSolver/src/SimulationLib/FullSampleSimulation.cpp
warthan07/Nemaktis
54b1e64c1d40668e6dc22b11eac5487a09b58478
[ "MIT" ]
2
2020-02-25T08:13:32.000Z
2022-02-18T12:12:34.000Z
RayTracingSolver/src/SimulationLib/FullSampleSimulation.cpp
warthan07/Nemaktis
54b1e64c1d40668e6dc22b11eac5487a09b58478
[ "MIT" ]
null
null
null
RayTracingSolver/src/SimulationLib/FullSampleSimulation.cpp
warthan07/Nemaktis
54b1e64c1d40668e6dc22b11eac5487a09b58478
[ "MIT" ]
1
2022-02-18T12:13:40.000Z
2022-02-18T12:13:40.000Z
#include <fstream> #include <sstream> #include "FullSampleSimulation.h" #include "LinearInterpolatedMapping.h" #include "InverseScreenMap.h" template <int dim> FullSampleSimulation<dim>::FullSampleSimulation( json settings, double lc_thickness, unsigned int N_lc_steps, std::shared_ptr<CubicInterpolatedMapping<dim,3,double> > &n_field) : Simulation<dim>::Simulation(settings, lc_thickness, N_lc_steps, n_field) { auto N_rays_per_dim = parse_Vector<dim-1,int>( settings.at("Light source"), "Source N rays per dim"); auto widths = parse_Vector<dim-1,double>( settings.at("Light source"), "Source widths"); for(int i=0; i<dim-1; i++) widths(i) *= N_rays_per_dim(i)*1./(N_rays_per_dim(i)-4); auto origin = -widths/2; auto source_mesh = std::make_shared<CartesianMesh<dim-1> >(origin,widths,N_rays_per_dim); auto source_domain = std::make_shared<ParallelotopeDomain<dim-1> >(origin, widths); source = std::make_shared<LightSource<dim-1> >( settings, source_mesh, source_domain); extra_ray_family = std::make_shared<RayFamily<dim> >( *this->source, -this->lower_iso_thickness-this->lc_thickness, 0.5); ordi_ray_family = std::make_shared<RayFamily<dim> >( *this->source, -this->lower_iso_thickness-this->lc_thickness, 0.5); double eps_par = std::pow(this->mat_properties.n_extra, 2.); double eps_perp = std::pow(this->mat_properties.n_ordi, 2.); extra_ode = std::make_shared<ExtraordinaryODEFunction<dim> >( eps_par, eps_perp, n_field); ordi_ode = std::make_shared<OrdinaryODEFunction<dim> >( eps_perp, n_field); // We build the ODE sequences from bottom to top for(auto ode : this->lower_iso_odes) { extra_ray_ode_seq.odes.push_back(ode); ordi_ray_ode_seq.odes.push_back(ode); } extra_ray_ode_seq.odes.push_back(extra_ode); ordi_ray_ode_seq.odes.push_back(ordi_ode); for(auto ode : this->upper_iso_odes) { extra_ray_ode_seq.odes.push_back(ode); ordi_ray_ode_seq.odes.push_back(ode); } ray_splitting_ode_idx = int(this->lower_iso_odes.size()-1); N_rays = int(extra_ray_family->ray_bundles->size()); } template <int dim> void FullSampleSimulation<dim>::run() { std::vector<int> cur_ode_idx(N_rays, ray_splitting_ode_idx+1); auto e = *extra_ray_family; auto o = *ordi_ray_family; auto e_seq = extra_ray_ode_seq; auto o_seq = ordi_ray_ode_seq; RayStepper<dim> stepper(this->z_step); FresnelTransmission<dim> trans; std::shared_ptr<ODEFunction<dim> > trans_odes[4]; std::shared_ptr<DefinitionDomain<dim-1> > screen_domain = std::make_shared<ParallelotopeDomain<dim-1> >( *(this->coarse_horiz_mesh)); /**************************************************** * First, we propagate rays in the lower iso layers * ****************************************************/ std::cout << "Initializing rays..." << std::endl << std::endl; ThreadException exc; std::vector<double> s_steps_extra(N_rays, this->z_step); std::vector<double> s_steps_ordi(N_rays, this->z_step); #pragma omp parallel for \ firstprivate(e_seq, o_seq, stepper, trans) private(trans_odes) for(int i=0; i<N_rays; i++) { try { auto& extra_ray_bundle = e.ray_bundles->at(i); auto& ordi_ray_bundle = o.ray_bundles->at(i); for(int ode_idx=0; ode_idx<=ray_splitting_ode_idx; ode_idx++) { stepper.euler_step_to_boundary( e_seq.odes[ode_idx], extra_ray_bundle); stepper.euler_step_to_boundary( o_seq.odes[ode_idx], ordi_ray_bundle); trans_odes[0] = e_seq.odes[ode_idx]; trans_odes[1] = o_seq.odes[ode_idx]; trans_odes[2] = e_seq.odes[ode_idx+1]; trans_odes[3] = o_seq.odes[ode_idx+1]; // Special method for the ray splitting at the Iso/Aniso // interface if(ode_idx==ray_splitting_ode_idx) trans.update(trans_odes, extra_ray_bundle, ordi_ray_bundle); else { trans.update(trans_odes, extra_ray_bundle); trans.update(trans_odes, ordi_ray_bundle); } } } catch(...) { exc.capture_exception(); } } exc.rethrow(); /************************************************* * Second, we propagate rays inside the LC layer * *************************************************/ double z; Vector<3,std::complex<double> > E_tot; std::complex<double> I(0., 1.); unsigned int node_idx = 0; for(int k=0; k<this->N_lc_steps; k++) { std::cout << "Step " << k+1 << "/" << this->N_lc_steps << ":" << std::endl; if(this->bulk_fields_output || this->bulk_ray_output) { std::cout << " Updating map data..." << std::endl; e.update_map_data(); o.update_map_data(); } if(this->bulk_fields_output) { // We inverse the screen mapping std::cout << " Inversing ray mapping..." << std::endl; std::cout << " Coarse search of inverses..." << std::endl; InverseScreenMap<dim-1> inv_map( e.target_map, *this->coarse_horiz_mesh, screen_domain, this->typical_length, this->hc_parameters); for(int r=0; r<this->N_refinement_cycles; r++) { std::cout << " Refinement of inverses..." << std::endl; inv_map.refine_data(); } auto inv_map_data = inv_map.get_data(); // We reconstruct the field values and save them std::cout << " Reconstructing optical fields..." << std::endl; #pragma omp parallel for firstprivate(E_tot, e, o) for(int hpx_idx=0; hpx_idx<inv_map_data->size(); hpx_idx++) { auto it = inv_map_data->at(hpx_idx); int px_idx = hpx_idx + k*this->N_horiz_pixels; std::vector<Vector<3,std::complex<double> > > E_vals[2]; std::vector<double> optical_length_vals; try { e.get_interpolated_maxwell_fields( it.second, E_vals, optical_length_vals); o.get_interpolated_maxwell_fields( it.first, E_vals, optical_length_vals); for(int wave_idx=0; wave_idx<this->N_wavelengths; wave_idx++) { for(int pol_idx=0; pol_idx<2; pol_idx++) { E_tot = std::complex<double>(0,0); for(int ray=0; ray<E_vals[0].size(); ray++) E_tot += E_vals[pol_idx][ray]*std::exp( I*2.*PI*(optical_length_vals[ray] -this->mat_properties.n_ordi*this->z_step*k) / this->wavelengths[wave_idx]); for(int comp=0; comp<3; comp++) { this->bulk_fields_data->E_real[pol_idx][wave_idx] ->SetComponent(px_idx, comp, std::real(E_tot(comp))); this->bulk_fields_data->E_imag[pol_idx][wave_idx] ->SetComponent(px_idx, comp, std::imag(E_tot(comp))); } } } this->bulk_fields_data->ray_multiplicity->SetComponent( px_idx, 0, E_vals[0].size()); } catch(...) { exc.capture_exception(); } } exc.rethrow(); } if(this->bulk_ray_output) { std::cout << " Interpolating ray data..." << std::endl; #pragma omp parallel for firstprivate(E_tot, e, o) for(int hpx_idx=0; hpx_idx<this->N_horiz_pixels; hpx_idx++) { MultiDimIndex<dim-1> mesh_idx( this->full_horiz_mesh->n_points_per_dim, 0, false); mesh_idx = hpx_idx; Vector<dim-1,double> screen_pos = this->full_horiz_mesh->origin + mesh_idx.get() * this->full_horiz_mesh->cell_lengths; int px_idx = hpx_idx + k*this->N_horiz_pixels; e.save_interpolated_ray_values(px_idx, screen_pos, this->bulk_extra_data); o.save_interpolated_ray_values(px_idx, screen_pos, this->bulk_ordi_data); } } // We evolve the rays to the next z-slice std::cout << " Propagating rays to the next target plane..." << std::endl << std::endl; if(k<this->N_lc_steps-1) { #pragma omp parallel for \ firstprivate(e_seq,o_seq,stepper,trans,z) private(trans_odes) for(int i=0; i<N_rays; i++) { auto& extra_ray_bundle = e.ray_bundles->at(i); auto& ordi_ray_bundle = o.ray_bundles->at(i); int& ode_idx = cur_ode_idx[i]; try { z = - this->lc_thickness/2 + (k+1)*this->z_step; stepper.euler_z_step( e_seq.odes[ode_idx], extra_ray_bundle, s_steps_extra[i], z); stepper.euler_z_step( o_seq.odes[ode_idx], ordi_ray_bundle, s_steps_ordi[i], z); } catch(...) { exc.capture_exception(); } } exc.rethrow(); } else { int ode_idx = ray_splitting_ode_idx+1; #pragma omp parallel for \ firstprivate(e_seq, o_seq, stepper, trans) private(trans_odes) for(int i=0; i<N_rays; i++) { try { auto& extra_ray_bundle = e.ray_bundles->at(i); auto& ordi_ray_bundle = o.ray_bundles->at(i); stepper.euler_step_to_boundary( e_seq.odes[ode_idx], extra_ray_bundle); stepper.euler_step_to_boundary( o_seq.odes[ode_idx], ordi_ray_bundle); trans_odes[0] = e_seq.odes[ode_idx]; trans_odes[1] = o_seq.odes[ode_idx]; trans_odes[2] = e_seq.odes[ode_idx+1]; trans_odes[3] = o_seq.odes[ode_idx+1]; trans.update(trans_odes, extra_ray_bundle); trans.update(trans_odes, ordi_ray_bundle); } catch(...) { exc.capture_exception(); } } exc.rethrow(); } } if(this->bulk_ray_output) { std::cout << "Exporting bulk ray data..." << std::endl; this->bulk_extra_data->write( this->basedir, this->bulk_basename+"_extra_rays.vti"); this->bulk_ordi_data->write( this->basedir, this->bulk_basename+"_ordi_rays.vti"); } if(this->bulk_fields_output) { std::cout << "Exporting bulk optical fields..." << std::endl; this->bulk_fields_data->write( this->basedir, this->bulk_basename+"_fields.vti"); } std::cout << std::endl; /*********************************************************** * Finally, we propagate rays through the upper iso layers * ***********************************************************/ // If we need reconstructed fields on the screen, we reconstruct // the fields locally on a centered focal plane before propagating // fields in Fourier space throught the iso layers if(this->screen_fields_output) { std::cout << "Reconstructing optical fields on the focalisation plane..." << std::endl; // We go to a centered virtual focal plane #pragma omp parallel for firstprivate(stepper) for(int i=0; i<N_rays; i++) { stepper.virtual_z_step(e.ray_bundles->at(i), this->z_foc_1); stepper.virtual_z_step(o.ray_bundles->at(i), this->z_foc_1); } std::cout << " Updating map data..." << std::endl; e.update_map_data(); o.update_map_data(); std::cout << " Inversing ray mapping..." << std::endl; std::cout << " Coarse search of inverses..." << std::endl; InverseScreenMap<dim-1> inv_map( e.target_map, *this->coarse_horiz_mesh, screen_domain, this->typical_length, this->hc_parameters); for(int r=0; r<this->N_refinement_cycles; r++) { std::cout << " Refinement of inverses..." << std::endl; inv_map.refine_data(); } auto inv_map_data = inv_map.get_data(); // We reconstruct the field values and save them std::cout << " Reconstructing optical fields locally..." << std::endl; #pragma omp parallel for firstprivate(E_tot, e, o) for(int hpx_idx=0; hpx_idx<inv_map_data->size(); hpx_idx++) { auto it = inv_map_data->at(hpx_idx); std::vector<Vector<3,std::complex<double> > > E_vals[2]; std::vector<double> optical_length_vals; try { e.get_interpolated_maxwell_fields( it.second, E_vals, optical_length_vals); o.get_interpolated_maxwell_fields( it.first, E_vals, optical_length_vals); for(int wave_idx=0; wave_idx<this->N_wavelengths; wave_idx++) { for(int pol_idx=0; pol_idx<2; pol_idx++) { E_tot = std::complex<double>(0,0); for(int ray=0; ray<E_vals[0].size(); ray++) E_tot += E_vals[pol_idx][ray]*std::exp( I*2.*PI*optical_length_vals[ray] / this->wavelengths[wave_idx]); for(int comp=0; comp<2; comp++) { this->screen_fields_data->E_real[pol_idx][wave_idx]->SetComponent( hpx_idx, comp, std::real(E_tot(comp))); this->screen_fields_data->E_imag[pol_idx][wave_idx]->SetComponent( hpx_idx, comp, std::imag(E_tot(comp))); } this->screen_fields_data->E_real[pol_idx][wave_idx]->SetComponent( hpx_idx, 2, 0); this->screen_fields_data->E_imag[pol_idx][wave_idx]->SetComponent( hpx_idx, 2, 0); } } this->screen_fields_data->ray_multiplicity->SetComponent( hpx_idx, 0, E_vals[0].size()); } catch(...) { exc.capture_exception(); } } exc.rethrow(); std::cout << " Switching to Fourier space to propagate through the iso layers..." << std::endl; this->apply_fourier_iso_layer_filter(); std::cout << " Exporting screen optical fields..." << std::endl << std::endl; this->screen_fields_data->write( this->basedir, this->screen_basename+"_fields.vti"); // We come back inside the first iso layer #pragma omp parallel for firstprivate(stepper) for(int i=0; i<N_rays; i++) { stepper.virtual_z_step(e.ray_bundles->at(i), this->lc_thickness/2+1e-8); stepper.virtual_z_step(o.ray_bundles->at(i), this->lc_thickness/2+1e-8); } } // If we need ray data on the screen, we propagate rays in the usual // way throught the iso layers. if(this->screen_ray_output) { std::cout << "Interpolating ray data on the focalisation plane..." << std::endl; #pragma omp parallel for \ firstprivate(e_seq, o_seq, stepper, trans) private(trans_odes) for(int i=0; i<N_rays; i++) { try { auto& extra_ray_bundle = e.ray_bundles->at(i); auto& ordi_ray_bundle = o.ray_bundles->at(i); for(int ode_idx=ray_splitting_ode_idx+2; ode_idx<e_seq.odes.size()-1; ode_idx++) { stepper.euler_step_to_boundary( e_seq.odes[ode_idx], extra_ray_bundle); stepper.euler_step_to_boundary( o_seq.odes[ode_idx], ordi_ray_bundle); trans_odes[0] = e_seq.odes[ode_idx]; trans_odes[1] = o_seq.odes[ode_idx]; trans_odes[2] = e_seq.odes[ode_idx+1]; trans_odes[3] = o_seq.odes[ode_idx+1]; trans.update(trans_odes, extra_ray_bundle); trans.update(trans_odes, ordi_ray_bundle); } } catch(...) { exc.capture_exception(); } } exc.rethrow(); #pragma omp parallel for firstprivate(stepper) for(int i=0; i<N_rays; i++) { stepper.virtual_z_step(e.ray_bundles->at(i), this->z_foc_2); stepper.virtual_z_step(o.ray_bundles->at(i), this->z_foc_2); } std::cout << " Updating map data..." << std::endl; e.update_map_data(); o.update_map_data(); #pragma omp parallel for firstprivate(E_tot, e, o) for(int hpx_idx=0; hpx_idx<this->N_horiz_pixels; hpx_idx++) { MultiDimIndex<dim-1> mesh_idx( this->full_horiz_mesh->n_points_per_dim, 0, false); mesh_idx = hpx_idx; Vector<dim-1,double> screen_pos = this->full_horiz_mesh->origin + mesh_idx.get() * this->full_horiz_mesh->cell_lengths; e.save_interpolated_ray_values(hpx_idx, screen_pos, this->screen_extra_data); o.save_interpolated_ray_values(hpx_idx, screen_pos, this->screen_ordi_data); } std::cout << " Exporting screen ray data..." << std::endl << std::endl; this->screen_extra_data->write( this->basedir, this->screen_basename+"_extra_rays.vti"); this->screen_ordi_data->write( this->basedir, this->screen_basename+"_ordi_rays.vti"); } } template class FullSampleSimulation<2>; template class FullSampleSimulation<3>;
31.898734
80
0.660516
[ "vector" ]
4da1c65447edf2bbf260810798b89eb9d740a43a
2,989
hpp
C++
include/ui_utils.hpp
Lauriethefish/FishUtils
110815bb316bfb4376cc8306e4eeaf1cfd28727f
[ "Zlib" ]
1
2021-10-17T12:03:40.000Z
2021-10-17T12:03:40.000Z
include/ui_utils.hpp
Lauriethefish/FishUtils
110815bb316bfb4376cc8306e4eeaf1cfd28727f
[ "Zlib" ]
null
null
null
include/ui_utils.hpp
Lauriethefish/FishUtils
110815bb316bfb4376cc8306e4eeaf1cfd28727f
[ "Zlib" ]
null
null
null
#pragma once // Contains useful functions for avoiding repeating code in the FishUtils UI // Also contains a bunch of common UI related includes // I am aware that this is using namespace in a header, but it's only included within UI CPP files that need these namespaces for convenience #include "questui/shared/BeatSaberUI.hpp" #include "questui/shared/CustomTypes/Components/Backgroundable.hpp" #include "questui/shared/CustomTypes/Components/Settings/IncrementSetting.hpp" using namespace QuestUI; #include "HMUI/ViewController_AnimationType.hpp" #include "HMUI/ViewController_AnimationDirection.hpp" #include "HMUI/Touchable.hpp" #include "UnityEngine/UI/VerticalLayoutGroup.hpp" #include "UnityEngine/UI/HorizontalLayoutGroup.hpp" #include "UnityEngine/UI/GridLayoutGroup.hpp" #include "UnityEngine/UI/Toggle.hpp" using namespace UnityEngine::UI; #include "UnityEngine/Transform.hpp" #include "UnityEngine/GameObject.hpp" #include "UnityEngine/RectOffset.hpp" #include "UnityEngine/Resources.hpp" using namespace UnityEngine; #include "TMPro/TextMeshProUGUI.hpp" #include "TMPro/TextAlignmentOptions.hpp" using namespace TMPro; namespace FishUtils::UIUtils { // Creates a decent looking title with a round-rect background on the specified Transform void CreateTitle(Transform* parent, std::string text, std::string hoverHint = ""); // Creates a HorizontalLayoutGroup on transform with childForceExpandWidth set to false and childControlWidth set to true. // Also sets the child alignment to middleCenter so that elements can stack left-to-right without being force-expanded to fit the available space HorizontalLayoutGroup* CreateListLikeHorizontalLayout(Transform* parent); // Creates a VerticalLayoutGroup on transform with childForceExpandHeight set to false and childControlHeight set to true // Also sets the child alignment to upperCenter so that elements can stack up-to-down without being force-expanded to fit the available space VerticalLayoutGroup* CreateListLikeVerticalLayout(Transform* parent); // Creates a horizontal separator line thing to show a divide between two areas of a UI // Blue by default because this is FishCore void CreateSeparatorLine(Transform* parent, Color color = {0, 0.5, 0.5, 1.0}); // Applies a round-rect-panel background using QuestUI's backgroundable void ApplyRectPanelBackground(GameObject* gameObject); // Sets the text of a toggle, by finding the right text mesh void SetToggleText(Toggle* toggle, std::string text); // Sets the value of a toggle, and also calls the notify function, even if the value didn't change void SetToggleForceNotify(Toggle* toggle, bool newValue); // Removes this GameObject then all of its children void RemoveAndChildren(GameObject* gameObject); // Finds the index of value in this dropdown and sets the selected index to that index void SetDropdownValue(HMUI::SimpleTextDropdown* dropdown, std::string value); }
48.209677
149
0.786216
[ "mesh", "transform" ]
4da8b43e69a26f1ec2b8cae4118c0626014a62f6
13,209
cpp
C++
src/build_world.cpp
encelo/ncTracer
fd1340a3c6999eb6f111725be308374d38e3acd0
[ "MIT" ]
null
null
null
src/build_world.cpp
encelo/ncTracer
fd1340a3c6999eb6f111725be308374d38e3acd0
[ "MIT" ]
null
null
null
src/build_world.cpp
encelo/ncTracer
fd1340a3c6999eb6f111725be308374d38e3acd0
[ "MIT" ]
null
null
null
#include "Ortographic.h" #include "PinHole.h" #include "Jittered.h" #include "MultiJittered.h" #include "Hammersley.h" #include "Halton.h" #include "NRooks.h" #include "Sphere.h" #include "Plane.h" #include "Matte.h" #include "Ambient.h" #include "PointLight.h" #include "Phong.h" #include "Reflective.h" #include "Directional.h" #include "AmbientOccluder.h" #include "AreaLight.h" #include "Emissive.h" #include "Rectangle.h" #include "EnvironmentLight.h" #include "Tracer.h" #include <ncine/common_macros.h> #define CORNELL_BOX (1) #if !CORNELL_BOX #define AMBIENT (0) #define AMBIENT_OCCLUSION (1) #define POINT_LIGHTS (1) #define AREA_LIGHTS (0) #define PATH_TRACE (0) #endif namespace { const unsigned int numSamples = 4; std::unique_ptr<pm::Rectangle> rectangleFromVertices(const pm::Vector3 pA, const pm::Vector3 pB, const pm::Vector3 pC) { auto rect = std::make_unique<pm::Rectangle>(pA, pB - pA, pC - pA, cross(pB - pA, pC - pA).normalize()); return rect; } void setupSpheres(pm::World &world, pm::PinHole &camera, pm::Tracer::Type &tracerType) { tracerType = pm::Tracer::Type::AREALIGHTING; camera.editEye().set(0.0f, 2.0f, -8.0f); camera.editUp().set(0.0f, 1.0f, 0.0f); camera.editLookAt().set(0.0f, 2.0f, 0.0f); camera.editViewDistance() = 4.0f; camera.computeUvw(); auto vpSampler = world.createSampler<pm::NRooks>(numSamples); world.viewPlane().setSampler(vpSampler); world.viewPlane().editMaxDepth() = 5; auto hammersley = world.createSampler<pm::Hammersley>(16); #if AMBIENT auto ambient = std::make_unique<pm::Ambient>(); ambient->setRadianceScale(0.01f); world.setAmbientLight(std::move(ambient)); #elif AMBIENT_OCCLUSION auto multiJittered = world.createSampler<pm::MultiJittered>(64); auto ambient = std::make_unique<pm::AmbientOccluder>(); ambient->setRadianceScale(0.01f); ambient->setColor(0.25f, 0.25f, 0.25f); ambient->setMinAmount(0.0f); ambient->setSampler(multiJittered); world.setAmbientLight(std::move(ambient)); #endif auto plane = std::make_unique<pm::Plane>(pm::Vector3(0.0f, 0.0f, 0.0f), pm::Vector3(0.0f, 1.0f, 0.0f)); auto white = std::make_unique<pm::Phong>(); white->setCd(1.0f, 1.0f, 1.0f); white->setKa(0.25f); white->setKd(0.45f); //white->setKs(0.25f); //white->setSpecularExp(32.0f); white->diffuse().setSampler(hammersley); plane->setMaterial(white.get()); world.addObject(std::move(plane)); world.addMaterial(std::move(white)); auto sphere1 = std::make_unique<pm::Sphere>(pm::Vector3(0.0f, 1.0f, 0.0f), 1.0f); auto red = std::make_unique<pm::Phong>(); red->setCd(1.0f, 0.0f, 0.0f); red->setKa(0.25f); red->setKd(0.65f); red->setKs(0.15f); red->setSpecularExp(32.0f); red->diffuse().setSampler(hammersley); sphere1->setMaterial(red.get()); world.addObject(std::move(sphere1)); world.addMaterial(std::move(red)); auto sphere2 = std::make_unique<pm::Sphere>(pm::Vector3(2.0f, 0.5f, 0.0f), 0.5f); auto green = std::make_unique<pm::Phong>(); green->setCd(0.0f, 1.0f, 0.0f); green->setKa(0.1f); green->setKd(0.45f); green->setKs(0.5f); green->setSpecularExp(32.0f); green->diffuse().setSampler(hammersley); sphere2->setMaterial(green.get()); world.addObject(std::move(sphere2)); world.addMaterial(std::move(green)); auto sphere3 = std::make_unique<pm::Sphere>(pm::Vector3(-2.0f, 2.0f, 0.0f), 0.75f); auto blue = std::make_unique<pm::Phong>(); blue->setCd(0.0f, 0.0f, 1.0f); blue->setKa(0.1f); blue->setKd(0.75f); blue->setKs(0.25f); blue->setSpecularExp(24.0f); blue->diffuse().setSampler(hammersley); sphere3->setMaterial(blue.get()); world.addObject(std::move(sphere3)); world.addMaterial(std::move(blue)); #if POINT_LIGHTS auto light1 = std::make_unique<pm::PointLight>(0.0f, 2.0f, -2.0f); //light1->setColor(1.0f, 0.0f, 1.0f); light1->setRadianceScale(0.1f); world.addLight(std::move(light1)); auto light2 = std::make_unique<pm::PointLight>(3.0f, 3.0f, -2.0f); light2->setRadianceScale(0.1f); //light2->setCastShadows(false); //world.addLight(std::move(light2)); auto light3 = std::make_unique<pm::PointLight>(-3.0f, 3.0f, -2.0); light3->setRadianceScale(0.1f); //light3->setColor(0.5f, 1.0f, 0.33f); //light3->setCastShadows(false); //world.addLight(std::move(light3)); auto light4 = std::make_unique<pm::Directional>(-1.0f, 1.0f, 0.0f); light4->setRadianceScale(0.0001f); light4->setColor(0.5f, 1.0f, 0.33f); //light4->setCastShadows(false); //world.addLight(std::move(light4)); #elif AREA_LIGHTS auto emissive = world.createMaterial<pm::Emissive>(); emissive->setRadianceScale(0.25f); auto object = world.createObject<pm::Rectangle>(pm::Vector3(-1.0f, 3.0f, -1.0f), pm::Vector3(2.0f, 0.0f, 0.0f), pm::Vector3(0.0f, 0.0f, 2.0f), pm::Vector3(0.0f, -1.0f, 0.0f)); object->setSampler(hammersley); object->setMaterial(emissive); object->setCastShadows(false); auto light1 = world.createLight<pm::AreaLight>(object); auto object2 = world.createObject<pm::Rectangle>(pm::Vector3(-4.0f, 0.0f, 0.5f), pm::Vector3(0.0f, 1.0f, 0.0f), pm::Vector3(0.0f, 0.0f, 1.0f), pm::Vector3(1.0f, 0.0f, 0.0f)); object2->setSampler(hammersley); object2->setMaterial(emissive); object2->setCastShadows(false); auto light2 = world.createLight<pm::AreaLight>(object2); auto envSampler = world.createSampler<pm::NRooks>(256); auto envEmissive = world.createMaterial<pm::Emissive>(); envEmissive->setRadianceScale(0.1f); envEmissive->setCe(1.0f, 1.0f, 0.6f); auto envlight = world.createLight<pm::EnvironmentLight>(envEmissive); envlight->setSampler(envSampler); #elif PATH_TRACE auto object = std::make_unique<pm::Rectangle>(pm::Vector3(-1.0f, 3.0f, -1.0f), pm::Vector3(2.0f, 0.0f, 0.0f), pm::Vector3(0.0f, 0.0f, 2.0f), pm::Vector3(0.0f, -1.0f, 0.0f)); object->setSampler(hammersley); auto emissive = std::make_unique<pm::Emissive>(); emissive->setRadianceScale(0.25f); //emissive->setCe(1.0f, 0.0f, 0.0f); object->setMaterial(emissive.get()); world.addObject(std::move(object)); world.addMaterial(std::move(emissive)); auto object2 = std::make_unique<pm::Rectangle>(pm::Vector3(-4.0f, 0.0f, 0.5f), pm::Vector3(0.0f, 1.0f, 0.0f), pm::Vector3(0.0f, 0.0f, 1.0f), pm::Vector3(1.0f, 0.0f, 0.0f)); object2->setSampler(hammersley); auto emissive2 = std::make_unique<pm::Emissive>(); emissive2->setRadianceScale(0.2f); //emissive2->setCe(1.0f, 0.0f, 0.0f); object2->setMaterial(emissive2.get()); world.addObject(std::move(object2)); world.addMaterial(std::move(emissive2)); #endif } void setupCornellBox(pm::World &world, pm::PinHole &camera, pm::Tracer::Type &tracerType) { tracerType = pm::Tracer::Type::GLOBALTRACE; camera.editEye().set(278.0f, 273.0f, -800.0f); camera.editUp().set(0.0f, 1.0f, 0.0f); camera.editLookAt().set(278.0f, 273.0f, 0.0f); camera.editViewDistance() = 4.0f; camera.computeUvw(); auto vpSampler = world.createSampler<pm::MultiJittered>(64); world.viewPlane().setSampler(vpSampler); world.viewPlane().editMaxDepth() = 5; auto hammersley = world.createSampler<pm::Hammersley>(64); // Materials auto white = world.createMaterial<pm::Matte>(); white->setCd(0.7f, 0.7f, 0.7f); white->ambient().setSampler(hammersley); white->diffuse().setSampler(hammersley); auto red = world.createMaterial<pm::Matte>(); red->setCd(0.7f, 0.0f, 0.0f); red->ambient().setSampler(hammersley); red->diffuse().setSampler(hammersley); auto green = world.createMaterial<pm::Matte>(); green->setCd(0.0f, 0.7f, 0.0f); green->ambient().setSampler(hammersley); green->diffuse().setSampler(hammersley); auto emissive = world.createMaterial<pm::Emissive>(); // Light auto lightRect = world.createObject<pm::Rectangle>(pm::Vector3(213.0f, 548.79f, 227.0f), pm::Vector3(343.0f - 213.0f, 0.0f, 0.0f), pm::Vector3(0.0f, 0.0f, 332.0f - 227.0f), pm::Vector3(0.0f, -1.0f, 0.0f)); lightRect->setSampler(hammersley); lightRect->setMaterial(emissive); //auto light = world.createLight<pm::AreaLight>(lightRect); // Walls auto floor = world.createObject<pm::Rectangle>(pm::Vector3(0.0f, 0.0f, 0.0f), pm::Vector3(552.8f, 0.0f, 0.0f), pm::Vector3(0.0f, 0.0f, 559.2f), pm::Vector3(0.0f, 1.0f, 0.0f)); floor->setMaterial(white); auto ceiling = world.createObject<pm::Rectangle>(pm::Vector3(0.0f, 548.8f, 0.0f), pm::Vector3(556.0f, 0.0f, 0.0f), pm::Vector3(0.0f, 0.0f, 559.2f), pm::Vector3(0.0f, -1.0f, 0.0f)); ceiling->setMaterial(white); auto leftWall = world.createObject<pm::Rectangle>(pm::Vector3(552.8f, 0.0f, 0.0f), pm::Vector3(0.0f, 548.8f, 0.0f), pm::Vector3(0.0f, 0.0f, 559.2f), pm::Vector3(-1.0f, 0.0f, 0.0f)); leftWall->setMaterial(red); auto rightWall = world.createObject<pm::Rectangle>(pm::Vector3(0.0f, 0.0f, 0.0f), pm::Vector3(0.0f, 548.8f, 0.0f), pm::Vector3(0.0f, 0.0f, 559.2f), pm::Vector3(1.0f, 0.0f, 0.0f)); rightWall->setMaterial(green); auto backWall = world.createObject<pm::Rectangle>(pm::Vector3(0.0f, 0.0f, 559.2f), pm::Vector3(0.0f, 548.8f, 0.0f), pm::Vector3(556.0f, 0.0f, 0.0f), pm::Vector3(0.0f, 0.0f, -1.0f)); backWall->setMaterial(white); // Short object auto short1 = rectangleFromVertices(pm::Vector3(130.0f, 165.0f, 65.0f), pm::Vector3(82.0f, 165.0f, 225.0f), pm::Vector3(290.0f, 165.0f, 114.0f)); short1->setMaterial(white); world.addObject(std::move(short1)); auto short2 = rectangleFromVertices(pm::Vector3(290.0f, 0.0f, 114.0f), pm::Vector3(290.0f, 165.0f, 114.0f), pm::Vector3(240.0f, 0.0f, 272.0f)); short2->setMaterial(white); world.addObject(std::move(short2)); auto short3 = rectangleFromVertices(pm::Vector3(130.0f, 0.0f, 65.0f), pm::Vector3(130.0f, 165.0f, 65.0f), pm::Vector3(290.0f, 0.0f, 114.0f)); short3->setMaterial(white); world.addObject(std::move(short3)); auto short4 = rectangleFromVertices(pm::Vector3(82.0f, 0.0f, 225.0f), pm::Vector3(82.0f, 165.0f, 225.0f), pm::Vector3(130.0f, 0.0f, 65.0f)); short4->setMaterial(white); world.addObject(std::move(short4)); auto short5 = rectangleFromVertices(pm::Vector3(240.0f, 0.0f, 272.0f), pm::Vector3(240.0f, 165.0f, 272.0f), pm::Vector3(82.0f, 0.0f, 225.0f)); short5->setMaterial(white); world.addObject(std::move(short5)); // Tall object auto tall1 = rectangleFromVertices(pm::Vector3(423.0f, 330.0f, 247.0f), pm::Vector3(265.0f, 330.0f, 296.0f), pm::Vector3(472.0f, 330.0f, 406.0f)); tall1->setMaterial(white); world.addObject(std::move(tall1)); auto tall2 = rectangleFromVertices(pm::Vector3(423.0f, 0.0f, 247.0f), pm::Vector3(423.0f, 330.0f, 247.0f), pm::Vector3(472.0f, 0.0f, 406.0f)); tall2->setMaterial(white); world.addObject(std::move(tall2)); auto tall3 = rectangleFromVertices(pm::Vector3(472.0f, 0.0f, 406.0f), pm::Vector3(472.0f, 330.0f, 406.0f), pm::Vector3(314.0f, 0.0f, 456.0f)); tall3->setMaterial(white); world.addObject(std::move(tall3)); auto tall4 = rectangleFromVertices(pm::Vector3(314.0f, 0.0f, 456.0f), pm::Vector3(314.0f, 330.0f, 456.0f), pm::Vector3(265.0f, 0.0f, 296.0f)); tall4->setMaterial(white); world.addObject(std::move(tall4)); auto tall5 = rectangleFromVertices(pm::Vector3(265.0f, 0.0f, 296.0f), pm::Vector3(265.0f, 330.0f, 296.0f), pm::Vector3(423.0f, 0.0f, 247.0f)); tall5->setMaterial(white); world.addObject(std::move(tall5)); } void validateWorld(const pm::World &world) { if (world.viewPlane().samplerState().sampler() == nullptr) { LOGE("Missing viewplane sampler!"); exit(EXIT_FAILURE); } for (const auto &object : world.objects()) { if (object->material() == nullptr) { LOGE("Missing material!"); exit(EXIT_FAILURE); } } for (const auto &material : world.materials()) { if (material->type() == pm::Material::Type::MATTE) { const pm::Matte *matte = static_cast<pm::Matte *>(material.get()); if (matte->ambient().sampler() == nullptr) { LOGE("Missing ambient sampler from matte material!"); exit(EXIT_FAILURE); } else if (matte->diffuse().sampler() == nullptr) { LOGE("Missing diffuse sampler from matte material!"); exit(EXIT_FAILURE); } } else if (material->type() == pm::Material::Type::PHONG) { const pm::Phong *phong = static_cast<pm::Phong *>(material.get()); if (phong->ambient().sampler() == nullptr) { LOGE("Missing ambient sampler from phong material!"); exit(EXIT_FAILURE); } else if (phong->diffuse().sampler() == nullptr) { LOGE("Missing diffuse sampler from phong material!"); exit(EXIT_FAILURE); } else if (phong->specular().sampler() == nullptr) { LOGE("Missing specular sampler from phong material!"); exit(EXIT_FAILURE); } } } } } void initWorld(pm::World &world, pm::PinHole &camera, pm::Tracer::Type &tracerType) { world.viewPlane().editPixelSize() = 0.004f; #if CORNELL_BOX setupCornellBox(world, camera, tracerType); #else setupSpheres(world, camera, tracerType); #endif validateWorld(world); LOGI_X("Scene statistics: %u objects, %u materials, %u lights, %u samplers", world.objects().size(), world.materials().size(), world.lights().size(), world.samplers().size()); #if 0 //pm::Ortographic camera; world.viewPlane().setPixelSize(0.005f); pm::PinHole camera; camera.setEye(0.0f, 1.0f, -5.0f); camera.setUp(0.0f, 1.0f, 0.0f); camera.setLookAt(0.0f, 1.0f, 0.0f); camera.setViewDistance(4.0f); camera.computeUvw(); camera.setExposureTime(1.0f); #endif }
35.412869
206
0.688319
[ "object" ]
4da935cd3b387a6f0155430190c10bd8ab0b371f
3,883
hpp
C++
includes/Terra.hpp
razerx100/Terra
a30738149cb07325283c2da9ac7972f079cb4dbc
[ "MIT" ]
null
null
null
includes/Terra.hpp
razerx100/Terra
a30738149cb07325283c2da9ac7972f079cb4dbc
[ "MIT" ]
null
null
null
includes/Terra.hpp
razerx100/Terra
a30738149cb07325283c2da9ac7972f079cb4dbc
[ "MIT" ]
null
null
null
#ifndef TERRA_HPP_ #define TERRA_HPP_ #include <IThreadPool.hpp> #include <DebugLayerManager.hpp> #include <CommandPoolManager.hpp> #include <DeviceManager.hpp> #include <VKInstanceManager.hpp> #include <GraphicsQueueManager.hpp> #include <ISurfaceManager.hpp> #include <SwapChainManager.hpp> #include <IDisplayManager.hpp> #include <CopyQueueManager.hpp> #include <ResourceBuffer.hpp> #include <ViewportAndScissorManager.hpp> #include <RenderPassManager.hpp> #include <DescriptorSetManager.hpp> #include <TextureStorage.hpp> #include <DepthBuffer.hpp> #include <memory> #include <ModelContainer.hpp> #include <ISharedDataContainer.hpp> #include <CameraManager.hpp> namespace Terra { // Variables extern std::shared_ptr<IThreadPool> threadPool; extern std::unique_ptr<DebugLayerManager> debugLayer; extern std::unique_ptr<CommandPoolManager> graphicsCmdPool; extern std::unique_ptr<CommandPoolManager> copyCmdPool; extern std::unique_ptr<DeviceManager> device; extern std::unique_ptr<InstanceManager> vkInstance; extern std::unique_ptr<GraphicsQueueManager> graphicsQueue; extern std::unique_ptr<CopyQueueManager> copyQueue; extern std::unique_ptr<SwapChainManager> swapChain; extern std::unique_ptr<IDisplayManager> display; extern std::unique_ptr<ISurfaceManager> surface; extern std::unique_ptr<ResourceBuffer> vertexBuffer; extern std::unique_ptr<ResourceBuffer> indexBuffer; extern std::unique_ptr<HostAccessibleBuffers> uniformBuffer; extern std::unique_ptr<ViewportAndScissorManager> viewportAndScissor; extern std::unique_ptr<RenderPassManager> renderPass; extern std::unique_ptr<ModelContainer> modelContainer; extern std::unique_ptr<DescriptorSetManager> descriptorSet; extern std::unique_ptr<TextureStorage> textureStorage; extern std::unique_ptr<CameraManager> cameraManager; extern std::unique_ptr<DepthBuffer> depthBuffer; extern std::shared_ptr<ISharedDataContainer> sharedData; // Initialization functions void SetThreadPool(std::shared_ptr<IThreadPool>&& threadPoolArg) noexcept; void InitDebugLayer(VkInstance instance); void InitGraphicsCmdPool( VkDevice logicalDevice, size_t queueIndex, std::uint32_t bufferCount ); void InitCopyCmdPool( VkDevice logicalDevice, size_t queueIndex ); void InitDevice(); void InitVkInstance(const char* appName); void InitGraphicsQueue( VkDevice logicalDevice, VkQueue queue, std::uint32_t bufferCount ); void InitCopyQueue( VkDevice logicalDevice, VkQueue queue ); void InitSwapChain( const SwapChainManagerCreateInfo& swapCreateInfo, VkQueue presentQueue, size_t queueFamilyIndex ); void InitDisplay(); void InitSurface(VkInstance instance, void* windowHandle, void* moduleHandle); void InitVertexBuffer( VkDevice logicalDevice, VkPhysicalDevice physicalDevice, const std::vector<std::uint32_t>& queueFamilyIndices ); void InitIndexBuffer( VkDevice logicalDevice, VkPhysicalDevice physicalDevice, const std::vector<std::uint32_t>& queueFamilyIndices ); void InitUniformBuffer( VkDevice logicalDevice, VkPhysicalDevice physicalDevice ); void InitViewportAndScissor(std::uint32_t width, std::uint32_t height); void InitRenderPass( VkDevice logicalDevice, VkFormat swapChainFormat, VkFormat depthFormat ); void InitModelContainer( const std::string& shaderPath, VkDevice logicalDevice ); void InitDescriptorSet(VkDevice logicalDevice); void InitTextureStorage( VkDevice logicalDevice, VkPhysicalDevice physicalDevice, const std::vector<std::uint32_t>& queueFamilyIndices ); void InitCameraManager(); void InitDepthBuffer( VkDevice logicalDevice, VkPhysicalDevice physicalDevice, const std::vector<std::uint32_t>& queueFamilyIndices ); void SetSharedData(std::shared_ptr<ISharedDataContainer>&& sharedDataArg) noexcept; } #endif
36.632075
85
0.791913
[ "vector" ]
4da9f9d6e9c5b9bc36a2dab57639b28a710b7fb4
2,031
hpp
C++
engine/include/storm/engine/render/utils/RingHardwareBuffer.hpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
17
2019-02-12T14:40:06.000Z
2021-12-21T12:54:17.000Z
engine/include/storm/engine/render/utils/RingHardwareBuffer.hpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
null
null
null
engine/include/storm/engine/render/utils/RingHardwareBuffer.hpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
2
2019-02-21T10:07:42.000Z
2020-05-08T19:49:10.000Z
// Copyright (C) 2021 Arthur LAURENT <arthur.laurent4@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level of this distribution #pragma once /////////// - StormKit::core - /////////// #include <storm/core/NonCopyable.hpp> #include <storm/core/Platform.hpp> #include <storm/core/RingBuffer.hpp> /////////// - StormKit::render - /////////// #include <storm/render/Fwd.hpp> #include <storm/render/core/Enums.hpp> #include <storm/render/resource/HardwareBuffer.hpp> namespace storm::engine { class STORMKIT_PUBLIC RingHardwareBuffer { public: RingHardwareBuffer(core::ArraySize count, const render::Device &device, render::HardwareBufferUsage usage, core::ArraySize byte_count, render::MemoryProperty property = render::MemoryProperty::Host_Visible | render::MemoryProperty::Device_Local); ~RingHardwareBuffer(); RingHardwareBuffer(RingHardwareBuffer &&) noexcept; RingHardwareBuffer &operator=(RingHardwareBuffer &&) noexcept; void next(); core::Byte *map(core::UInt32 offset); void unmap(); template<typename T> void upload(core::span<const T> data, core::Int32 offset = 0); render::HardwareBuffer &buffer(); const render::HardwareBuffer &buffer() const noexcept; core::ArraySize count() const noexcept; core::ArraySize elementSize() const noexcept; core::ArraySize size() const noexcept; core::Int32 currentOffset() const noexcept; DEVICE_CONST_GETTER private: render::DeviceConstRef m_device; core::ArraySize m_count = 0u; core::ArraySize m_element_size = 0u; core::Int32 m_offset = 0u; render::HardwareBufferOwnedPtr m_buffer; }; } // namespace storm::engine #include "RingHardwareBuffer.inl"
33.85
99
0.616445
[ "render" ]
4dbf34a71ecddd990bab1746ba3b4e2c048de810
1,637
cpp
C++
PlatformTestSDL2/PlatformTestSDL2/PlayerState_Fall.cpp
MitchellHodzen/SDL2PlatformEngine
d4fccf4595360d6cd7c3ab184b6231f8338b4fb0
[ "MIT" ]
null
null
null
PlatformTestSDL2/PlatformTestSDL2/PlayerState_Fall.cpp
MitchellHodzen/SDL2PlatformEngine
d4fccf4595360d6cd7c3ab184b6231f8338b4fb0
[ "MIT" ]
null
null
null
PlatformTestSDL2/PlatformTestSDL2/PlayerState_Fall.cpp
MitchellHodzen/SDL2PlatformEngine
d4fccf4595360d6cd7c3ab184b6231f8338b4fb0
[ "MIT" ]
null
null
null
#include "PlayerState_Fall.h" //Transition Classes: #include "PlayerState_WallSlide.h" PlayerState_Fall::PlayerState_Fall() { } PlayerState_Fall::~PlayerState_Fall() { } void PlayerState_Fall::Enter(Player& player) { //std::cout << "Enter Fall" << std::endl; } void PlayerState_Fall::Exit() { //std::cout << "Exit Fall" << std::endl; } PlayerState* PlayerState_Fall::Update(Player& player, std::vector<Entity*> entityList) { if (player.GetVelocityY() > 0) { player.SetAnimation(Animations::PlayerAnimations::Fall); } if (!PlayerState_Airborne::movingHorizontal) { player.ApplyHorizontalFriction(); } player.ApplyGravity(); player.ApplyInternalForces(); //player.HandleWallSliding(); Direction collisionDirection = player.MoveHorizontal(entityList); if (player.GetVelocityY() > 0) { if (collisionDirection == Direction::LEFT) { return Transition(player, new PlayerState_WallSlide(collisionDirection)); } if (collisionDirection == Direction::RIGHT) { return Transition(player, new PlayerState_WallSlide(collisionDirection)); } } return PlayerState_Airborne::Update(player, entityList); } PlayerState* PlayerState_Fall::GetInput(Player& player, PlayerActions action, InputType type) { if (type != InputType::RELEASED) { switch(action) { case PlayerActions::JUMP: //player.SetNewVelocityY(-player.GetMaxJumpSpeed()); break; default: break; } } return PlayerState_Airborne::GetInput(player, action, type); }
24.073529
93
0.657911
[ "vector" ]
4dc1da221303692a6cf734a68c7ad1e0f8f4014b
87,559
hpp
C++
cloud_codec_v2/include/pcl/cloud_codec_v2/impl/point_cloud_codec_v2_impl.hpp
cwi-dis/cwipc_codec
35c3663c81e90183e0d353505c81175f04ab9022
[ "MIT" ]
null
null
null
cloud_codec_v2/include/pcl/cloud_codec_v2/impl/point_cloud_codec_v2_impl.hpp
cwi-dis/cwipc_codec
35c3663c81e90183e0d353505c81175f04ab9022
[ "MIT" ]
null
null
null
cloud_codec_v2/include/pcl/cloud_codec_v2/impl/point_cloud_codec_v2_impl.hpp
cwi-dis/cwipc_codec
35c3663c81e90183e0d353505c81175f04ab9022
[ "MIT" ]
null
null
null
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2009-2012, Willow Garage, Inc. * Copyright (c) 2014, Stichting Centrum Wiskunde en Informatica. * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #ifndef POINT_CLOUD_CODECV2_IMPL_HPP #define POINT_CLOUD_CODECV2_IMPL_HPP // STL Containers containing fixed-size vectorizable Eigen types need aligned_allocator<...> // see: http://eigen.tuxfamily.org/dox-devel/group__TopicStlContainers.html #include <Eigen/StdVector> // point cloud compression from PCL #ifdef PCL_INSTALLED #include <pcl/io/impl/octree_pointcloud_compression.hpp> #include <pcl/io/impl/entropy_range_coder.hpp> #else //PCL_INSTALLED #include <pcl/compression/impl/octree_pointcloud_compression.hpp> #include <pcl/compression/impl/entropy_range_coder.hpp> #endif//PCL_INSTALLED #include <pcl/cloud_codec_v2/point_cloud_codec_v2.h> #include <pcl/compression/point_coding.h> #include <pcl/filters/radius_outlier_removal.h> #if defined(_OPENMP) #include <omp.h> #endif//defined(_OPENMP) //includes to do the ICP procedures #include <pcl/point_types.h> #include <pcl/registration/icp.h> #include <Eigen/Geometry> #include <pcl/cloud_codec_v2/impl/rigid_transform_coding_impl.hpp> namespace pcl{ namespace io{ /** * \brief encoding routing based on overriding pcl octree codec written by Julius Kammerl * extra features include * - centroid coding * - color coding based on jpeg * - scalable bitstream (not yet implemented) * \author Rufael Mekuria rufael.mekuria@cwi.nl * \param cloud_arg * \param compressed_tree_data_out_arg */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2< PointT, LeafT, BranchT, OctreeT>::encodePointCloud ( const PointCloudConstPtr &cloud_arg, std::ostream& compressed_tree_data_out_arg, uint64_t timeStamp) { unsigned char recent_tree_depth = static_cast<unsigned char> (getTreeDepth ()); #ifdef CWIPC_CODEC_DELETE_BUFFER_IN_ENCODER // CWI addition to prevent crashes as in original cloud codec deleteCurrentBuffer(); #endif #ifdef CWIPC_CODEC_DELETE_TREE_IN_ENCODER // // xxxjack tried to remove this code: it isn't in the original // octree_pointcloud_compression and removing it gives a significant // performance update. // However, removing it results in a crash on Windows, after encoding // around 50 tiled pointclouds of the loot 150Kpoint set. // deleteTree(); #endif // initialize octree setInputCloud (cloud_arg); #ifdef xxxjack_removed_suspect_code // CWI added, when encoding hte output variable stores the (simplified icloud) output_ = PointCloudPtr(new PointCloud()); #else // Added by Jack. We initialize the output_ pointcloud only if we want to do I and P frames if (i_frame_rate_ > 1) { output_ = PointCloudPtr(new PointCloud()); } else { output_ = nullptr; } #endif // add point to octree addPointsFromInputCloud (); // make sure cloud contains points if (leaf_count_ > 0) { // color field analysis cloud_with_color_ = false; std::vector<pcl::PCLPointField> fields; int rgba_index = -1; rgba_index = pcl::getFieldIndex<PointT>("rgb", fields); if (rgba_index == -1) { rgba_index = pcl::getFieldIndex<PointT>("rgba", fields); } if (rgba_index >= 0) { point_color_offset_ = static_cast<unsigned char> (fields[rgba_index].offset); cloud_with_color_ = true; } // apply encoding configuration cloud_with_color_ &= do_color_encoding_; // if octree depth changed, we enforce I-frame encoding i_frame_ |= (recent_tree_depth != getTreeDepth ());// | !(iFrameCounter%10); // enable I-frame rate if (i_frame_counter_++==i_frame_rate_) { i_frame_counter_ =0; i_frame_ = true; } // increase frameID frame_ID_++; // do octree encoding if (!do_voxel_grid_enDecoding_) { point_count_data_vector_.clear (); point_count_data_vector_.reserve (cloud_arg->points.size ()); } // initialize color encoding (including new color coding based on jpeg) if(!color_coding_type_){ color_coder_.initializeEncoding (); color_coder_.setPointCount (static_cast<unsigned int> (cloud_arg->points.size ())); color_coder_.setVoxelCount (static_cast<unsigned int> (leaf_count_)); } else { // new jpeg color coding jp_color_coder_.initializeEncoding (); jp_color_coder_.setPointCount (static_cast<unsigned int> (cloud_arg->points.size ())); jp_color_coder_.setVoxelCount (static_cast<unsigned int> (leaf_count_)); } // initialize point encoding (including new centroid encoder) point_coder_.initializeEncoding (); centroid_coder_.initializeEncoding (); point_coder_.setPointCount (static_cast<unsigned int> (cloud_arg->points.size ())); centroid_coder_.initializeEncoding (); centroid_coder_.setPointCount( static_cast<unsigned int> (object_count_)); // serialize octree if (i_frame_) { // i-frame encoding - encode tree structure without referencing previous buffer serializeTree (binary_tree_data_vector_); } else { #ifdef CWIPC_CODEC_WITH_SINGLE_BUF abort(); #else // p-frame encoding - XOR encoded tree structure serializeTree (binary_tree_data_vector_, true); #endif } // write frame header information to stream writeFrameHeader (compressed_tree_data_out_arg, timeStamp); // apply entropy coding to the content of all data vectors and send data to output stream entropyEncoding(compressed_tree_data_out_arg, compressed_tree_data_out_arg); #ifndef CWIPC_CODEC_WITH_SINGLE_BUF switchBuffers(); #endif // reset object count object_count_ = 0; if (b_show_statistics_) // todo update for codec v2 { float bytes_per_XYZ = static_cast<float> (compressed_point_data_len_) / static_cast<float> (point_count_); float bytes_per_color = static_cast<float> (compressed_color_data_len_) / static_cast<float> (point_count_); PCL_INFO ("*** POINTCLOUD ENCODING ***\n"); PCL_INFO ("Frame ID: %d\n", frame_ID_); if (i_frame_) PCL_INFO ("Encoding Frame: Intra frame\n"); else PCL_INFO ("Encoding Frame: Prediction frame\n"); PCL_INFO ("Number of encoded points: %ld\n", point_count_); PCL_INFO ("XYZ compression percentage: %f%%\n", bytes_per_XYZ / (3.0f * sizeof(float)) * 100.0f); PCL_INFO ("XYZ bytes per point: %f bytes\n", bytes_per_XYZ); PCL_INFO ("Color compression percentage: %f%%\n", bytes_per_color / (sizeof (int)) * 100.0f); PCL_INFO ("Color bytes per point: %f bytes\n", bytes_per_color); PCL_INFO ("Size of uncompressed point cloud: %f kBytes\n", static_cast<float> (point_count_) * (sizeof (int) + 3.0f * sizeof (float)) / 1024); PCL_INFO ("Size of compressed point cloud: %d kBytes\n", (compressed_point_data_len_ + compressed_color_data_len_) / (1024)); PCL_INFO ("Total bytes per point: %f\n", bytes_per_XYZ + bytes_per_color); PCL_INFO ("Total compression percentage: %f\n", (bytes_per_XYZ + bytes_per_color) / (sizeof (int) + 3.0f * sizeof(float)) * 100.0f); PCL_INFO ("Compression ratio: %f\n\n", static_cast<float> (sizeof (int) + 3.0f * sizeof (float)) / static_cast<float> (bytes_per_XYZ + bytes_per_color)); } } else { if (b_show_statistics_) PCL_INFO ("Info: Dropping empty point cloud\n"); #ifdef xxxjack_removed_suspect_code deleteTree(); #endif i_frame_counter_ = 0; i_frame_ = true; } } /** * \brief decoding routing based on overriding pcl octree codec written by Julius Kammerl * extra features include * - centroid coding * - color coding based on jpeg * \author Rufael Mekuria rufael.mekuria@cwi.nl * \param compressed_tree_data_in_arg * \param cloud_arg decoded point cloud */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> bool OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::decodePointCloud ( std::istream& compressed_tree_data_in_arg, PointCloudPtr &cloud_arg, std::uint64_t &timeStamp) { //std::cout << "\n Entered cloud codec v2 \n"; //std::cout << "\n Size of compressed frame" << sizeof(compressed_tree_data_in_arg); // synchronize to frame header if (!syncToHeader(compressed_tree_data_in_arg)) return false; //std::cout << "\n Header synced \n"; #if 0 // initialize octree switchBuffers (); // added to prevent crashes as happens with original cloud codec deleteCurrentBuffer(); #endif deleteTree(); setOutputCloud (cloud_arg); //std::cout << " \n Octree buffers switched \n"; // color field analysis cloud_with_color_ = false; std::vector<pcl::PCLPointField> fields; int rgba_index = -1; rgba_index = pcl::getFieldIndex<PointT>("rgb", fields); if (rgba_index == -1) rgba_index = pcl::getFieldIndex<PointT>("rgba", fields); if (rgba_index >= 0) { point_color_offset_ = static_cast<unsigned char> (fields[rgba_index].offset); cloud_with_color_ = true; } // read header from input stream readFrameHeader (compressed_tree_data_in_arg, timeStamp); //TO DO Shishir: Set codec parameteres from frame header before decoding // //this->octree_resolution_ = octreeResolution; //this->color_bit_resolution_ = colorBitResolution; //this->jpeg_quality_ = jpeg_quality; //std::cout << "\n Frame header read \n "; // set the right grid pattern to the JPEG coder jp_color_coder_ = ColorCodingJPEG<PointT>(75,color_coding_type_); // decode data vectors from stream entropyDecoding(compressed_tree_data_in_arg, compressed_tree_data_in_arg); //std::cout << "\n Entropy coding done \n"; // initialize color and point encoding if(!color_coding_type_) color_coder_.initializeDecoding (); else jp_color_coder_.initializeDecoding (); point_coder_.initializeDecoding (); centroid_coder_.initializeDecoding(); // initialize output cloud output_->points.clear (); output_->points.reserve (static_cast<std::size_t> (point_count_)); //std::cout << "\n Starting to deserialize \n"; if (i_frame_) { // i-frame decoding - decode tree structure without referencing previous buffer deserializeTree (binary_tree_data_vector_); } else { #ifdef CWIPC_CODEC_WITH_SINGLE_BUF abort(); #else // p-frame decoding - decode XOR encoded tree structure deserializeTree (binary_tree_data_vector_, true); #endif } // assign point cloud properties output_->height = 1; output_->width = static_cast<uint32_t> (cloud_arg->points.size ()); output_->is_dense = false; //std::cout << "\n Pointcloud properties assigned \n"; if (b_show_statistics_) { float bytes_per_XYZ = static_cast<float> (compressed_point_data_len_) / static_cast<float> (point_count_); float bytes_per_color = static_cast<float> (compressed_color_data_len_) / static_cast<float> (point_count_); PCL_INFO ("*** POINTCLOUDV2 DECODING ***\n"); PCL_INFO ("Frame ID: %d\n", frame_ID_); if (i_frame_) PCL_INFO ("Encoding Frame: Intra frame\n"); else PCL_INFO ("Encoding Frame: Prediction frame\n"); PCL_INFO ("Number of encoded points: %ld\n", point_count_); PCL_INFO ("XYZ compression percentage: %f%%\n", bytes_per_XYZ / (3.0f * sizeof (float)) * 100.0f); PCL_INFO ("XYZ bytes per point: %f bytes\n", bytes_per_XYZ); PCL_INFO ("Color compression percentage: %f%%\n", bytes_per_color / (sizeof (int)) * 100.0f); PCL_INFO ("Color bytes per point: %f bytes\n", bytes_per_color); PCL_INFO ("Size of uncompressed point cloud: %f kBytes\n", static_cast<float> (point_count_) * (sizeof (int) + 3.0f * sizeof (float)) / 1024.0f); PCL_INFO ("Size of compressed point cloud: %f kBytes\n", static_cast<float> (compressed_point_data_len_ + compressed_color_data_len_) / 1024.0f); PCL_INFO ("Total bytes per point: %d bytes\n", static_cast<int> (bytes_per_XYZ + bytes_per_color)); PCL_INFO ("Total compression percentage: %f%%\n", (bytes_per_XYZ + bytes_per_color) / (sizeof (int) + 3.0f * sizeof (float)) * 100.0f); PCL_INFO ("Compression ratio: %f\n\n", static_cast<float> (sizeof (int) + 3.0f * sizeof (float)) / static_cast<float> (bytes_per_XYZ + bytes_per_color)); } //std::cout << "\nDecoding done\n"; return true; } /** * \brief helper function to compute the delta frames * \author Rufael Mekuria rufael.mekuria@cwi.nl * \param pcloud_arg_in input point cloud to simplify * \param out_cloud output simplified point cloud */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT,LeafT,BranchT,OctreeT>::simplifyPCloud(const PointCloudConstPtr &pcloud_arg_in, PointCloudPtr &out_cloud ) { // this is the octree coding part of the predictive encoding OctreePointCloudCodecV2<PointT,LeafT,BranchT,OctreeT> *octree_simplifier = new OctreePointCloudCodecV2<PointT,LeafT,BranchT,OctreeT> ( MANUAL_CONFIGURATION, false, point_resolution_, octree_resolution_, true, 0, true, color_bit_resolution_ /*,0,do_voxel_centroid_enDecoding_*/ ); // use bounding box and obtain the octree grid octree_simplifier->defineBoundingBox(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); octree_simplifier->setInputCloud (pcloud_arg_in); octree_simplifier->addPointsFromInputCloud (); ///////////////////////////////////////////////////////////////////////// //! initialize output cloud //PointCloudPtr out_cloud(new PointCloud( octree_simplifier.leaf_count_, 1)); out_cloud->width = (uint32_t) octree_simplifier->getLeafCount(); out_cloud->height = 1; out_cloud->points.reserve(octree_simplifier->getLeafCount()); // cant get access to the number of leafs //////////////////////////////////////////////////////////////////////////// ///////////// compute the simplified cloud by iterating the octree //////// #if PCL_VERSION >= 100901 octree::OctreeDepthFirstIterator<OctreeT> it_ = octree_simplifier->leaf_depth_begin(); for (int l_index = 0; *it_; it_++, l_index++) { if (it_.isBranchNode()) continue; #else//PCL_VERSION >= 100901 octree::OctreeDepthFirstIterator<OctreeT> it_ = octree_simplifier->leaf_begin(); octree::OctreeLeafNodeIterator<OctreeT> it_end = octree_simplifier->leaf_end(); for(int l_index =0;it_ !=it_end; it_++, l_index++) { #endif//PCL_VERSION >= 100901 // new point for the simplified cloud PointT l_new_point; //! centroid for storage std::vector<int>& point_indices = it_.getLeafContainer().getPointIndicesVector(); // if centroid coding, store centroid, otherwise add if(!do_voxel_centroid_enDecoding_) { octree_simplifier->genLeafNodeCenterFromOctreeKey(it_.getCurrentOctreeKey(),l_new_point); } else { Eigen::Vector4f cent; pcl::compute3DCentroid<PointT>(*pcloud_arg_in, point_indices, cent); l_new_point.x = cent[0]; l_new_point.y = cent[1]; l_new_point.z = cent[2]; } long color_r=0; long color_g=0; long color_b=0; //! compute average color for(int i=0; i< point_indices.size();i++) { color_r+=pcloud_arg_in->points[point_indices[i]].r; color_g+=pcloud_arg_in->points[point_indices[i]].g; color_b+=pcloud_arg_in->points[point_indices[i]].b; } l_new_point.r = (char) (color_r / point_indices.size()); l_new_point.g = (char) (color_g / point_indices.size()); l_new_point.b = (char) (color_b / point_indices.size()); out_cloud->points.push_back(l_new_point); } //////////////// done computing simplified cloud and octree structure ////////////////// delete octree_simplifier; }; /*! * \brief helper function to generate macroblock tree for computing shared macroblocks * \author Rufael Mekuria rufael.mekuria@cwi.nl * \param in_cloud input point cloud * \return pointer to a macroblock tree structure */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> OctreePointCloudCompression<PointT,LeafT,BranchT,OctreeT> * OctreePointCloudCodecV2<PointT,LeafT,BranchT,OctreeT>::generate_macroblock_tree(PointCloudConstPtr in_cloud) { MacroBlockTree *tree = new MacroBlockTree ( MANUAL_CONFIGURATION, false, point_resolution_, octree_resolution_ * macroblock_size_, true, 0, true, color_bit_resolution_ /*,0,do_voxel_centroid_enDecoding_*/ ); // I frame coder tree->defineBoundingBox(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); tree->setInputCloud (in_cloud); /* assume right argument was given, either the original p cloud or an i cloud */ tree->addPointsFromInputCloud (); return tree; } /*! * \brief helper function to do ICP prediction between shared macroblocks * \author Rufael Mekuria rufael.mekuria@cwi.nl * \param i_cloud macroblock icloud * \param p_cloud macroblock pcloud * \param rigid_transform output rigid transform * \param has_converged true if converged otherwise false * \param rgb_offsets values for rgb offsets (if enabled) * pointer to a macroblock tree structure */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT,LeafT,BranchT,OctreeT>::do_icp_prediction( Eigen::Matrix4f& rigid_transform, PointCloudPtr i_cloud, PointCloudPtr p_cloud, bool & has_converged, char *rgb_offsets ) { // check if it makes sense to do icp, i.e. input and output points approx. equal bool do_icp = p_cloud->size() > 6 ? (p_cloud->size() < i_cloud->size() * 2) && (p_cloud->size() >= i_cloud->size() * 0.5) : false; if(!do_icp) { has_converged = false; return; } // color variance filter double in_av[3]={0,0,0}; double out_av[3]={0,0,0}; double in_var=0; double out_var=0; if(do_icp) { // create references to ease acccess via [] operator in the cloud pcl::PointCloud<PointT> & rcloud_out = *p_cloud; pcl::PointCloud<PointT> & rcloud_in = *i_cloud; for(int i=0; i<rcloud_in.size();i++) { in_av[0]+= (double) rcloud_in[i].r; in_av[1]+= (double) rcloud_in[i].g; in_av[2]+= (double) rcloud_in[i].b; } in_av[0]/=rcloud_in.size(); in_av[1]/=rcloud_in.size(); in_av[2]/=rcloud_in.size(); // variance for(int i=0; i<rcloud_in.size();i++) { double val= (rcloud_in[i].r - in_av[0]) * (rcloud_in[i].r - in_av[0]) + (rcloud_in[i].g - in_av[1]) * (rcloud_in[i].g - in_av[1]) + (rcloud_in[i].b - in_av[2]) * (rcloud_in[i].b - in_av[2]); in_var+=val; } in_var/=(3*rcloud_in.size()); // for(int i=0; i<rcloud_out.size();i++) { out_av[0]+= (double) rcloud_out[i].r; out_av[1]+= (double) rcloud_out[i].g; out_av[2]+= (double) rcloud_out[i].b; } out_av[0]/=rcloud_out.size(); out_av[1]/=rcloud_out.size(); out_av[2]/=rcloud_out.size(); for(int i=0; i<rcloud_out.size();i++) { double val= (rcloud_out[i].r - out_av[0]) * (rcloud_out[i].r - out_av[0]) + (rcloud_out[i].g - out_av[1]) * (rcloud_out[i].g - out_av[1]) + (rcloud_out[i].b - out_av[2]) * (rcloud_out[i].b - out_av[2]); out_var+=val; } out_var/=(3*rcloud_out.size()); // for segments with large variance, skip the icp prediction if(in_var > icp_var_threshold_ || out_var > icp_var_threshold_) do_icp = false; } char &rgb_offset_r=rgb_offsets[0]; char &rgb_offset_g=rgb_offsets[1]; char &rgb_offset_b=rgb_offsets[2]; if(do_icp_color_offset_){ if(std::abs(out_av[0] - in_av[0]) < 32) rgb_offset_r = (char)(out_av[0] - in_av[0]); if(std::abs(out_av[1] - in_av[1]) < 32) rgb_offset_g = (char)(out_av[1] - in_av[1]); if(std::abs(out_av[2] - in_av[2]) < 32) rgb_offset_b = (char)(out_av[2] - in_av[2]); } if(!do_icp) { has_converged = false; return; } // do the actual icp transformation pcl::IterativeClosestPoint<PointT, PointT> icp; icp.setInputSource(i_cloud); icp.setInputTarget(p_cloud); icp.setMaximumIterations (icp_max_iterations_); // Set the transformation epsilon (criterion 2) icp.setTransformationEpsilon (transformationepsilon_); // Set the euclidean distance difference epsilon (criterion 3) icp.setEuclideanFitnessEpsilon (3 * transformationepsilon_); pcl::PointCloud<PointT> Final; icp.align(Final); // compute the fitness for the colors if(icp.hasConverged() && icp.getFitnessScore() < point_resolution_ * 2) { has_converged = true; // rigid_transform = new Eigen::Matrix4f(icp.getFinalTransformation()); rigid_transform = icp.getFinalTransformation(); return; } has_converged = false; } /*! \brief generate a point cloud Delta to output stream * \param icloud_arg point cloud to be used a I frame * \param pcloud_arg point cloud to be encoded as a pframe * \param out_cloud_arg [out] the predicted frame * \param i_coded_data intra encoded data * \param p_coded_data inter encoded data * \param icp_on_original (option to do icp on original or simplified clouds) * \param write_out_cloud (flag to write the output cloud to out_cloud_arg) */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT,LeafT,BranchT,OctreeT>::generatePointCloudDeltaFrame( const PointCloudConstPtr &icloud_arg /* icloud is already stored but can also be given as argument */, const PointCloudConstPtr &pcloud_arg, PointCloudPtr& out_cloud_arg, /* write the output cloud so we can assess the quality resulting from this algorithm */ std::ostream& i_coded_data, std::ostream& p_coded_data, bool icp_on_original, bool write_out_cloud, uint64_t timeStamp) { // intra coded points storage (points that cannot be predicted) typename pcl::PointCloud<PointT>::Ptr intra_coded_points(new pcl::PointCloud<PointT>()); // initialize simplified predictive cloud PointCloudPtr simp_pcloud(new PointCloud()); if(!icp_on_original){ simplifyPCloud(pcloud_arg, simp_pcloud); } // keep track of the prediction statistics long macro_block_count=0; long shared_macroblock_count=0; long convergence_count=0; // initialize output cloud out_cloud_arg->height=1; out_cloud_arg->width =0; ////////////// generate the octree for the macroblocks ////////////////////////////// MacroBlockTree * i_block_tree = generate_macroblock_tree(icloud_arg); MacroBlockTree * p_block_tree = generate_macroblock_tree(icp_on_original ? pcloud_arg:simp_pcloud); //////////// iterate the predictive frame and find common macro blocks ///////////// #if PCL_VERSION >= 100901 octree::OctreeDepthFirstIterator<OctreeT> it_predictive = p_block_tree->leaf_depth_begin(); for (; *it_predictive; ++it_predictive) { if (it_predictive.isBranchNode()) continue; #else//PCL_VERSION >= 100901 octree::OctreeDepthFirstIterator<OctreeT> it_predictive = p_block_tree->leaf_begin(); octree::OctreeDepthFirstIterator<OctreeT> it_predictive_end = p_block_tree->leaf_end(); for(;it_predictive!=it_predictive_end;++it_predictive) { #endif//PCL_VERSION >= 100901 macro_block_count++; const octree::OctreeKey current_key = it_predictive.getCurrentOctreeKey(); pcl::octree::OctreeContainerPointIndices *i_leaf; typename pcl::PointCloud<PointT>::Ptr cloud_out (new pcl::PointCloud<PointT>(icp_on_original ? *pcloud_arg : *simp_pcloud , it_predictive.getLeafContainer().getPointIndicesVector())); if((i_leaf = i_block_tree->findLeaf(current_key.x,current_key.y,current_key.z)) != NULL) { typename pcl::PointCloud<PointT>::Ptr cloud_in (new pcl::PointCloud<PointT>(*icloud_arg, i_leaf->getPointIndicesVector())); shared_macroblock_count++; // shared block, do icp bool icp_success=false; Eigen::Matrix4f rt = Eigen::Matrix4f::Identity(); char rgb_offsets[3]={0,0,0}; do_icp_prediction( rt, cloud_in, cloud_out, icp_success, rgb_offsets ); if(icp_success) { convergence_count++; // icp success, encode the rigid transform std::vector<int16_t> comp_dat; Eigen::Quaternion<float> l_quat_out; RigidTransformCoding<float>::compressRigidTransform(rt,comp_dat,l_quat_out); // write octree key, write rigid transform int16_t l_key_dat[3]={0,0,0}; l_key_dat[0] = (int) current_key.x; l_key_dat[1] = (int) current_key.y; l_key_dat[2] = (int) current_key.z; // write the p coded data (we can add entropy encoding later) p_coded_data.write((const char *) l_key_dat ,3*sizeof(int16_t)); p_coded_data.write((const char *) &comp_dat[0] ,comp_dat.size()*sizeof(int16_t)); if(do_icp_color_offset_) p_coded_data.write((const char *) &rgb_offsets[0] ,3*sizeof(char)); // following code is for generation of the predicted frame Eigen::Matrix4f mdec = Eigen::Matrix4f::Identity(); Eigen::Quaternion<float> l_quat_out_dec; RigidTransformCoding<float>::deCompressRigidTransform(comp_dat, mdec,l_quat_out_dec); /* uncomment this code for debugging the rigid transform bool corrected_tf_matrix=false; for(int i=0; i<16;i++) { float diff=0; if((diff=std::abs(rt(i/4,i%4) - mdec(i/4,i%4))) > 0.01){ //mdec(i/4,i%4) = rt(i/4,i%4); corrected_tf_matrix=true; std::cout << " error decoding rigid transform " << comp_dat.size() << " index " << i/4 << "," << i%4 << std::endl; std::cout << " original " << rt << std::endl; std::cout << " decoded " << mdec << std::endl; std::cin.get(); } } if(corrected_tf_matrix) std::cout << " matrix decoded not ok " <<std::endl; else std::cout << " matrix decoded ok " <<std::endl; */ if(write_out_cloud){ // predicted point cloud pcl::PointCloud<PointT> manual_final; transformPointCloud<PointT, float> ( *cloud_in, manual_final, mdec ); // generate the output points for(int i=0; i < manual_final.size();i++){ PointT &pt = manual_final[i]; // color offset if(do_icp_color_offset_){ pt.r+=rgb_offsets[0]; pt.g+=rgb_offsets[1]; pt.b+=rgb_offsets[2]; } out_cloud_arg->push_back(pt); } } } else { // icp failed // add to intra coded points for(int i=0; i < cloud_out->size();i++){ if(write_out_cloud) out_cloud_arg->push_back((*cloud_out)[i]); intra_coded_points->push_back((*cloud_out)[i]); } } } else { // exclusive block // add to intra coded points for(int i=0; i < cloud_out->size();i++) { if(write_out_cloud) out_cloud_arg->push_back((*cloud_out)[i]); intra_coded_points->push_back((*cloud_out)[i]); } } } /* encode all the points that could not be predicted from the previous coded frame in i frame manner with cluod_codec_v2 */ OctreePointCloudCodecV2<PointT,LeafT,BranchT,OctreeT> intra_coder ( MANUAL_CONFIGURATION, b_show_statistics_, point_resolution_, octree_resolution_, true, 0, true, color_bit_resolution_, color_coding_type_, timeStamp, do_voxel_centroid_enDecoding_ ); intra_coder.defineBoundingBox(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); intra_coder.encodePointCloud(intra_coded_points, i_coded_data, timeStamp); //compute convergence statistics //compute the convergence statistics shared_macroblock_percentage_ = (float)shared_macroblock_count / (float)macro_block_count ; shared_macroblock_convergence_percentage_ = (float)convergence_count / (float)shared_macroblock_count; // clean up delete i_block_tree; delete p_block_tree; } // Next data structures are used to store essential information to parallelize a CPU intensive loop template<typename T> struct cloudInfoT { typename pcl::octree::OctreeContainerPointIndices* i_leaf; octree::OctreeKey current_key; std::vector<int>* indices; }; template<typename T> struct cloudResultT { Eigen::Matrix4f rt; typename pcl::PointCloud<T>::Ptr in_cloud; typename pcl::PointCloud<T>::Ptr out_cloud; bool icp_success; char rgb_offsets[3]; bool leaf_found; }; /** \brief routine to encode a delta frame (predictive coding) * \author Rufael Mekuria rufael.mekuria@cwi.nl * \param icloud_arg point cloud to be used a I frame * \param pcloud_arg point cloud to be encoded as a pframe * \param out_cloud_arg [out] the predicted frame * \param i_coded_data intra encoded data * \param p_coded_data inter encoded data * \param icp_on_original (option to do icp on original or simplified clouds) * \param write_out_cloud (flag to write the output cloud to out_cloud_arg) */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::encodePointCloudDeltaFrame( const PointCloudConstPtr &icloud_arg, const PointCloudConstPtr &pcloud_arg, PointCloudPtr &out_cloud_arg, std::ostream& i_coded_data, std::ostream& p_coded_data, bool icp_on_original, bool write_out_cloud, uint64_t timeStamp) { #ifndef _OPENMP num_threads_ = 0; #endif// _OPENMP std::vector<cloudInfoT<PointT> > p_info_list; std::vector<cloudResultT<PointT> > p_result_list; std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > p_result_matrices; // intra coded points storage (points that cannot be predicted) typename pcl::PointCloud<PointT>::Ptr intra_coded_points(new pcl::PointCloud<PointT>()); // keep track of the prediction statistics long macro_block_count = 0; long shared_macroblock_count = 0; long convergence_count = 0; // initialize predictive cloud PointCloudPtr simp_pcloud(new PointCloud()); if (!icp_on_original) { simplifyPCloud(pcloud_arg, simp_pcloud); } // initialize output cloud out_cloud_arg->height = 1; out_cloud_arg->width = 0; ////////////// generate the octree for the macroblocks ////////////////////////////// MacroBlockTree * i_block_tree = generate_macroblock_tree(icloud_arg); MacroBlockTree * p_block_tree = generate_macroblock_tree(icp_on_original ? pcloud_arg : simp_pcloud); //////////// iterate the predictive frame and find common macro blocks ///////////// #if PCL_VERSION >= 100901 octree::OctreeDepthFirstIterator<OctreeT> it_predictive = p_block_tree->leaf_depth_begin(); if (num_threads_ == 0) { for (; *it_predictive; ++it_predictive) { if (!(it_predictive.isLeafNode())) continue; #else//PCL_VERSION >= 100901 octree::OctreeDepthFirstIterator<OctreeT> it_predictive = p_block_tree->leaf_begin(); octree::OctreeDepthFirstIterator<OctreeT> it_predictive_end = p_block_tree->leaf_end(); if (num_threads_ == 0) { for (; it_predictive != it_predictive_end; ++it_predictive) { #endif//PCL_VERSION >= 100901 const octree::OctreeKey current_key = it_predictive.getCurrentOctreeKey(); pcl::octree::OctreeContainerPointIndices *i_leaf; typename pcl::PointCloud<PointT>::Ptr cloud_out(new pcl::PointCloud<PointT>(icp_on_original ? *pcloud_arg : *simp_pcloud, it_predictive.getLeafContainer().getPointIndicesVector())); macro_block_count++; if ((i_leaf = i_block_tree->findLeaf(current_key.x, current_key.y, current_key.z)) != NULL) { shared_macroblock_count++; typename pcl::PointCloud<PointT>::Ptr cloud_in(new pcl::PointCloud<PointT>(*icloud_arg, i_leaf->getPointIndicesVector())); // shared block, do icp bool icp_success = false; Eigen::Matrix4f rt = Eigen::Matrix4f::Identity(); char rgb_offsets[3] = { 0,0,0 }; // Next function is CPU intensive, and candidate for parallel execution do_icp_prediction( rt, cloud_in, cloud_out, icp_success, rgb_offsets ); if (icp_success) { convergence_count++; // icp success, encode the rigid transform std::vector<int16_t> comp_dat; Eigen::Quaternion<float> l_quat_out; RigidTransformCoding<float>::compressRigidTransform(rt, comp_dat, l_quat_out); // write octree key, write rigid transform int16_t l_key_dat[3] = { 0,0,0 }; l_key_dat[0] = (int)current_key.x; l_key_dat[1] = (int)current_key.y; l_key_dat[2] = (int)current_key.z; // write the p coded data (we can add entropy encoding later) uint8_t chunk_size = (uint8_t)(3 * sizeof(int16_t) + comp_dat.size()*sizeof(int16_t) + (do_icp_color_offset_ ? 3 : 0)); // size of the chunk p_coded_data.write((const char *)&chunk_size, sizeof(chunk_size)); p_coded_data.write((const char *)l_key_dat, 3 * sizeof(int16_t)); p_coded_data.write((const char *)&comp_dat[0], comp_dat.size()*sizeof(int16_t)); if (do_icp_color_offset_) p_coded_data.write((const char *)rgb_offsets, 3 * sizeof(char)); // following code is for generation of predicted frame Eigen::Matrix4f mdec = Eigen::Matrix4f::Identity(); Eigen::Quaternion<float> l_quat_out_dec; RigidTransformCoding<float>::deCompressRigidTransform(comp_dat, mdec, l_quat_out_dec); // predicted point cloud pcl::PointCloud<PointT> manual_final; if (write_out_cloud) { transformPointCloud<PointT, float> (*cloud_in, manual_final, mdec ); } // generate the output points if (write_out_cloud) { for (int i = 0; i < manual_final.size(); i++) { PointT &pt = manual_final[i]; // color offset if (do_icp_color_offset_) { pt.r += rgb_offsets[0]; pt.g += rgb_offsets[1]; pt.b += rgb_offsets[2]; } out_cloud_arg->push_back(pt); } } } else { // icp failed // add to intra coded points for (int i = 0; i < cloud_out->size(); i++) { if (write_out_cloud) out_cloud_arg->push_back((*cloud_out)[i]); intra_coded_points->push_back((*cloud_out)[i]); } } } else { // exclusive block // add to intra coded points for (int i = 0; i < cloud_out->size(); i++) { if (write_out_cloud) out_cloud_arg->push_back((*cloud_out)[i]); intra_coded_points->push_back((*cloud_out)[i]); } } } } else // num_threads > 0 --> parallelization /* For _OPENMP, the previous loop over the common macro blocks of a frame must be converted in an equivalent one, * where the number of iterations is known before the loop starts. * We do this by storing all information in the current loop that is needed for the computations in the vector p_info_list, * next start another loop in parallel chunks managed by OPENMP for the actual computations, storing the results in the vector p_result_list. * Finally, in a third loop is all results are further processed as in the sequential setting. */ { // store the input arguments for 'do_icp_prediction' for (; *it_predictive; ++it_predictive) { if (it_predictive.isBranchNode()) continue; const octree::OctreeKey current_key = it_predictive.getCurrentOctreeKey(); pcl::octree::OctreeContainerPointIndices* i_leaf = i_block_tree->findLeaf(current_key.x, current_key.y, current_key.z); cloudInfoT<PointT> ci; cloudResultT<PointT> cr; ci.i_leaf = i_leaf; ci.current_key = current_key; ci.indices = &it_predictive.getLeafContainer().getPointIndicesVector(); cr.leaf_found = i_leaf != NULL; cr.icp_success = false; for (int j = 0; j < 3; j++) { cr.rgb_offsets[j] = 0; } p_info_list.push_back(ci); p_result_list.push_back(cr); Eigen::Matrix4f crm; p_result_matrices.push_back(crm); macro_block_count++; } #if defined(_OPENMP) std::cout << " running in parallel on " << num_threads_ << std::endl; omp_set_num_threads(num_threads_); #endif//defined(_OPENMP) #pragma omp parallel for shared(p_info_list,p_result_list,p_result_matrices) for (int i = 0; i < p_info_list.size(); i++) { pcl::octree::OctreeContainerPointIndices* i_leaf = p_info_list[i].i_leaf; typename pcl::PointCloud<PointT>::Ptr cloud_out(new pcl::PointCloud<PointT>(icp_on_original ? *pcloud_arg : *simp_pcloud, *p_info_list[i].indices)); p_result_list[i].out_cloud = cloud_out; if (i_leaf != NULL) { p_result_list[i].in_cloud = (PointCloudPtr) new pcl::PointCloud<PointT>(*icloud_arg, i_leaf->getPointIndicesVector()); do_icp_prediction( p_result_matrices[i], (PointCloudPtr)p_result_list[i].in_cloud, (PointCloudPtr)p_result_list[i].out_cloud, p_result_list[i].icp_success, p_result_list[i].rgb_offsets ); } } // #pragma omp for #pragma omp barrier // wait until all threads finished for (int i = 0; i < p_result_list.size(); i++) { typename pcl::PointCloud<PointT>::Ptr cloud_out = p_result_list[i].out_cloud; if (p_result_list[i].leaf_found) { shared_macroblock_count++; typename pcl::PointCloud<PointT>::Ptr cloud_in = p_result_list[i].in_cloud; if (p_result_list[i].icp_success) { char rgb_offsets[3]; Eigen::Matrix4f rt = p_result_matrices[i]; for (int j = 0; j < 3; j++) { rgb_offsets[j] = p_result_list[i].rgb_offsets[j]; } octree::OctreeKey current_key = p_info_list[i].current_key; convergence_count++; // icp success, encode the rigid transform std::vector<int16_t> comp_dat; Eigen::Quaternion<float> l_quat_out; RigidTransformCoding<float>::compressRigidTransform(rt, comp_dat, l_quat_out); // write octree key, write rigid transform int16_t l_key_dat[3] = { 0, 0, 0 }; l_key_dat[0] = (int)current_key.x; l_key_dat[1] = (int)current_key.y; l_key_dat[2] = (int)current_key.z; // write the p coded data (we can add entropy encoding later) uint8_t chunk_size = (uint8_t)(3 * sizeof(int16_t) + comp_dat.size()*sizeof(int16_t) + (do_icp_color_offset_ ? 3 : 0)); // size of the chunk p_coded_data.write((const char *)&chunk_size, sizeof(chunk_size)); p_coded_data.write((const char *)l_key_dat, 3 * sizeof(int16_t)); p_coded_data.write((const char *)&comp_dat[0], comp_dat.size()*sizeof(int16_t)); if (do_icp_color_offset_) p_coded_data.write((const char *)rgb_offsets, 3 * sizeof(char)); // following code is for generation of predicted frame Eigen::Matrix4f mdec; Eigen::Quaternion<float> l_quat_out_dec; RigidTransformCoding<float>::deCompressRigidTransform(comp_dat, mdec, l_quat_out_dec); // predicted point cloud pcl::PointCloud<PointT> manual_final; if (write_out_cloud) { transformPointCloud<PointT, float> (*cloud_in, manual_final, mdec ); } // generate the output points if (write_out_cloud) { for (int i = 0; i < manual_final.size(); i++) { PointT &pt = manual_final[i]; // color offset if (do_icp_color_offset_) { pt.r += rgb_offsets[0]; pt.g += rgb_offsets[1]; pt.b += rgb_offsets[2]; } out_cloud_arg->push_back(pt); } } } else { // icp failed // add to intra coded points for (int i = 0; i < cloud_out->size(); i++) { if (write_out_cloud) out_cloud_arg->push_back((*cloud_out)[i]); intra_coded_points->push_back((*cloud_out)[i]); } } } else { // exclusive block // add to intra coded points for (int i = 0; i < cloud_out->size(); i++) { if (write_out_cloud) out_cloud_arg->push_back((*cloud_out)[i]); intra_coded_points->push_back((*cloud_out)[i]); } } } } /* encode all the points that could not be predicted from the previous coded frame in i frame manner with cloud_codec_v2 */ OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT> intra_coder ( MANUAL_CONFIGURATION, false, point_resolution_, octree_resolution_, true, 0, true, color_bit_resolution_, color_coding_type_, timeStamp, do_voxel_centroid_enDecoding_ ); intra_coder.defineBoundingBox(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); intra_coder.encodePointCloud(intra_coded_points, i_coded_data, timeStamp); //compute the convergence statistics shared_macroblock_percentage_ = (float)shared_macroblock_count / (float)macro_block_count; shared_macroblock_convergence_percentage_ = (float)convergence_count / (float)shared_macroblock_count; // clean up delete i_block_tree; delete p_block_tree; } /** \brief routine to decode a delta frame (predictive coding) * \author Rufael Mekuria rufael.mekuria@cwi.nl * \param icloud_arg point cloud to be used a I frame * \param cloud_out_arg decoded frame * \param i_coded_data intra encoded data * \param p_coded_data inter encoded data */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> bool OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::decodePointCloudDeltaFrame( const PointCloudConstPtr &icloud_arg, PointCloudPtr &cloud_out_arg, std::istream& i_coded_data, std::istream& p_coded_data, uint64_t& timeStamp) { ////////////// generate the macroblocks of the iframe ////////////////////////////// MacroBlockTree * i_block_tree = generate_macroblock_tree(icloud_arg); ///////////// inputs for decoding chunks of p data ///////////////////////////////// int16_t keys_in[3]={0,0,0}; uint8_t chunk_size=0; char rgb_offsets[3]={0,0,0}; std::vector<int16_t> comp_dat_in; int decoded_mblocks=0; ///////////////////////////decode p data /////////////////////////// while(p_coded_data.good()) { // read the chunk size first p_coded_data.read((char *) &chunk_size, sizeof(uint8_t)); if((chunk_size > 0) && p_coded_data.good()){ // read the keys p_coded_data.read((char *) keys_in, 3*sizeof(int16_t)); // compute size of comp_dat (13 for vector mode a, 6 for quaternion mode) uint8_t comp_dat_size = chunk_size - 3*sizeof(int16_t) - (do_icp_color_offset_ ? 3:0); comp_dat_in.resize(comp_dat_size/sizeof(int16_t)); // load compdat p_coded_data.read((char *) &comp_dat_in[0] ,comp_dat_in.size()*sizeof(int16_t)); //load color offsets if(do_icp_color_offset_) p_coded_data.read((char *) &rgb_offsets[0] ,3*sizeof(char)); pcl::octree::OctreeContainerPointIndices *i_leaf; if((i_leaf = i_block_tree->findLeaf(keys_in[0],keys_in[1],keys_in[2]))) { typename pcl::PointCloud<PointT>::Ptr cloud_in (new pcl::PointCloud<PointT>(*icloud_arg, i_leaf->getPointIndicesVector())); // following code is for generation of predicted frame Eigen::Matrix4f mdec = Eigen::Matrix4f::Identity(); Eigen::Quaternion<float> l_quat_out_dec; RigidTransformCoding<float>::deCompressRigidTransform(comp_dat_in, mdec,l_quat_out_dec); // predicted point cloud pcl::PointCloud<PointT> p_chunk; // generate the pcoded data from the previous frame transformPointCloud<PointT, float> ( *cloud_in, p_chunk, mdec ); decoded_mblocks++; //decode the predictive points for(int j=0; j<p_chunk.size();j++) { PointT &p_point = (p_chunk)[j]; if(do_icp_color_offset_) { p_point.r+=p_point.r + rgb_offsets[0]; p_point.g+=p_point.g + rgb_offsets[1]; p_point.b+=p_point.b + rgb_offsets[2]; } cloud_out_arg->push_back(p_point); } } else{ std::cout << " failed decoding predictive frame, no corresponding i block " << std::endl; } } else break; } std::cout << " decoded: " << decoded_mblocks << " pblocks, resulting in " << cloud_out_arg->size() << " output points " << std::endl; // decode the intra coded points typename pcl::PointCloud<PointT>::Ptr intra_coded_points(new pcl::PointCloud<PointT>()); OctreePointCloudCodecV2<PointT,LeafT,BranchT,OctreeT> intra_coder ( MANUAL_CONFIGURATION, false, point_resolution_, octree_resolution_, true, 0, true, color_bit_resolution_, color_coding_type_, timeStamp, do_voxel_centroid_enDecoding_ ); uint64_t t = 0; if (!intra_coder.decodePointCloud(i_coded_data,intra_coded_points,t)) return false; // add the decoded input points to the output cloud for(int i=0; i< intra_coded_points->size();i++) cloud_out_arg->push_back((*intra_coded_points)[i]); // clean up delete i_block_tree; return true; } // struct local_color_enh{ unsigned int r; unsigned int g; unsigned int b; }; /* EXP * //! function for coding an enhancement layer, use the same input cloud!! template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::encodeEnhancementLayer(const PointCloudConstPtr &cloud_arg, std::ostream& compressed_tree_data_out_arg) { // get the leafs using namespace octree; LeafNodeIterator leaf_it = leaf_begin(); LeafNodeIterator leaf_end_it = leaf_end(); StaticRangeCoder color_coder; StaticRangeCoder position_coder; // temporary storage of the occupancy codes std::vector<char> occupancy_codes; occupancy_codes.reserve(this->leaf_count_); // write the color code back std::vector<char> color_vector; // iterate the leafs while(leaf_it != leaf_end_it) { // get the point indices std::vector<int>& point_indices = leaf_it.getLeafContainer().getPointIndicesVector(); // get the voxel grid size Eigen::Vector3f minpt; Eigen::Vector3f maxpt; getVoxelBounds(leaf_it, minpt,maxpt); // middle vertices Eigen::Vector3f midden = (maxpt - minpt) * 0.5 + minpt; // initialize the code position char code_pos=0u; // global and local color averages for the color unsigned int color_r=0; unsigned int color_g=0; unsigned int color_b=0; // local color averages for the colors std::array<local_color_enh,8> colors_per_cell; std::array<int,8> occupancy_count={}; // iterate all points and compute the occupancy code for(int i=0; i < point_indices.size(); i++) { unsigned char occ_code=0u; const PointT &l_point = (*cloud_arg)[point_indices[i]]; // if(l_point.x > midden.x()) occ_code+=1; // if(l_point.y > midden.y()) occ_code+=2; // if(l_point.z > midden.z()) occ_code+=4; code_pos |= (1u << occ_code); // global color average // color_r+=l_point.r; color_g+=l_point.g; color_b+=l_point.b; // local color average // colors_per_cell[occ_code].r+= l_point.r; colors_per_cell[occ_code].g+= l_point.g; colors_per_cell[occ_code].b+= l_point.b; occupancy_count[occ_code]++; } // write the occupancy code back occupancy_codes.push_back( (char) code_pos); color_r/=point_indices.size(); color_g/=point_indices.size(); color_b/=point_indices.size(); /////////// local color averages ///////////////////// for(int k=0;k<8;k++) { if(occupancy_count[k]) { colors_per_cell[k].r/= occupancy_count[k]; colors_per_cell[k].g/= occupancy_count[k]; colors_per_cell[k].b/= occupancy_count[k]; int color_diff_r = (int) color_r - (int) colors_per_cell[k].r; if(color_diff_r < 128 && color_diff_r >= -128) color_vector.push_back((char) color_diff_r); else color_vector.push_back(0); int color_diff_g = (int) color_g - (int) colors_per_cell[k].g; if(color_diff_g < 128 && color_diff_g >= -128) color_vector.push_back((char) color_diff_g); else color_vector.push_back(0); int color_diff_b = (int) color_b - (int) colors_per_cell[k].b; if(color_diff_b < 128 && color_diff_b >= -128) color_vector.push_back((char) color_diff_b); else color_vector.push_back(0); } } // increment ++leaf_it; } /// format of the enhancement layer ////// std::size_t pos_vec_size = occupancy_codes.size(); std::size_t color_vec_size = color_vector.size(); std::size_t comp_dat_size=0; compressed_tree_data_out_arg.write( (const char *) &pos_vec_size, sizeof(pos_vec_size )); compressed_tree_data_out_arg.write( (const char *) &color_vec_size , sizeof(color_vec_size)); comp_dat_size+=position_coder.encodeCharVectorToStream(occupancy_codes, compressed_tree_data_out_arg); comp_dat_size+=color_coder.encodeCharVectorToStream(color_vector, compressed_tree_data_out_arg); } //! function for decoding an enhancment layer template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::decodeEnhancementLayer(std::istream& compressed_tree_data_in_arg, PointCloudPtr &cloud_arg, PointCloudPtr &cloud_arg_enh) { // decode all the occupancy codes std::size_t size_of_colors; std::size_t size_of_occupancy_codes; std::vector<char> occ_codes; std::vector<char> color_deltas; compressed_tree_data_in_arg.read((char *) &size_of_colors, sizeof(size_of_colors)); compressed_tree_data_in_arg.read((char *) &size_of_occupancy_codes,sizeof(size_of_occupancy_codes)); occ_codes.resize(size_of_occupancy_codes); color_deltas.resize(size_of_colors); StaticRangeCoder pos_decoder; StaticRangeCoder color_decoder; pos_decoder.decodeStreamToCharVector(compressed_tree_data_in_arg, occ_codes); color_decoder.decodeStreamToCharVector(compressed_tree_data_in_arg, color_deltas); // get the leafs LeafNodeIterator leaf_it = leaf_begin(); LeafNodeIterator leaf_end_it = leaf_end(); std::vector<char>::iterator curr_occ = occ_codes.begin(); std::vector<char>::iterator color_it= color_deltas.begin(); assert(occ_codes.size() == this->leaf_count_); // apply all inverse operations // iterate the leafs while(leaf_it != leaf_end_it) { // do the decoding OctreeKey ckey; ckey = leaf_it.getCurrentOctreeKey(); for(unsigned char k=0;k<8;k++) { unsigned char ccode = (1u << k); // test occupancy if( (*curr_code & ccode) == ccode){ uint8_t x=0,y=0,z=0; PointT newPoint; int l = k; if(l >= 4) { //zpos z++; l-=4; } if(l>=2) { y++; l-=2; } if(l>=1) { x++; } // newPoint.x = static_cast<float> ((static_cast<double> (ckey.x) + (x ? 0.75 : 0.25)) * resolution_ + min_x_); newPoint.y = static_cast<float> ((static_cast<double> (ckey.y) + (y ? 0.75 : 0.25)) * resolution_ + min_y_); newPoint.z = static_cast<float> ((static_cast<double> (ckey.z) + (z ? 0.75 : 0.25)) * resolution_ + min_z_); std::vector<int>& indicesV =leaf_it.getLeafContainer().getPointIndicesVector(); int index_point = indicesV.size() > 0 ? indicesV[0] : -1; if(index_point != -1){ newPoint.r = *color_it++ + (*cloud_arg[index_point]).r; newPoint.g = *color_it++ + (*cloud_arg[index_point]).g; newPoint.b = *color_it++ + (*cloud_arg[index_point]).b; } //enhancement layer code decoded cloud_arg_enh->push_back(newPoint); } } // increment iterator ++leaf_it; ++curr_code; } } EXP */ /////////////////// CODE OVERWRITING CODEC V1 to become codec V2 //////////////////////////////// //! write Frame header, extended for cloud codecV2 template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::writeFrameHeader(std::ostream& compressed_tree_data_out_arg, uint64_t timeStamp) { compressed_tree_data_out_arg.write (reinterpret_cast<const char*> (frame_header_identifier_), strlen (frame_header_identifier_)); //! use the base class and write some extended information on codecV2 /* int octree_bits; int color_bits; int jpeg_quality; int macroblock_size; */ OctreePointCloudCompression<PointT, LeafT, BranchT, OctreeT>::writeFrameHeader(compressed_tree_data_out_arg); //! write additional fields for cloud codec v2 //std::cout << "\n Input time stamp is: " << timeStamp << "\n"; compressed_tree_data_out_arg.write(reinterpret_cast<const char*> (&timeStamp), sizeof(timeStamp)); compressed_tree_data_out_arg.write(reinterpret_cast<const char*> (&octreeResolution), sizeof(octreeResolution)); compressed_tree_data_out_arg.write(reinterpret_cast<const char*> (&colorBitResolution), sizeof(colorBitResolution)); compressed_tree_data_out_arg.write(reinterpret_cast<const char*> (&jpeg_quality), sizeof(jpeg_quality)); compressed_tree_data_out_arg.write (reinterpret_cast<const char*> (&do_voxel_centroid_enDecoding_), sizeof (do_voxel_centroid_enDecoding_)); // centroid coding compressed_tree_data_out_arg.write (reinterpret_cast<const char*> (&do_connectivity_encoding_), sizeof (do_connectivity_encoding_)); // connectivity coding (not yet added) compressed_tree_data_out_arg.write (reinterpret_cast<const char*> (&create_scalable_bitstream_), sizeof (create_scalable_bitstream_)); // scalable bitstream compressed_tree_data_out_arg.write (reinterpret_cast<const char*> (&color_coding_type_), sizeof (color_coding_type_)); // color coding type (added jpeg based modes) compressed_tree_data_out_arg.write (reinterpret_cast<const char*> (&macroblock_size_), sizeof (macroblock_size_)); // settings for ICP based prediction compressed_tree_data_out_arg.write (reinterpret_cast<const char*> (&do_icp_color_offset_), sizeof (do_icp_color_offset_)); // settings for ICP based prediction }; //! read Frame header, extended for cloud codecV2 template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::readFrameHeader(std::istream& compressed_tree_data_in_arg, uint64_t& timeStamp) { //! use the base class and read some extended information on codecV2 _BaseCodecT::readFrameHeader(compressed_tree_data_in_arg); //! read additional fields for cloud codec v2 compressed_tree_data_in_arg.read(reinterpret_cast<char*> (&timeStamp), sizeof(timeStamp)); compressed_tree_data_in_arg.read(reinterpret_cast<char*> (&octreeResolution), sizeof(octreeResolution)); compressed_tree_data_in_arg.read(reinterpret_cast<char*> (&colorBitResolution), sizeof(colorBitResolution)); compressed_tree_data_in_arg.read(reinterpret_cast<char*> (&jpeg_quality), sizeof(jpeg_quality)); //std::cout << "\n Timestamp is :" << timeStamp; compressed_tree_data_in_arg.read (reinterpret_cast<char*> (&do_voxel_centroid_enDecoding_), sizeof (do_voxel_centroid_enDecoding_)); compressed_tree_data_in_arg.read (reinterpret_cast<char*> (&do_connectivity_encoding_), sizeof (do_connectivity_encoding_)); compressed_tree_data_in_arg.read (reinterpret_cast<char*> (&create_scalable_bitstream_), sizeof (create_scalable_bitstream_)); compressed_tree_data_in_arg.read (reinterpret_cast<char*> (&color_coding_type_), sizeof (color_coding_type_)); compressed_tree_data_in_arg.read (reinterpret_cast<char*> (&macroblock_size_), sizeof (macroblock_size_)); compressed_tree_data_in_arg.read (reinterpret_cast<char*> (&do_icp_color_offset_), sizeof (do_icp_color_offset_)); }; /** \brief Encode leaf node information during serialization, added jpeg color coding and voxel centroid coding * \param leaf_arg: reference to new leaf node * \param key_arg: octree key of new leaf node * \brief added centroids encoding compared to the original codec of PCL */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::serializeTreeCallback (LeafT &leaf_arg, const OctreeKey& key_arg) { // reference to point indices vector stored within octree leaf // const std::vector<int>& leafIdx = leaf_arg.getPointIndicesVector(); double lowerVoxelCorner[3]; PointT centroid; // // // calculate lower voxel corner based on octree key // lowerVoxelCorner[0] = static_cast<double> (key_arg.x) * resolution_ + min_x_; lowerVoxelCorner[1] = static_cast<double> (key_arg.y) * resolution_ + min_y_; lowerVoxelCorner[2] = static_cast<double> (key_arg.z) * resolution_ + min_z_; // // // points detail encoding if (!do_voxel_grid_enDecoding_) { // encode amount of points within voxel point_count_data_vector_.push_back (static_cast<int> (leafIdx.size ())); // differentially encode points to lower voxel corner point_coder_.encodePoints (leafIdx, lowerVoxelCorner, input_); if (cloud_with_color_) { // encode color of points if(!color_coding_type_) { color_coder_.encodePoints (leafIdx, point_color_offset_, input_); } else { jp_color_coder_.encodePoints (leafIdx, point_color_offset_, input_); } } } else // centroid or voxelgrid encoding { if (cloud_with_color_) { // encode average color of all points within voxel if(!color_coding_type_) color_coder_.encodeAverageOfPoints (leafIdx, point_color_offset_, input_); else jp_color_coder_.encodeAverageOfPoints (leafIdx, point_color_offset_, input_); std::vector<char> & l_colors = color_coding_type_ ? jp_color_coder_.getAverageDataVectorB() : color_coder_.getAverageDataVector(); //! get the colors from the vector from the color coder, use to store to do temporal prediction centroid.r = l_colors[l_colors.size() - 1]; centroid.g = l_colors[l_colors.size() - 2]; centroid.b = l_colors[l_colors.size() - 3]; } if(!do_voxel_centroid_enDecoding_) { centroid.x = lowerVoxelCorner[0] + 0.5 * resolution_ ; centroid.y = lowerVoxelCorner[1] + 0.5 * resolution_ ; centroid.z = lowerVoxelCorner[2] + 0.5 * resolution_ ; } else { Eigen::Vector4f f_centroid; pcl::compute3DCentroid<PointT>(*(input_), leafIdx, f_centroid); centroid.x = f_centroid[0]; centroid.y = f_centroid[1]; centroid.z = f_centroid[2]; centroid_coder_.encodePoint(lowerVoxelCorner, centroid); } // store the simplified cloud so that it can be used for predictive encoding (if wanted) if (output_) { output_->points.push_back(centroid); } } } /** \brief Decode leaf nodes information during deserialization, added jpeg and voxel centroid coding * \param key_arg octree key of new leaf node * \brief added centroids encoding compared to the original codec */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::deserializeTreeCallback (LeafT&, const OctreeKey& key_arg) { double lowerVoxelCorner[3]; std::size_t pointCount, i, cloudSize; PointT newPoint; pointCount = 1; if (!do_voxel_grid_enDecoding_) { // get current cloud size cloudSize = output_->points.size(); // get amount of point to be decoded pointCount = *point_count_data_vector_iterator_; point_count_data_vector_iterator_++; // increase point cloud by amount of voxel points for (i = 0; i < pointCount; i++) output_->points.push_back (newPoint); // calculcate position of lower voxel corner lowerVoxelCorner[0] = static_cast<double> (key_arg.x) * resolution_ + min_x_; lowerVoxelCorner[1] = static_cast<double> (key_arg.y) * resolution_ + min_y_; lowerVoxelCorner[2] = static_cast<double> (key_arg.z) * resolution_ + min_z_; // decode differentially encoded points point_coder_.decodePoints (output_, lowerVoxelCorner, cloudSize, cloudSize + pointCount); } else { // decode the centroid or the voxel center if(do_voxel_centroid_enDecoding_) { PointT centroid_point; // calculcate position of lower voxel corner lowerVoxelCorner[0] = static_cast<double> (key_arg.x) * resolution_ + min_x_; lowerVoxelCorner[1] = static_cast<double> (key_arg.y) * resolution_ + min_y_; lowerVoxelCorner[2] = static_cast<double> (key_arg.z) * resolution_ + min_z_; centroid_coder_.decodePoint(newPoint,lowerVoxelCorner); } else { // calculate center of lower voxel corner newPoint.x = static_cast<float> ((static_cast<double> (key_arg.x) + 0.5) * resolution_ + min_x_); newPoint.y = static_cast<float> ((static_cast<double> (key_arg.y) + 0.5) * resolution_ + min_y_); newPoint.z = static_cast<float> ((static_cast<double> (key_arg.z) + 0.5) * resolution_ + min_z_); } // add point to point cloud output_->points.push_back (newPoint); } if (cloud_with_color_) { if (data_with_color_) // decode color information if(!color_coding_type_) color_coder_.decodePoints (output_, output_->points.size () - pointCount, output_->points.size (), point_color_offset_); else jp_color_coder_.decodePoints (output_, output_->points.size () - pointCount, output_->points.size (), point_color_offset_); else // set default color information color_coder_.setDefaultColor(output_, output_->points.size() - pointCount, output_->points.size(), point_color_offset_); } } /** \brief Synchronize to frame header * \param compressed_tree_data_in_arg: binary input stream * \brief use the new v2 header */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> bool OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::syncToHeader (std::istream& compressed_tree_data_in_arg) { // sync to frame header //std::cout << " \n Entered sync to frame header\n"; unsigned int header_id_pos = 0; //std::cout << "\n Frame header identifier is :" << frame_header_identifier_; while (header_id_pos < strlen (frame_header_identifier_)) { char readChar; if (compressed_tree_data_in_arg.eof()) return false; compressed_tree_data_in_arg.read (static_cast<char*> (&readChar), sizeof (readChar)); if (readChar != frame_header_identifier_[header_id_pos++]) header_id_pos = (frame_header_identifier_[0]==readChar)?1:0; //std::cout << "\n Header_id_pos is: " << header_id_pos; //std::cout << "\n Read char is:" << readChar << " Current frame header char is :" << frame_header_identifier_[header_id_pos]; } //std::cout << " \n Left loop\n"; //! read the original octree header _BaseCodecT::syncToHeader (compressed_tree_data_in_arg); return true; }; /** \brief Apply entropy encoding to encoded information and output to binary stream, added bitstream scalability and centroid encoding compared to V1 * \param compressed_tree_data_out_arg1 binary voxel output stream * \param compressed_tree_data_out_arg2 binary color output stream */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::entropyEncoding (std::ostream& compressed_tree_data_out_arg1, std::ostream& compressed_tree_data_out_arg2 ) { uint64_t binary_tree_data_vector_size; uint64_t point_avg_color_data_vector_size; compressed_point_data_len_ = 0; compressed_color_data_len_ = 0; // encode binary octree structure binary_tree_data_vector_size = binary_tree_data_vector_.size (); compressed_tree_data_out_arg1.write (reinterpret_cast<const char*> (&binary_tree_data_vector_size), sizeof (binary_tree_data_vector_size)); compressed_point_data_len_ += entropy_coder_.encodeCharVectorToStream(binary_tree_data_vector_, compressed_tree_data_out_arg1); // store the number of bytes used for voxel encoding compression_performance_metrics[0] = compressed_point_data_len_ ; // encode centroids if(do_voxel_centroid_enDecoding_) { // encode differential centroid information std::vector<char>& point_diff_data_vector = centroid_coder_.getDifferentialDataVector (); uint32_t point_diff_data_vector_size = (uint32_t) point_diff_data_vector.size(); compressed_tree_data_out_arg1.write (reinterpret_cast<const char*> (&point_diff_data_vector_size), sizeof (uint32_t)); compressed_point_data_len_ += entropy_coder_.encodeCharVectorToStream(point_diff_data_vector, compressed_tree_data_out_arg1); } // store the number of bytes used for voxel centroid encoding compression_performance_metrics[1] = compressed_point_data_len_ - compression_performance_metrics[0]; // encode colors if (cloud_with_color_) { // encode averaged voxel color information std::vector<char>& pointAvgColorDataVector = color_coding_type_ ? jp_color_coder_.getAverageDataVector () : color_coder_.getAverageDataVector (); point_avg_color_data_vector_size = pointAvgColorDataVector.size (); compressed_tree_data_out_arg1.write (reinterpret_cast<const char*> (&point_avg_color_data_vector_size), sizeof (point_avg_color_data_vector_size)); compressed_color_data_len_ += entropy_coder_.encodeCharVectorToStream(pointAvgColorDataVector, compressed_tree_data_out_arg1); } // store the number of bytes used for the color stream compression_performance_metrics[2] = compressed_color_data_len_ ; // flush output stream compressed_tree_data_out_arg1.flush (); if (!do_voxel_grid_enDecoding_) { uint64_t pointCountDataVector_size; uint64_t point_diff_data_vector_size; uint64_t point_diff_color_data_vector_size; // encode amount of points per voxel pointCountDataVector_size = point_count_data_vector_.size(); compressed_tree_data_out_arg2.write (reinterpret_cast<const char*> (&pointCountDataVector_size), sizeof (pointCountDataVector_size)); compressed_point_data_len_ += entropy_coder_.encodeIntVectorToStream(point_count_data_vector_, compressed_tree_data_out_arg2); // encode differential point information std::vector<char>& point_diff_data_vector = point_coder_.getDifferentialDataVector(); point_diff_data_vector_size = point_diff_data_vector.size (); compressed_tree_data_out_arg2.write (reinterpret_cast<const char*> (&point_diff_data_vector_size), sizeof (point_diff_data_vector_size)); compressed_point_data_len_ += entropy_coder_.encodeCharVectorToStream(point_diff_data_vector, compressed_tree_data_out_arg2); if (cloud_with_color_) { // encode differential color information std::vector<char>& point_diff_color_data_vector = color_coding_type_ ? jp_color_coder_.getDifferentialDataVector () : color_coder_.getDifferentialDataVector (); point_diff_color_data_vector_size = point_diff_color_data_vector.size (); compressed_tree_data_out_arg2.write (reinterpret_cast<const char*> (&point_diff_color_data_vector_size), sizeof (point_diff_color_data_vector_size)); compressed_color_data_len_ += entropy_coder_.encodeCharVectorToStream (point_diff_color_data_vector, compressed_tree_data_out_arg2); } } // flush output stream compressed_tree_data_out_arg2.flush (); }; /** \brief Entropy decoding of input binary stream and output to information vectors, added bitstream scalability and centroid encoding compared to V1 * \param compressed_tree_data_in_arg1 binary voxel input stream * \param compressed_tree_data_in_arg2 binary color enhancement input stream */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::entropyDecoding (std::istream& compressed_tree_data_in_arg1, std::istream& compressed_tree_data_in_arg2) { uint64_t binary_tree_data_vector_size = 0; uint64_t point_avg_color_data_vector_size = 0; compressed_point_data_len_ = 0; compressed_color_data_len_ = 0; // decode binary octree structure compressed_tree_data_in_arg1.read (reinterpret_cast<char*> (&binary_tree_data_vector_size), sizeof (binary_tree_data_vector_size)); binary_tree_data_vector_.resize(static_cast<std::size_t> (binary_tree_data_vector_size)); compressed_point_data_len_ += entropy_coder_.decodeStreamToCharVector(compressed_tree_data_in_arg1, binary_tree_data_vector_); //! new option for encoding centroids if(do_voxel_centroid_enDecoding_) { uint32_t l_count; // decode differential point information std::vector<char>& pointDiffDataVector = centroid_coder_.getDifferentialDataVector (); compressed_tree_data_in_arg1.read (reinterpret_cast<char*> (&l_count), sizeof (uint32_t)); pointDiffDataVector.resize (static_cast<std::size_t> (l_count)); compressed_point_data_len_ += entropy_coder_.decodeStreamToCharVector(compressed_tree_data_in_arg1, pointDiffDataVector); } if (data_with_color_) { // decode averaged voxel color information std::vector<char>& point_avg_color_data_vector = color_coding_type_ ? jp_color_coder_.getAverageDataVector() : color_coder_.getAverageDataVector(); compressed_tree_data_in_arg1.read (reinterpret_cast<char*> (&point_avg_color_data_vector_size), sizeof (point_avg_color_data_vector_size)); point_avg_color_data_vector.resize (static_cast<std::size_t> (point_avg_color_data_vector_size)); compressed_color_data_len_ += entropy_coder_.decodeStreamToCharVector(compressed_tree_data_in_arg1, point_avg_color_data_vector); } /* no enhancement layer encoding/decoding TBD */ //! check if the enhancement layer has been received compressed_tree_data_in_arg2.peek(); if(compressed_tree_data_in_arg2.good() && (! compressed_tree_data_in_arg2.eof()) ) do_voxel_grid_enDecoding_ = false; else do_voxel_grid_enDecoding_ = true; if (!do_voxel_grid_enDecoding_) { uint64_t point_count_data_vector_size; uint64_t point_diff_data_vector_size; uint64_t point_diff_color_data_vector_size; // decode amount of points per voxel compressed_tree_data_in_arg2.read (reinterpret_cast<char*> (&point_count_data_vector_size), sizeof (point_count_data_vector_size)); point_count_data_vector_.resize (static_cast<std::size_t> (point_count_data_vector_size)); compressed_point_data_len_ += entropy_coder_.decodeStreamToIntVector(compressed_tree_data_in_arg2, point_count_data_vector_); point_count_data_vector_iterator_ = point_count_data_vector_.begin (); // decode differential point information std::vector<char>& pointDiffDataVector = point_coder_.getDifferentialDataVector(); compressed_tree_data_in_arg2.read (reinterpret_cast<char*> (&point_diff_data_vector_size), sizeof (point_diff_data_vector_size)); pointDiffDataVector.resize (static_cast<std::size_t> (point_diff_data_vector_size)); compressed_point_data_len_ += entropy_coder_.decodeStreamToCharVector (compressed_tree_data_in_arg2, pointDiffDataVector); if (data_with_color_) { // decode differential color information std::vector<char>& pointDiffColorDataVector = color_coder_.getDifferentialDataVector (); compressed_tree_data_in_arg2.read (reinterpret_cast<char*> (&point_diff_color_data_vector_size), sizeof (point_diff_color_data_vector_size)); pointDiffColorDataVector.resize (static_cast<std::size_t> (point_diff_color_data_vector_size)); compressed_color_data_len_ += entropy_coder_.decodeStreamToCharVector (compressed_tree_data_in_arg2, pointDiffColorDataVector); } } /* enhancement layer encoding/decoding EXP */ }; /** \brief * \param point_clouds: an array of pointers to point_clouds to be inspected and modified * by \ref pcl_outlier_filter. */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::remove_outliers (std::vector<PointCloudPtr> &point_clouds, int min_points, double radius, unsigned int debug_level) { // apply a radius filter to remove outliers typedef OctreePointCloudCompression<PointT> colorOctreeCodec; if(min_points > 0) { for(int i=0;i<point_clouds.size();i++){ typename colorOctreeCodec::PointCloudPtr l_ptr = typename colorOctreeCodec::PointCloudPtr(new typename colorOctreeCodec::PointCloud()); pcl::RadiusOutlierRemoval<PointT> rorfilter (true); // Initializing with true will allow us to extract the removed indices rorfilter.setInputCloud (point_clouds[i]); rorfilter.setRadiusSearch (radius); rorfilter.setMinNeighborsInRadius (min_points); rorfilter.setNegative (false); rorfilter.filter (*l_ptr); // swap the pointer IndicesConstPtr indices_rem = rorfilter.getRemovedIndices (); // point_§clouds[i]->erase(indices_rem->begin(),indices_rem->end()); // The resulting cloud_out contains all points of cloud_in that have 'min_points' or more neighbors within the 'radius' search area point_clouds[i] = l_ptr; if (debug_level > 2) { std::cout << "filtered out a total of: " << indices_rem->size() << " outliers" <<std::endl; } // The indices_rem array indexes all points of cloud_in that have less than 'min_points' neighbors within the 0.1 'radius' search area } } } /** \brief * \param point_clouds: a vector of pointers to point_clouds to be inspected and modified * to normalize their bouding boxes s.t. they effectivly can be used for interframe coding. */ template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> BoundingBox OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::normalize_pointclouds(std::vector<PointCloudPtr> &point_clouds, std::vector<BoundingBox, Eigen::aligned_allocator<BoundingBox> > &bounding_boxes, double bb_expand_factor, std::vector<float> dynamic_range, std::vector<float> offset, unsigned int debug_level) { Eigen::Vector4f min_pt_bb(0,0,0,0); Eigen::Vector4f max_pt_bb; pcl::io::BoundingBox bb; bool is_bb_init = false; int bb_align_count=0; std::vector<bool> aligned_flags(point_clouds.size()); // flags to check if a cloud is aligned // initial bounding box min_pt_bb[0]= 1000; min_pt_bb[1]= 1000; min_pt_bb[2]= 1000; max_pt_bb[0]= -1000; max_pt_bb[1]= -1000; max_pt_bb[2]= -1000; for(int k=0;k<point_clouds.size();k++){ Eigen::Vector4f min_pt; Eigen::Vector4f max_pt; pcl::getMinMax3D<PointT>(*point_clouds[k],min_pt,max_pt); if (debug_level > 3) std::cerr << "[ " << min_pt.x() << "," << min_pt.y() << "," << min_pt.z() << "] [" << max_pt.x() << "," << max_pt.y() << "," << max_pt.z() <<"]" << std::endl; // check if min fits bounding box, otherwise adapt the bounding box if( !( (min_pt.x() > min_pt_bb.x()) && (min_pt.y() > min_pt_bb.y()) && (min_pt.z() > min_pt_bb.z()))) { is_bb_init = false; } // check if max fits bounding box, otherwise adapt the bounding box if(!((max_pt.x() < max_pt_bb.x()) && (max_pt.y() < max_pt_bb.y()) && (max_pt.z() < max_pt_bb.z()))) { is_bb_init = false; } if(!is_bb_init) { aligned_flags[k] = false; bb_align_count++; // initialize the bounding box, with bb_expand_factor extra min_pt_bb[0] = min_pt[0] - bb_expand_factor*abs(max_pt[0] - min_pt[0]); min_pt_bb[1] = min_pt[1] - bb_expand_factor*abs(max_pt[1] - min_pt[1]); min_pt_bb[2] = min_pt[2] - bb_expand_factor*abs(max_pt[2] - min_pt[2]); max_pt_bb[0] = max_pt[0] + bb_expand_factor*abs(max_pt[0] - min_pt[0]); max_pt_bb[1] = max_pt[1] + bb_expand_factor*abs(max_pt[1] - min_pt[1]); max_pt_bb[2] = max_pt[2] + bb_expand_factor*abs(max_pt[2] - min_pt[2]); is_bb_init = true; std::cout << "re-intialized bounding box !!! " << std::endl; } else aligned_flags[k] = true; Eigen::Vector4f dyn_range = max_pt_bb - min_pt_bb; bounding_boxes[k].max_xyz = max_pt_bb; bounding_boxes[k].min_xyz = min_pt_bb; for(int j=0; j < point_clouds[k]->size();j++) { // offset the minimum value point_clouds[k]->at(j).x-=min_pt_bb[0]; point_clouds[k]->at(j).y-=min_pt_bb[1]; point_clouds[k]->at(j).z-=min_pt_bb[2]; // dynamic range point_clouds[k]->at(j).x/=dyn_range[0]; point_clouds[k]->at(j).y/=dyn_range[1]; point_clouds[k]->at(j).z/=dyn_range[2]; } // bounding box is expanded Eigen::Vector4f min_pt_res; Eigen::Vector4f max_pt_res; pcl::getMinMax3D<PointT>(*(point_clouds[k]),min_pt_res,max_pt_res); assert(min_pt_res[0] >= 0); assert(min_pt_res[1] >= 0); assert(min_pt_res[2] >= 0); assert(max_pt_res[0] <= 1); assert(max_pt_res[1] <= 1); assert(max_pt_res[2] <= 1); } bb.min_xyz = min_pt_bb; bb.max_xyz = max_pt_bb; return bb; } template<typename PointT, typename LeafT, typename BranchT, typename OctreeT> void OctreePointCloudCodecV2<PointT, LeafT, BranchT, OctreeT>::restore_scaling (PointCloudPtr &point_cloud, const BoundingBox& bb) { Eigen::Vector4f dyn_range = bb.max_xyz - bb.min_xyz; dyn_range[3] = 1; // avoid uninitialized variables if (point_cloud->size() > 0) for (int l = 0; l < point_cloud->size(); l++) { // dynamic range point_cloud->at(l).x *= dyn_range[0]; point_cloud->at(l).y *= dyn_range[1]; point_cloud->at(l).z *= dyn_range[2]; // offset the minimum value point_cloud->at(l).x += bb.min_xyz[0]; point_cloud->at(l).y += bb.min_xyz[1]; point_cloud->at(l).z += bb.min_xyz[2]; } } } } #endif
42.278609
410
0.634601
[ "geometry", "object", "vector", "transform" ]
4dc2422da3b6cd231011d7bfcd7c67c3efa00e20
7,136
cpp
C++
CodeCraft-2019/grid.cpp
pauvrepetit/huawei-code-craft-2019
e48e2e80e4f55a949594dbb12488e77614f84f55
[ "MIT" ]
null
null
null
CodeCraft-2019/grid.cpp
pauvrepetit/huawei-code-craft-2019
e48e2e80e4f55a949594dbb12488e77614f84f55
[ "MIT" ]
null
null
null
CodeCraft-2019/grid.cpp
pauvrepetit/huawei-code-craft-2019
e48e2e80e4f55a949594dbb12488e77614f84f55
[ "MIT" ]
null
null
null
#include "grid.h" #include <utility> #include <stack> using std::pair; using std::make_pair; using std::stack; vector < pair<int, int> > cross_num; vector <bool> cross_num_conflict; stack<int> road_answer; bool numbering(int row, int column, int id){ bool re_bool = true; if(cross_num_conflict[id] == true && cross_num[id] != make_pair(row, column)) return false; if(cross_num_conflict[id] == true) return true; cross_num_conflict[id] = true; cross_num[id] = make_pair(row, column); for(int i = 0;i < 4; ++i){ if(cross_temporary[id].roadId[i] == -1) continue; switch (i) { case 0: re_bool = re_bool & numbering(row - 1, column, cross_temporary[id].to[i]); break; case 1: re_bool = re_bool & numbering(row, column + 1, cross_temporary[id].to[i]); break; case 2: re_bool = re_bool & numbering(row + 1, column, cross_temporary[id].to[i]); break; case 3: re_bool = re_bool & numbering(row, column - 1, cross_temporary[id].to[i]); break; default: break; } } return re_bool; } void preprocessing(){ build_weighted_map(); shortest_path(); return; } bool numbering_cross(){ cross_num.resize(cross.size() + 1 ); cross_num_conflict.resize(cross.size() + 1, false); preprocessing(); if(numbering(0,0,1) == false){ cout << "numbering_cross error" << endl; return false; } return true; } bool lu_to_rd(int from, int to){ if(from == to) return true; if(cross_num[from].first < cross_num[to].first && cross_temporary[from].roadId[2] != -1){ road_answer.push(cross_temporary[from].roadId[2]); if(lu_to_rd(cross_temporary[from].to[2], to) == true) return true; else{ road_answer.pop(); } } if(cross_num[from].second < cross_num[to].second && cross_temporary[from].roadId[1] != -1){ road_answer.push(cross_temporary[from].roadId[1]); if(lu_to_rd(cross_temporary[from].to[1], to) == true) return true; else{ road_answer.pop(); return false; } } else return false; } bool rd_to_lu(int from, int to){ if(from == to) return true; if(cross_num[from].first > cross_num[to].first && cross_temporary[from].roadId[0] != -1){ road_answer.push(cross_temporary[from].roadId[0]); if(rd_to_lu(cross_temporary[from].to[0], to) == true) return true; else{ road_answer.pop(); } } if(cross_num[from].second > cross_num[to].second && cross_temporary[from].roadId[3] != -1){ road_answer.push(cross_temporary[from].roadId[3]); if(rd_to_lu(cross_temporary[from].to[3], to) == true) return true; else{ road_answer.pop(); return false; } } else return false; } bool ru_to_ld(int from, int to){ if(from == to) return true; if(cross_num[from].second > cross_num[to].second && cross_temporary[from].roadId[3] != -1){ road_answer.push(cross_temporary[from].roadId[3]); if(ru_to_ld(cross_temporary[from].to[3], to) == true) return true; else{ road_answer.pop(); } } if(cross_num[from].first < cross_num[to].first && cross_temporary[from].roadId[2] != -1){ road_answer.push(cross_temporary[from].roadId[2]); if(ru_to_ld(cross_temporary[from].to[2], to) == true) return true; else{ road_answer.pop(); return false; } } else return false; } bool ld_to_ru(int from, int to){ if(from == to) return true; if(cross_num[from].second < cross_num[to].second && cross_temporary[from].roadId[1] != -1){ road_answer.push(cross_temporary[from].roadId[1]); if(ld_to_ru(cross_temporary[from].to[1], to) == true) return true; else{ road_answer.pop(); } } if(cross_num[from].first > cross_num[to].first && cross_temporary[from].roadId[0] != -1){ road_answer.push(cross_temporary[from].roadId[0]); if(ld_to_ru(cross_temporary[from].to[0], to) == true) return true; else{ road_answer.pop(); return false; } } else return false; } void clear_road_answer(){ if(road_answer.empty() == true) return; int id = road_answer.top(); road_answer.pop(); clear_road_answer(); outfile << ", " << id; } void output(string &answerPath){ outfile.open(answerPath, ios::out); for(decltype(car.size()) i = 0; i < car.size(); i++){ if((cross_num[car[i].from ].first <= cross_num[car[i].to ].first) && (cross_num[car[i].from ].second <= cross_num[car[i].to ].second)){ outfile << "(" << car[i].id << ", " << car[i].planTime; if(lu_to_rd(car[i].from, car[i].to) == false){ cout << "can't find a road" << endl; //return; short_road_output(car[i].from, car[i].to); } clear_road_answer(); outfile << ")" << endl; } if((cross_num[car[i].from ].first > cross_num[car[i].to ].first) && (cross_num[car[i].from ].second > cross_num[car[i].to ].second)){ outfile << "(" << car[i].id << ", " << car[i].planTime + 80; if(rd_to_lu(car[i].from, car[i].to) == false){ cout << "can't find a road" << endl; //return; short_road_output(car[i].from, car[i].to); } clear_road_answer(); outfile << ")" << endl; } if((cross_num[car[i].from ].first <= cross_num[car[i].to ].first) && (cross_num[car[i].from ].second > cross_num[car[i].to ].second)){ outfile << "(" << car[i].id << ", " << car[i].planTime + 160; if(ru_to_ld(car[i].from, car[i].to) == false){ cout << "can't find a road" << endl; //return; short_road_output(car[i].from, car[i].to); } clear_road_answer(); outfile << ")" << endl; } if((cross_num[car[i].from ].first > cross_num[car[i].to ].first) && (cross_num[car[i].from ].second <= cross_num[car[i].to ].second)){ outfile << "(" << car[i].id << ", " << car[i].planTime + 240; if(ld_to_ru(car[i].from, car[i].to) == false){ cout << "can't find a road" << endl; //return; short_road_output(car[i].from, car[i].to); } clear_road_answer(); outfile << ")" << endl; } } } bool grid_solve(string &answerPath){ if(numbering_cross() == false) return false; output(answerPath); return true; }
30.237288
143
0.524383
[ "vector" ]
4dc94508cea57c1f543f65fa735bca6e7293aaf2
11,540
cc
C++
utilities/hdrhistogram.cc
vpn03/kv_engine
a3131a099154c39a0f7b0458bf0cc4ea38363a64
[ "MIT", "BSD-3-Clause" ]
null
null
null
utilities/hdrhistogram.cc
vpn03/kv_engine
a3131a099154c39a0f7b0458bf0cc4ea38363a64
[ "MIT", "BSD-3-Clause" ]
null
null
null
utilities/hdrhistogram.cc
vpn03/kv_engine
a3131a099154c39a0f7b0458bf0cc4ea38363a64
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2019-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #include "hdrhistogram.h" #include <folly/lang/Assume.h> #include <nlohmann/json.hpp> #include <platform/cb_malloc.h> #include <spdlog/fmt/fmt.h> #include <iostream> #include <optional> // Custom deleter for the hdr_histogram struct. void HdrHistogram::HdrDeleter::operator()(struct hdr_histogram* val) { hdr_close_ex(val, cb_free); } HdrHistogram::HdrHistogram(uint64_t lowestDiscernibleValue, int64_t highestTrackableValue, int significantFigures, Iterator::IterMode iterMode) : defaultIterationMode(iterMode) { auto handle = histogram.wlock(); resize(handle, lowestDiscernibleValue, highestTrackableValue, significantFigures); } HdrHistogram& HdrHistogram::operator+=(const HdrHistogram& other) { /* * Note: folly::acquireLockedPair() takes an exclusive lock on * this->histogram as we pass it a non-const ref. Where as it takes a shared * lock on other.histogram as we pass it a const ref. We can do this as we * only need to write to the ptr of this->histogram. (see * folly::acquireLocked() source code comments for more information regard * how it takes locks) */ auto lockPair = folly::acquireLockedPair(this->histogram, other.histogram); // Don't use structured binding as this messes up clang-analyzer, analyzing // the destruction of folly's locks. WHistoLockedPtr& thisLock = lockPair.first; ConstRHistoLockedPtr& otherLock = lockPair.second; if (otherLock->get()->total_count > 0) { // work out if we need to resize the receiving histogram auto newDiscernibleMin = getMinDiscernibleValue(thisLock); auto newMax = getMaxTrackableValue(thisLock); auto newSigfig = getSigFigAccuracy(thisLock); bool resize = false; if (getMinDiscernibleValue(otherLock) < newDiscernibleMin) { newDiscernibleMin = getMinDiscernibleValue(otherLock); resize = true; } if (getMaxTrackableValue(otherLock) > newMax) { newMax = getMaxTrackableValue(otherLock); resize = true; } if (getSigFigAccuracy(otherLock) > newSigfig) { newSigfig = getSigFigAccuracy(otherLock); resize = true; } if (resize) { this->resize(thisLock, newDiscernibleMin, newMax, newSigfig); } hdr_add(thisLock->get(), otherLock->get()); } return *this; } HdrHistogram& HdrHistogram::operator=(const HdrHistogram& other) { if (this != &other) { // reset this object to make sure we are in a state to copy too this->reset(); // take advantage of the code already written in for the addition // assigment operator *this += other; } return *this; } bool HdrHistogram::addValue(uint64_t v) { return hdr_record_value(histogram.rlock()->get(), v); } bool HdrHistogram::addValueAndCount(uint64_t v, uint64_t count) { return hdr_record_values(histogram.rlock()->get(), v, count); } uint64_t HdrHistogram::getValueCount() const { return static_cast<uint64_t>(histogram.rlock()->get()->total_count); } uint64_t HdrHistogram::getMinValue() const { return static_cast<uint64_t>(hdr_min(histogram.rlock()->get())); } uint64_t HdrHistogram::getMaxValue() const { return static_cast<uint64_t>(hdr_max(histogram.rlock()->get())); } void HdrHistogram::reset() { hdr_reset(histogram.wlock()->get()); } uint64_t HdrHistogram::getValueAtPercentile(double percentage) const { return hdr_value_at_percentile(histogram.rlock()->get(), percentage); } HdrHistogram::Iterator HdrHistogram::makeLinearIterator( int64_t valueUnitsPerBucket) const { HdrHistogram::Iterator itr(histogram, Iterator::IterMode::Linear); hdr_iter_linear_init(&itr, itr.histoRLockPtr->get(), valueUnitsPerBucket); return itr; } HdrHistogram::Iterator HdrHistogram::makeLogIterator(int64_t firstBucketWidth, double log_base) const { HdrHistogram::Iterator itr(histogram, Iterator::IterMode::Log); hdr_iter_log_init( &itr, itr.histoRLockPtr->get(), firstBucketWidth, log_base); return itr; } HdrHistogram::Iterator HdrHistogram::makePercentileIterator( uint32_t ticksPerHalfDist) const { HdrHistogram::Iterator itr(histogram, Iterator::IterMode::Percentiles); hdr_iter_percentile_init(&itr, itr.histoRLockPtr->get(), ticksPerHalfDist); return itr; } HdrHistogram::Iterator HdrHistogram::makeRecordedIterator() const { HdrHistogram::Iterator itr(histogram, Iterator::IterMode::Recorded); hdr_iter_recorded_init(&itr, itr.histoRLockPtr->get()); return itr; } HdrHistogram::Iterator HdrHistogram::makeIterator( Iterator::IterMode mode) const { switch (mode) { case Iterator::IterMode::Percentiles: return makePercentileIterator(5); case Iterator::IterMode::Log: return makeLogIterator(1, 2); case Iterator::IterMode::Linear: { int64_t bucketWidth = getMaxTrackableValue() / 20; if (bucketWidth < 0) { bucketWidth = 1; } return makeLinearIterator(bucketWidth); } case Iterator::IterMode::Recorded: return makeRecordedIterator(); } folly::assume_unreachable(); } HdrHistogram::Iterator HdrHistogram::getHistogramsIterator() const { return makeIterator(defaultIterationMode); } std::optional<std::pair<uint64_t, uint64_t>> HdrHistogram::Iterator::getNextValueAndCount() { std::optional<std::pair<uint64_t, uint64_t>> valueAndCount; if (hdr_iter_next(this)) { auto value = static_cast<uint64_t>(this->value); uint64_t count = 0; switch (type) { case Iterator::IterMode::Log: count = specifics.log.count_added_in_this_iteration_step; break; case Iterator::IterMode::Linear: count = specifics.linear.count_added_in_this_iteration_step; break; case Iterator::IterMode::Percentiles: value = highest_equivalent_value; count = cumulative_count - lastCumulativeCount; lastCumulativeCount = cumulative_count; break; case Iterator::IterMode::Recorded: count = this->count; break; } return valueAndCount = std::make_pair(value, count); } else { return valueAndCount; } } std::optional<std::tuple<uint64_t, uint64_t, uint64_t>> HdrHistogram::Iterator::getNextBucketLowHighAndCount() { std::optional<std::tuple<uint64_t, uint64_t, uint64_t>> bucketHighLowCount; auto valueAndCount = getNextValueAndCount(); if (valueAndCount.has_value()) { bucketHighLowCount = { lastVal, valueAndCount->first, valueAndCount->second}; lastVal = valueAndCount->first; } return bucketHighLowCount; } std::optional<std::pair<uint64_t, double>> HdrHistogram::Iterator::getNextValueAndPercentile() { std::optional<std::pair<uint64_t, double>> valueAndPer; if (type == Iterator::IterMode::Percentiles) { if (hdr_iter_next(this)) { valueAndPer = {highest_equivalent_value, specifics.percentiles.percentile}; } } return valueAndPer; } std::string HdrHistogram::Iterator::dumpValues() { fmt::memory_buffer dump; while (auto pair = getNextValueAndCount()) { fmt::format_to(dump, "Value[{}-{}]\tCount:{}\t\n", value_iterated_from, value_iterated_to, pair->second); } fmt::format_to(dump, "Total:\t{}\n", total_count); return {dump.data(), dump.size()}; } void HdrHistogram::printPercentiles() const { hdr_percentiles_print(histogram.rlock()->get(), stdout, 5, 1.0, CLASSIC); } void HdrHistogram::dumpLinearValues(int64_t bucketWidth) const { HdrHistogram::Iterator itr = makeLinearIterator(bucketWidth); fmt::print(stdout, itr.dumpValues()); } void HdrHistogram::dumpLogValues(int64_t firstBucketWidth, double log_base) const { HdrHistogram::Iterator itr = makeLogIterator(firstBucketWidth, log_base); fmt::print(stdout, itr.dumpValues()); } nlohmann::json HdrHistogram::to_json() const { nlohmann::json rootObj; // Five is the number of iteration steps per half-distance to 100%. auto itr = makePercentileIterator(5); rootObj["total"] = itr.total_count; // bucketsLow represents the starting value of the first bucket // e.g. if the first bucket was from [0 - 10]ms then it would be 0 rootObj["bucketsLow"] = itr.value_iterated_from; nlohmann::json dataArr; int64_t lastval = 0; while (auto pair = itr.getNextValueAndPercentile()) { if (!pair.has_value()) break; dataArr.push_back( {pair->first, itr.cumulative_count - lastval, pair->second}); lastval = itr.cumulative_count; } rootObj["data"] = dataArr; return rootObj; } std::string HdrHistogram::to_string() const { return to_json().dump(); } size_t HdrHistogram::getMemFootPrint() const { return hdr_get_memory_size(histogram.rlock()->get()) + sizeof(HdrHistogram); } double HdrHistogram::getMean() const { return hdr_mean(histogram.rlock()->get()); } void HdrHistogram::resize(WHistoLockedPtr& histoLockPtr, uint64_t lowestDiscernibleValue, int64_t highestTrackableValue, int significantFigures) { // hdr_init_ex will also check but will just return EINVAL. Check here // first so we can generate amore useful exception message, as this could be // a common mistake when adding a new histogram if (lowestDiscernibleValue == 0) { // lowestDiscernibleValue set to zero is not meaningful throw std::invalid_argument(fmt::format( "HdrHistogram lowestDiscernibleValue:{} must be greater than 0", lowestDiscernibleValue)); } struct hdr_histogram* hist = nullptr; auto status = hdr_init_ex(lowestDiscernibleValue, highestTrackableValue, significantFigures, &hist, // Pointer to initialise cb_calloc); if (status != 0) { throw std::system_error( status, std::generic_category(), fmt::format("HdrHistogram init failed, " "params lowestDiscernibleValue:{} " "highestTrackableValue:{} significantFigures:{}", lowestDiscernibleValue, highestTrackableValue, significantFigures)); } if (*histoLockPtr) { hdr_add(hist, histoLockPtr->get()); } histoLockPtr->reset(hist); }
34.969697
80
0.64714
[ "object" ]
4dcc40e552c13d9a9083a5c05eca414cdd088974
3,124
cc
C++
Geometry/TrackerNumberingBuilder/test/GeometricDetAnalyzer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Geometry/TrackerNumberingBuilder/test/GeometricDetAnalyzer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Geometry/TrackerNumberingBuilder/test/GeometricDetAnalyzer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
// -*- C++ -*- // // Package: GeometricDetAnalyzer // Class: GeometricDetAnalyzer // /**\class GeometricDetAnalyzer GeometricDetAnalyzer.cc test/GeometricDetAnalyzer/src/GeometricDetAnalyzer.cc Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: Tommaso Boccali // Created: Tue Jul 26 08:47:57 CEST 2005 // // // system include files #include <memory> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DetectorDescription/Core/interface/DDCompactView.h" #include "Geometry/Records/interface/IdealGeometryRecord.h" #include "Geometry/TrackerNumberingBuilder/interface/GeometricDet.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" // CLHEP Dependency #include <CLHEP/Vector/ThreeVector.h> // // // class decleration // class GeometricDetAnalyzer : public edm::one::EDAnalyzer<> { public: explicit GeometricDetAnalyzer(const edm::ParameterSet&); ~GeometricDetAnalyzer() override; void beginJob() override {} void analyze(edm::Event const& iEvent, edm::EventSetup const&) override; void endJob() override {} }; // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // GeometricDetAnalyzer::GeometricDetAnalyzer(const edm::ParameterSet& iConfig) { //now do what ever initialization is needed } GeometricDetAnalyzer::~GeometricDetAnalyzer() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) } // // member functions // // ------------ method called to produce the data ------------ void GeometricDetAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; edm::LogInfo("GeometricDetAnalyzer") << "Here I am "; // // get the GeometricDet // edm::ESHandle<GeometricDet> pDD; iSetup.get<IdealGeometryRecord>().get(pDD); edm::LogInfo("GeometricDetAnalyzer") << " Top node is " << pDD.product(); edm::LogInfo("GeometricDetAnalyzer") << " And Contains Daughters: " << pDD->deepComponents().size(); std::vector<const GeometricDet*> det = pDD->deepComponents(); for (auto& it : det) { const DDRotationMatrix& res = it->rotation(); DD3Vector x, y, z; res.GetComponents(x, y, z); DD3Vector colx(x.X(), x.Y(), x.Z()); DD3Vector coly(y.X(), y.Y(), y.Z()); DD3Vector colz(z.X(), z.Y(), z.Z()); DDRotationMatrix result(colx, coly, colz); DD3Vector cx, cy, cz; result.GetComponents(cx, cy, cz); if (cx.Cross(cy).Dot(cz) < 0.5) { edm::LogInfo("GeometricDetAnalyzer") << "Left Handed Rotation Matrix detected; making it right handed: " << it->name(); } } } //define this as a plug-in DEFINE_FWK_MODULE(GeometricDetAnalyzer);
27.646018
108
0.703905
[ "geometry", "vector" ]
4dd37a6d58b813670a66ed036baa37528aa36f8e
832
cpp
C++
UVa Online Judge/10774.cpp
xiezeju/ACM-Code-Archives
db135ed0953adcf5c7ab37a00b3f9458291ce0d7
[ "MIT" ]
1
2022-02-24T12:44:30.000Z
2022-02-24T12:44:30.000Z
UVa Online Judge/10774.cpp
xiezeju/ACM-Code-Archives
db135ed0953adcf5c7ab37a00b3f9458291ce0d7
[ "MIT" ]
null
null
null
UVa Online Judge/10774.cpp
xiezeju/ACM-Code-Archives
db135ed0953adcf5c7ab37a00b3f9458291ce0d7
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define LSOne(S) ((S) & -(S)) using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<ll> vll; const int INF = 0x3f3f3f3f; const long long LLINF = 4e18; const double EPS = 1e-9; const int N = 1010; int find(int n) { int cnt = 0; while (n) cnt++, n >>= 1; return cnt; } int jos(int n) { int len = find(n); n ^= (1 << (len - 1)); n <<= 1; n |= 1; return n; } int main() { int t, caseno = 0, n, survivor; scanf("%d", &t); while (t--) { scanf("%d", &n); int cnt = 0; for (;;) { cnt++; if ((survivor = jos(n)) == n) break; n = survivor; } printf("Case %d: %d %d\n", ++caseno, cnt - 1, n); } return 0; }
18.909091
57
0.489183
[ "vector" ]
4dd447bcc0525ad5c2e674d176bbfeaff12ffb4b
22,965
cpp
C++
Decoder/configuration.cpp
liqiangnlp/SMT.Decoder
922dd23df01789185ae6b4e252432864344bf40f
[ "MIT" ]
null
null
null
Decoder/configuration.cpp
liqiangnlp/SMT.Decoder
922dd23df01789185ae6b4e252432864344bf40f
[ "MIT" ]
null
null
null
Decoder/configuration.cpp
liqiangnlp/SMT.Decoder
922dd23df01789185ae6b4e252432864344bf40f
[ "MIT" ]
null
null
null
/* * $Id: * 0030 * * $File: * configuration.cpp * * $Proj: * Decoder for Statistical Machine Translation * * $Func: * config * * $Version: * 0.0.1 * * $Created by: * Qiang Li * * $Email * liqiangneu@gmail.com * * $Last Modified by: * 2013-03-14,10:13 */ #include "configuration.h" namespace decoder_configuration { bool Configuration::Init (STRPAIR &param) { CheckParamsInConf (param); if (!convert_pt_2_binary_flag_) { CheckFilesInConf (param); } return true; } bool Configuration::CheckParamsInConf (STRPAIR &param) { // check for "nround" string paramKey = "nround"; string paramDefValue = "1"; CheckEachParamInConf (param, paramKey, paramDefValue); nround_ = atoi (param[paramKey].c_str()); // check for "ngram" paramKey = "ngram"; paramDefValue = "3"; CheckEachParamInConf (param, paramKey, paramDefValue); ngram_ = atoi (param[paramKey].c_str()); // check for "beamsize" paramKey = "beamsize"; paramDefValue = "30"; CheckEachParamInConf (param, paramKey, paramDefValue); beamsize_ = atoi (param[paramKey].c_str()); // check for "nbest" paramKey = "nbest"; paramDefValue = "30"; CheckEachParamInConf (param, paramKey, paramDefValue); nbest_ = atoi (param[paramKey].c_str() ) > beamsize_ ? beamsize_ : atoi( param[paramKey].c_str()); // check for "nref" paramKey = "nref"; paramDefValue = "4"; CheckEachParamInConf (param, paramKey, paramDefValue); nref_ = atoi (param[paramKey].c_str()); // check for "maxreorderdis" paramKey = "maxreorderdis"; paramDefValue = "10"; CheckEachParamInConf( param, paramKey, paramDefValue ); max_reordering_distance_ = atoi (param[paramKey].c_str()); // check for "maxphraselength" paramKey = "maxphraselength"; paramDefValue = "3"; CheckEachParamInConf (param, paramKey, paramDefValue); max_phrase_length_ = atoi (param[paramKey].c_str()); // check for "nthread" paramKey = "nthread"; paramDefValue = "0"; CheckEachParamInConf (param, paramKey, paramDefValue); nthread_ = atoi (param[paramKey].c_str()); // check for "freefeature" paramKey = "freefeature"; paramDefValue = "0"; CheckEachParamInConf (param, paramKey, paramDefValue); free_feature_ = atoi (param[paramKey].c_str()); // check for "usepuncpruning" paramKey = "usepunctpruning"; paramDefValue = "1"; CheckEachParamInConf (param, paramKey, paramDefValue); use_punct_pruning_ = (param[paramKey] == "0" ? false : true); // check for "usecubepruning" paramKey = "usecubepruning"; paramDefValue = "1"; CheckEachParamInConf (param, paramKey, paramDefValue); use_cube_pruning_ = (param[paramKey] == "0" ? false : true); // check for "usecubepruninginc" if (!recase_flag_) { paramKey = "usecubepruninginc"; paramDefValue = "1"; CheckEachParamInConf (param, paramKey, paramDefValue); use_cube_pruninginc_ = (param[paramKey] == "0" ? false : true); use_cube_pruning_ = (use_cube_pruninginc_ == true ? false : use_cube_pruning_); } else { use_cube_pruninginc_ = false; } // check for "use-me-reorder" paramKey = "use-me-reorder"; paramDefValue = "1"; CheckEachParamInConf (param, paramKey, paramDefValue); use_me_reorder_ = (param[paramKey] == "0" ? false : true); // check for "use-msd-reorder" paramKey = "use-msd-reorder"; paramDefValue = "0"; CheckEachParamInConf (param, paramKey, paramDefValue); use_msd_reorder_ = (param[paramKey] == "0" ? false : true); // check for "useemptytranslation" paramKey = "useemptytranslation"; paramDefValue = "0"; CheckEachParamInConf (param, paramKey, paramDefValue); use_empty_translation_ = (param[paramKey] == "0" ? false : true); // check for "outputemptytranslation" paramKey = "outputemptytranslation"; paramDefValue = "0"; CheckEachParamInConf (param, paramKey, paramDefValue); output_empty_translation_ = (param[paramKey] == "0" ? false : true); // check for "use-context-sensitive-wd" paramKey = "use-context-sensitive-wd"; paramDefValue = "0"; CheckEachParamInConf (param, paramKey, paramDefValue); use_context_sensitive_wd_ = (param[paramKey] == "0" ? false : true); if (use_context_sensitive_wd_) { paramKey = "context-sensitive-wd-weights"; paramDefValue = "0.5 0.5"; CheckEachParamInConf(param, paramKey, paramDefValue); paramKey = "context-sensitive-wd-ranges"; paramDefValue = "-3:3 -3:3"; CheckEachParamInConf(param, paramKey, paramDefValue); paramKey = "context-sensitive-wd-fixedfs"; paramDefValue = "0 0"; CheckEachParamInConf(param, paramKey, paramDefValue); features.ParsingContextSensitiveFeatures(param); } // check for "outputoov" paramKey = "outputoov"; paramDefValue = "0"; CheckEachParamInConf (param, paramKey, paramDefValue); output_oov_ = (param[paramKey] == "0" ? false : true); // check for "labeloov" paramKey = "labeloov"; paramDefValue = "1"; CheckEachParamInConf (param, paramKey, paramDefValue); label_oov_ = (param[paramKey] == "0" ? false : true); // check for "englishstring" paramKey = "englishstring"; paramDefValue = "0"; CheckEachParamInConf (param, paramKey, paramDefValue); english_string_ = (param[paramKey] == "0" ? false : true); // check for "-MERT" paramKey = "-MERT"; paramDefValue = "0"; CheckEachParamInConf (param, paramKey, paramDefValue); mert_flag_ = (param[paramKey] == "0" ? false : true); // check for "recasemethod" paramKey = "recasemethod"; if (param[paramKey] != "l2r" && param[paramKey] != "cyk") { param[paramKey] = "l2r"; } paramDefValue = "l2r"; CheckEachParamInConf (param, paramKey, paramDefValue); recase_method_ = param[paramKey]; // init config file config_file_ = param["-config"]; // check for "log"; paramKey = "-log"; paramDefValue = "niutransserver.log.txt"; CheckEachParamInConf (param, paramKey, paramDefValue); log_file_ = param[paramKey]; // check for "output"; paramKey = "-output"; paramDefValue = "niutransserver.output.txt"; CheckEachParamInConf (param, paramKey, paramDefValue); output_file_ = param[paramKey]; if (mert_flag_) { // check for "mert_tmp_file_" paramKey = "-mert-tmp-file"; paramDefValue = "niutransserver.mert.tmp.txt"; CheckEachParamInConf(param, paramKey, paramDefValue); mert_tmp_file_ = param[paramKey]; // check for "mert_log_file_" paramKey = "-mert-log-file"; paramDefValue = "niutransserver.mert.log.txt"; CheckEachParamInConf(param, paramKey, paramDefValue); mert_log_file_ = param[paramKey]; // check for "mert_config_file_" paramKey = "-mert-config-file"; paramDefValue = "niutransserver.mert.config.txt"; CheckEachParamInConf(param, paramKey, paramDefValue); mert_config_file_ = param[paramKey]; } // check for "weights" paramKey = "weights"; paramDefValue = "1.000 0.500 0.200 0.200 0.200 0.200 0.500 0.500 -0.100 1.000 0 0 0 0 0 0 0"; CheckEachParamInConf (param, paramKey, paramDefValue); // check for "ranges" paramKey = "ranges"; paramDefValue = "-3:7 -1:3 0:3 0:0.4 0:3 0:0.4 -3:3 -3:3 -3:0 -3:3 0:0 0:0 0:0 0:0 0:0 0:0 0:0"; CheckEachParamInConf (param, paramKey, paramDefValue); // check for "fixedfs" paramKey = "fixedfs"; paramDefValue = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"; CheckEachParamInConf (param, paramKey, paramDefValue); features.ParsingFeatures (param); return true; } bool Configuration::CheckEachParamInConf (STRPAIR &param, string &paramKey, string &defValue) { if (param.find (paramKey) == param.end()) param[paramKey] = defValue; return true; } bool Configuration::CheckFilesInConf (STRPAIR &param) { // check for LM file string fileKey = "Ngram-LanguageModel-File"; checkFileInConf (param, fileKey); lm_file_ = param["Ngram-LanguageModel-File"]; // check for Target-side vocabulary fileKey = "Target-Vocab-File"; checkFileInConf (param, fileKey); target_vocab_file_ = param["Target-Vocab-File"]; // check for MaxEnt-based lexicalized reordering model if (use_me_reorder_) { fileKey = "ME-Reordering-Table"; checkFileInConf (param, fileKey); metabFile = param["ME-Reordering-Table"]; } // check for MSD lexicalized reordering model if (use_msd_reorder_) { fileKey = "MSD-Reordering-Model"; checkFileInConf( param, fileKey ); msdtabFile = param[ "MSD-Reordering-Model" ]; } // check for context sensitive word deletion model if (use_context_sensitive_wd_) { fileKey = "Context-Sensitive-WD"; checkFileInConf (param, fileKey); context_sensitive_model_ = param[fileKey]; } // check for phrase translation model if (!phrase_table_binary_flag_) { fileKey = "Phrase-Table"; checkFileInConf (param, fileKey); phrase_table_file_ = param["Phrase-Table"]; } else { fileKey = "Phrase-Table-Binary"; checkFileInConf (param, fileKey); phrase_table_file_ = param["Phrase-Table-Binary"]; fileKey = "Phrase-Table-Binary-SrcPhr"; checkFileInConf (param, fileKey); source_phrase_file_ = param["Phrase-Table-Binary-SrcPhr"]; fileKey = "Phrase-Table-Binary-TgtPhr"; checkFileInConf (param, fileKey); target_phrase_file_ = param["Phrase-Table-Binary-TgtPhr"]; } // check for Test file if (!support_service_flag_) { if (!mert_flag_) { fileKey = "-test"; checkFileInComm (param, fileKey); testFile = param["-test"]; } else { fileKey = "-dev"; checkFileInComm (param, fileKey); testFile = param["-dev"]; } } return true; } bool Configuration::checkFileInConf( STRPAIR &param , string &fileKey ) { if( param.find( fileKey ) != param.end() ) { ifstream inFile( param[ fileKey ].c_str() ); if( !inFile ) { cerr<<"ERROR: Please check the path of \""<<fileKey<<"\".\n"<<flush; exit( 1 ); } inFile.clear(); inFile.close(); } else { cerr<<"ERROR: Please add parameter \""<<fileKey<<"\" in your config file.\n"<<flush; exit( 1 ); } return true; } bool Configuration::checkFileInComm( STRPAIR &param , string &fileKey ) { if( param.find( fileKey ) != param.end() ) { ifstream inFile( param[ fileKey ].c_str() ); if( !inFile ) { cerr<<"ERROR: Please check the path of \""<<fileKey<<"\".\n"; cerr<<" file="<<param[fileKey]<<"\n"<<flush; exit( 1 ); } inFile.clear(); inFile.close(); } else { cerr<<"ERROR: Please add parameter \""<<fileKey<<"\" in your command.\n"<<flush; exit( 1 ); } return true; } bool Features::ParsingFeatures (map<string,string> &param) { vector< string > weightsVector; vector< string > rangesVector ; vector< string > fixedfsVector; Split (param["weights"], ' ', weightsVector); Split (param["ranges"], ' ', rangesVector); Split (param["fixedfs"], ' ', fixedfsVector); features_number_ = weightsVector.size(); if (features_number_ != rangesVector.size() || features_number_ != fixedfsVector.size()) { cerr<<"ERROR: Values number of 'weights', 'ranges', 'fixedfs' in config file is not the same!\n"<<flush; exit (1); } size_t pos = 0; for (vector< string >::iterator iter = weightsVector.begin(); iter != weightsVector.end(); ++iter) { float w = (float)atof(iter->c_str()); float f = (float)atof(fixedfsVector.at(pos).c_str()); vector<string> range; Split (rangesVector.at( pos ), ':', range); float min = (float)atof(range.at(0).c_str()); float max = (float)atof(range.at(1).c_str()); FeatureValue featureValue(w, min, max, f); feature_values_.push_back(featureValue); ++pos; } return true; } bool Features::ParsingFeatures(string &in_file_name) { cerr<<"ParsingFeatures from "<<in_file_name<<"...\n"<<flush; ifstream in_file(in_file_name.c_str()); if (!in_file) { cerr<<"Can not open file "<<in_file_name<<"\n"<<flush; exit(1); } string line; getline(in_file, line); RmEndSpace(line); RmStartSpace(line); ClearIllegalChar(line); features_number_ = atoi(line.c_str()); feature_values_.clear(); while (getline(in_file,line)) { RmEndSpace(line); RmStartSpace(line); ClearIllegalChar(line); vector<string> v_single_feature; Split(line, ' ', v_single_feature); if (v_single_feature.size() != 5) { cerr<<"Error: Format in config file is incorrect!\n"<<flush; exit(1); } float w = (float)atof(v_single_feature.at(1).c_str()); float min = (float)atof(v_single_feature.at(2).c_str()); float max = (float)atof(v_single_feature.at(3).c_str()); float f = (float)atof(v_single_feature.at(4).c_str()); FeatureValue feature_value(w, min, max, f); feature_values_.push_back(feature_value); } if (feature_values_.size() != features_number_) { cerr<<"Error: Format in config file is incorrect!\n"<<flush; exit(1); } in_file.close(); return true; } bool Features::ParsingContextSensitiveFeatures(map<string, string> &parameter) { vector<string> v_weights; vector<string> v_ranges; vector<string> v_fixedfs; Split (parameter["context-sensitive-wd-weights"], ' ', v_weights); Split (parameter["context-sensitive-wd-ranges"], ' ', v_ranges); Split (parameter["context-sensitive-wd-fixedfs"], ' ', v_fixedfs); cswd_feature_number_ = v_weights.size(); if (cswd_feature_number_ != v_ranges.size() || cswd_feature_number_ != v_fixedfs.size()) { cerr<<"Error: Values number of 'context-sensitive-wd-weights', 'context-sensitive-wd-ranges', and 'context-sensitive-wd-fixedfs' is not the same!\n"<<flush; exit (1); } size_t tmp_position = 0; for (vector<string>::iterator iter = v_weights.begin(); iter != v_weights.end(); ++iter) { float w = (float)atof(iter->c_str()); float f = (float)atof(v_fixedfs.at(tmp_position).c_str()); vector<string> v_range; Split (v_ranges.at(tmp_position), ':', v_range); float min = (float)atof(v_range.at(0).c_str()); float max = (float)atof(v_range.at(1).c_str()); FeatureValue feature_value(w, min, max, f); v_context_sensitive_wd_feature_.push_back(feature_value); ++tmp_position; } return true; } bool Configuration::PrintConfig () { cerr<<setfill(' '); cerr<<"Configuration:"<<"\n" <<" nround : "<<nround_ <<"\n" <<" ngram : "<<ngram_ <<"\n" <<" beamsize : "<<beamsize_ <<"\n" <<" nbest : "<<nbest_ <<"\n" <<" nref : "<<nref_ <<"\n" <<" maxreorderdis : "<<max_reordering_distance_<<"\n" <<" maxphraselength : "<<max_phrase_length_<<"\n" <<" freefeature : "<<free_feature_ <<"\n" <<" nthread : "<<nthread_ <<"\n\n" <<" usepunctpruning : "<<(use_punct_pruning_ == true ? "true" : "false")<<"\n" <<" usecubepruning : "<<(use_cube_pruning_ == true ? "true" : "false")<<"\n" <<" usecubepruninginc : "<<(use_cube_pruninginc_ == true ? "true" : "false")<<"\n" <<" use-me-reorder : "<<(use_me_reorder_ == true ? "true" : "false")<<"\n" <<" use-msd-reorder : "<<(use_msd_reorder_ == true ? "true" : "false")<<"\n" <<" useemptytranslation : "<<(use_empty_translation_ == true ? "true" : "false")<<"\n" <<" outputemptytranslation : "<<(output_empty_translation_ == true ? "true" : "false")<<"\n" <<" outputoov : "<<(output_oov_ == true ? "true" : "false")<<"\n" <<" labeloov : "<<(label_oov_ == true ? "true" : "false")<<"\n" <<" englishstring : "<<(english_string_ == true ? "true" : "false")<<"\n" <<" MERT : "<<(mert_flag_ == true ? "true" : "false")<<"\n"; if (recase_flag_) { cerr<<" recasemethod :"<<recase_method_<<"\n\n"; } else { cerr<<"\n"; } cerr<<" config = "<<config_file_<<"\n" <<" test = "<<testFile <<"\n" <<" output = "<<output_file_<<"\n"; if (!recase_flag_) { cerr<<" log = "<<log_file_<<"\n" <<"\n"<<flush; } else { cerr<<"\n"<<flush; } return true; } bool Configuration::PrintFeatures () { cerr<<setiosflags( ios::fixed )<<setprecision( 2 ); cerr<<"Weights of Feature:"<<"\n" <<" N-gram LM 00 :" <<" w=" <<features.feature_values_.at(0).weight_ <<" f=" <<features.feature_values_.at(0).fixed_ <<" min="<<features.feature_values_.at(0).min_value_ <<" max="<<features.feature_values_.at(0).max_value_<<"\n" <<" # of Tar-words 01 :" <<" w=" <<features.feature_values_.at(1).weight_ <<" f=" <<features.feature_values_.at(1).fixed_ <<" min="<<features.feature_values_.at(1).min_value_ <<" max="<<features.feature_values_.at(1).max_value_<<"\n" <<" Pr(e|f) 02 :" <<" w=" <<features.feature_values_.at(2).weight_ <<" f=" <<features.feature_values_.at(2).fixed_ <<" min="<<features.feature_values_.at(2).min_value_ <<" max="<<features.feature_values_.at(2).max_value_<<"\n" <<" Lex(e|f) 03 :" <<" w=" <<features.feature_values_.at(3).weight_ <<" f=" <<features.feature_values_.at(3).fixed_ <<" min="<<features.feature_values_.at(3).min_value_ <<" max="<<features.feature_values_.at(3).max_value_<<"\n" <<" Pr(f|e) 04 :" <<" w=" <<features.feature_values_.at(4).weight_ <<" f=" <<features.feature_values_.at(4).fixed_ <<" min="<<features.feature_values_.at(4).min_value_ <<" max="<<features.feature_values_.at(4).max_value_<<"\n" <<" Lex(f|e) 05 :" <<" w=" <<features.feature_values_.at(5).weight_ <<" f=" <<features.feature_values_.at(5).fixed_ <<" min="<<features.feature_values_.at(5).min_value_ <<" max="<<features.feature_values_.at(5).max_value_<<"\n" <<" # of Phrases 06 :" <<" w=" <<features.feature_values_.at(6).weight_ <<" f=" <<features.feature_values_.at(6).fixed_ <<" min="<<features.feature_values_.at(6).min_value_ <<" max="<<features.feature_values_.at(6).max_value_<<"\n"; if (!recase_flag_) { cerr<<" # of bi-lex links 07 :" <<" w=" <<features.feature_values_.at(7).weight_ <<" f=" <<features.feature_values_.at(7).fixed_ <<" min="<<features.feature_values_.at(7).min_value_ <<" max="<<features.feature_values_.at(7).max_value_<<"\n" <<" # of NULL-trans 08 :" <<" w=" <<features.feature_values_.at(8).weight_ <<" f=" <<features.feature_values_.at(8).fixed_ <<" min="<<features.feature_values_.at(8).min_value_ <<" max="<<features.feature_values_.at(8).max_value_<<"\n" <<" ME Reorder Model 09 :" <<" w=" <<features.feature_values_.at(9).weight_ <<" f=" <<features.feature_values_.at(9).fixed_ <<" min="<<features.feature_values_.at(9).min_value_ <<" max="<<features.feature_values_.at(9).max_value_<<"\n" <<" <UNDEFINED> 10 :" <<" w=" <<features.feature_values_.at(10).weight_ <<" f=" <<features.feature_values_.at(10).fixed_ <<" min="<<features.feature_values_.at(10).min_value_ <<" max="<<features.feature_values_.at(10).max_value_<<"\n" <<" MSD Pre & Mono 11 :" <<" w=" <<features.feature_values_.at(11).weight_ <<" f=" <<features.feature_values_.at(11).fixed_ <<" min="<<features.feature_values_.at(11).min_value_ <<" max="<<features.feature_values_.at(11).max_value_<<"\n" <<" MSD Pre & Swap 12 :" <<" w=" <<features.feature_values_.at(12).weight_ <<" f=" <<features.feature_values_.at(12).fixed_ <<" min="<<features.feature_values_.at(12).min_value_ <<" max="<<features.feature_values_.at(12).max_value_<<"\n" <<" MSD Pre & Disc 13 :" <<" w=" <<features.feature_values_.at(13).weight_ <<" f=" <<features.feature_values_.at(13).fixed_ <<" min="<<features.feature_values_.at(13).min_value_ <<" max="<<features.feature_values_.at(13).max_value_<<"\n" <<" MSD Fol & Mono 14 :" <<" w=" <<features.feature_values_.at(14).weight_ <<" f=" <<features.feature_values_.at(14).fixed_ <<" min="<<features.feature_values_.at(14).min_value_ <<" max="<<features.feature_values_.at(14).max_value_<<"\n" <<" MSD Fol & Swap 15 :" <<" w=" <<features.feature_values_.at(15).weight_ <<" f=" <<features.feature_values_.at(15).fixed_ <<" min="<<features.feature_values_.at(15).min_value_ <<" max="<<features.feature_values_.at(15).max_value_<<"\n" <<" MSD Fol & Disc 16 :" <<" w=" <<features.feature_values_.at(16).weight_ <<" f=" <<features.feature_values_.at(16).fixed_ <<" min="<<features.feature_values_.at(16).min_value_ <<" max="<<features.feature_values_.at(16).max_value_<<"\n" <<"\n"<<flush; if (free_feature_ != 0) { if (free_feature_ <= features.feature_values_.size() - 17) { for (int i = 0; i < free_feature_; ++i) { cerr<<" Free Feature ["<<i + 1<<"] :" <<" w=" <<features.feature_values_.at( i + 17 ).weight_ <<" f=" <<features.feature_values_.at( i + 17 ).fixed_ <<" min="<<features.feature_values_.at( i + 17 ).min_value_ <<" max="<<features.feature_values_.at( i + 17 ).max_value_<<"\n"; } cerr<<"\n"<<flush; } else { cerr<<"ERROR: Parameter 'freefeature' in config file do not adapt to the phrasetable!\n"; exit( 1 ); } } } else { cerr<<"\n"<<flush; } if (use_context_sensitive_wd_) { cerr<<" CSWD Align 01 :" <<" w=" <<features.v_context_sensitive_wd_feature_.at(0).weight_ <<" f=" <<features.v_context_sensitive_wd_feature_.at(0).fixed_ <<" min="<<features.v_context_sensitive_wd_feature_.at(0).min_value_ <<" max="<<features.v_context_sensitive_wd_feature_.at(0).max_value_<<"\n" <<" CSWD Unalign 02 :" <<" w=" <<features.v_context_sensitive_wd_feature_.at(1).weight_ <<" f=" <<features.v_context_sensitive_wd_feature_.at(1).fixed_ <<" min="<<features.v_context_sensitive_wd_feature_.at(1).min_value_ <<" max="<<features.v_context_sensitive_wd_feature_.at(1).max_value_<<"\n" <<"\n"<<flush; } return true; } }
35.007622
162
0.611452
[ "vector", "model" ]
4dd51037ded9202eeddb8390bcd7a3b73ae11861
4,657
cxx
C++
cxx/esroofit/src/RooNonCentralBinning.cxx
KaveIO/Eskapade-ROOT
3be7ea68f1fec206c00ba8e2fd0fbe1c04585eac
[ "Apache-2.0" ]
null
null
null
cxx/esroofit/src/RooNonCentralBinning.cxx
KaveIO/Eskapade-ROOT
3be7ea68f1fec206c00ba8e2fd0fbe1c04585eac
[ "Apache-2.0" ]
null
null
null
cxx/esroofit/src/RooNonCentralBinning.cxx
KaveIO/Eskapade-ROOT
3be7ea68f1fec206c00ba8e2fd0fbe1c04585eac
[ "Apache-2.0" ]
1
2019-01-11T10:20:34.000Z
2019-01-11T10:20:34.000Z
/***************************************************************************** * Project: RooFit * * Package: RooFitCore * * @(#)root/roofitcore:$Id$ * Authors: * * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * * * * Copyright (c) 2000-2005, Regents of the University of California * * and Stanford University. All rights resized. * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ ////////////////////////////////////////////////////////////////////////////// // // BEGIN_HTML // Class RooNonCentralBinning is an implements RooAbsBinning in terms // of an array of boundary values, posing no constraints on the choice // of binning, thus allowing variable bin sizes. Various methods allow // the user to add single bin boundaries, mirrored pairs, or sets of // uniformly spaced boundaries. // END_HTML // // esroofit includes. #include <esroofit/RooNonCentralBinning.h> // ROOT includes. #include <Riostream.h> // STL includes. #include <algorithm> using namespace std; ClassImp(RooNonCentralBinning) //_____________________________________________________________________________ RooNonCentralBinning::RooNonCentralBinning(Double_t xlo, Double_t xhi, const char *name) : RooBinning(xlo, xhi, name) { } //_____________________________________________________________________________ RooNonCentralBinning::RooNonCentralBinning(Int_t nbins, Double_t xlo, Double_t xhi, const char *name) : RooBinning(nbins, xlo, xhi, name) { _center.resize(nbins, -1.); } //_____________________________________________________________________________ RooNonCentralBinning::RooNonCentralBinning(Int_t nbins, const Double_t *boundaries, const char *name) : RooBinning(nbins, boundaries, name) { _center.resize(nbins, -1.); } //_____________________________________________________________________________ RooNonCentralBinning::RooNonCentralBinning(const RooNonCentralBinning &other, const char *name) : RooBinning(other, name), _center(other._center) { // Copy constructor } //_____________________________________________________________________________ RooNonCentralBinning::RooNonCentralBinning(const RooBinning &other, const char *name) : RooBinning(other, name) { _center.resize(_nbins, -1.); } //_____________________________________________________________________________ RooNonCentralBinning::~RooNonCentralBinning() { } //_____________________________________________________________________________ Double_t RooNonCentralBinning::binCenter(Int_t bin) const { //double center = RooBinning::binCenter(bin); return (_center[bin] < 0 ? RooBinning::binCenter(bin) : _center[bin]); } //_____________________________________________________________________________ void RooNonCentralBinning::setBinCenter(Int_t bin, Double_t value) { if (_nbins > static_cast<int>(_center.size())) { _center.resize(_nbins, -1.); } // set the position of the center of bin 'bin' if (bin >= 0 && bin < _nbins) { _center[bin] = value; } } //_____________________________________________________________________________ void RooNonCentralBinning::setAverageFromData(const RooDataSet &input, const RooRealVar &obs) { const RooArgSet *values = input.get(); RooRealVar *var = (RooRealVar *) values->find(obs.GetName()); if (var == NULL) { return; } if (_nbins != static_cast<int>(_center.size())) { _center.resize(_nbins, -1.); } std::vector<Double_t> x0(_nbins, 0.); std::vector<Double_t> x1(_nbins, 0.); for (Int_t i = 0; i < input.numEntries(); i++) { input.get(i); double w = input.weight(); double x = var->getVal(); int bin = this->binNumber(x); x0[bin] += w; x1[bin] += w * x; } for (Int_t i = 0; i < _nbins; i++) { _center[i] = (x0[i] > 0 ? x1[i] / x0[i] : -1.); } }
32.566434
103
0.611982
[ "vector" ]
4dd932a97726d3ccd0e4da83d5845fbcb54bcfbb
34,029
cpp
C++
src/lp_data/HighsSolution.cpp
ogmundur/HiGHS
ed3a64f589b3a1962783caef793dc20b158210d4
[ "MIT" ]
null
null
null
src/lp_data/HighsSolution.cpp
ogmundur/HiGHS
ed3a64f589b3a1962783caef793dc20b158210d4
[ "MIT" ]
null
null
null
src/lp_data/HighsSolution.cpp
ogmundur/HiGHS
ed3a64f589b3a1962783caef793dc20b158210d4
[ "MIT" ]
null
null
null
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the HiGHS linear optimization suite */ /* */ /* Written and engineered 2008-2021 at the University of Edinburgh */ /* */ /* Available as open-source under the MIT License */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file lp_data/HighsSolution.cpp * @brief Class-independent utilities for HiGHS * @author Julian Hall, Ivet Galabova, Qi Huangfu and Michael Feldmeier */ #include "lp_data/HighsSolution.h" #include <string> #include <vector> #include "ipm/IpxSolution.h" #include "lp_data/HighsInfo.h" #include "lp_data/HighsModelUtils.h" #include "lp_data/HighsOptions.h" #include "lp_data/HighsSolutionDebug.h" #include "util/HighsUtils.h" #ifdef IPX_ON #include "ipm/IpxStatus.h" #include "ipm/ipx/include/ipx_status.h" #include "ipm/ipx/src/lp_solver.h" #endif void getPrimalDualInfeasibilities(const HighsLp& lp, const HighsBasis& basis, const HighsSolution& solution, HighsSolutionParams& solution_params) { double primal_feasibility_tolerance = solution_params.primal_feasibility_tolerance; double dual_feasibility_tolerance = solution_params.dual_feasibility_tolerance; // solution_params are the values computed in this method. int& num_primal_infeasibilities = solution_params.num_primal_infeasibilities; double& max_primal_infeasibility = solution_params.max_primal_infeasibility; double& sum_primal_infeasibilities = solution_params.sum_primal_infeasibilities; int& num_dual_infeasibilities = solution_params.num_dual_infeasibilities; double& max_dual_infeasibility = solution_params.max_dual_infeasibility; double& sum_dual_infeasibilities = solution_params.sum_dual_infeasibilities; num_primal_infeasibilities = 0; max_primal_infeasibility = 0; sum_primal_infeasibilities = 0; num_dual_infeasibilities = 0; max_dual_infeasibility = 0; sum_dual_infeasibilities = 0; double primal_infeasibility; double dual_infeasibility; double lower; double upper; double value; double dual; HighsBasisStatus status; for (int iVar = 0; iVar < lp.numCol_ + lp.numRow_; iVar++) { if (iVar < lp.numCol_) { int iCol = iVar; lower = lp.colLower_[iCol]; upper = lp.colUpper_[iCol]; value = solution.col_value[iCol]; dual = solution.col_dual[iCol]; status = basis.col_status[iCol]; } else { int iRow = iVar - lp.numCol_; lower = lp.rowLower_[iRow]; upper = lp.rowUpper_[iRow]; value = solution.row_value[iRow]; dual = -solution.row_dual[iRow]; status = basis.row_status[iRow]; } // Flip dual according to lp.sense_ dual *= (int)lp.sense_; double primal_residual = std::max(lower - value, value - upper); primal_infeasibility = std::max(primal_residual, 0.); if (primal_infeasibility > primal_feasibility_tolerance) num_primal_infeasibilities++; max_primal_infeasibility = std::max(primal_infeasibility, max_primal_infeasibility); sum_primal_infeasibilities += primal_infeasibility; if (status != HighsBasisStatus::BASIC) { // Nonbasic variable: look for dual infeasibility if (primal_residual >= -primal_feasibility_tolerance) { // At a bound double middle = (lower + upper) * 0.5; if (lower < upper) { // Non-fixed variable if (value < middle) { // At lower dual_infeasibility = std::max(-dual, 0.); } else { // At Upper dual_infeasibility = std::max(dual, 0.); } } else { // Fixed variable dual_infeasibility = 0; } } else { // Between bounds (or free) dual_infeasibility = fabs(dual); } if (dual_infeasibility > dual_feasibility_tolerance) num_dual_infeasibilities++; max_dual_infeasibility = std::max(dual_infeasibility, max_dual_infeasibility); sum_dual_infeasibilities += dual_infeasibility; } } } #ifdef HiGHSDEV void analyseSimplexAndHighsSolutionDifferences( const HighsModelObject& highs_model_object) { const HighsSolution& solution = highs_model_object.solution_; const HighsLp& simplex_lp = highs_model_object.simplex_lp_; const HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; const HighsSolutionParams& scaled_solution_params = highs_model_object.scaled_solution_params_; const SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; const HighsScale& scale = highs_model_object.scale_; const double scaled_primal_feasibility_tolerance = scaled_solution_params.primal_feasibility_tolerance; const double scaled_dual_feasibility_tolerance = scaled_solution_params.dual_feasibility_tolerance; // Go through the columns, finding the differences in nonbasic column values // and duals int num_nonbasic_col_value_differences = 0; double sum_nonbasic_col_value_differences = 0; int num_nonbasic_col_dual_differences = 0; double sum_nonbasic_col_dual_differences = 0; for (int iCol = 0; iCol < simplex_lp.numCol_; iCol++) { int iVar = iCol; if (simplex_basis.nonbasicFlag_[iVar] == NONBASIC_FLAG_TRUE) { // Consider this nonbasic column double local_col_value = simplex_info.workValue_[iVar] * scale.col_[iCol]; double local_col_dual = (int)simplex_lp.sense_ * simplex_info.workDual_[iVar] / (scale.col_[iCol] / scale.cost_); double value_difference = fabs(local_col_value - solution.col_value[iCol]); double dual_difference = fabs(local_col_dual - solution.col_dual[iCol]); if (value_difference > scaled_primal_feasibility_tolerance) num_nonbasic_col_value_differences++; sum_nonbasic_col_value_differences += value_difference; if (value_difference > scaled_dual_feasibility_tolerance) num_nonbasic_col_dual_differences++; sum_nonbasic_col_dual_differences += dual_difference; } } // Go through the rows, finding the differences in nonbasic and // basic row values and duals, as well as differences in basic // column values and duals int num_nonbasic_row_value_differences = 0; double sum_nonbasic_row_value_differences = 0; int num_nonbasic_row_dual_differences = 0; double sum_nonbasic_row_dual_differences = 0; int num_basic_col_value_differences = 0; double sum_basic_col_value_differences = 0; int num_basic_col_dual_differences = 0; double sum_basic_col_dual_differences = 0; int num_basic_row_value_differences = 0; double sum_basic_row_value_differences = 0; int num_basic_row_dual_differences = 0; double sum_basic_row_dual_differences = 0; for (int ix = 0; ix < simplex_lp.numRow_; ix++) { int iRow = ix; int iVar = simplex_lp.numCol_ + iRow; if (simplex_basis.nonbasicFlag_[iVar] == NONBASIC_FLAG_TRUE) { // Consider this nonbasic row double local_row_value = -simplex_info.workValue_[iVar] / scale.row_[iRow]; double local_row_dual = (int)simplex_lp.sense_ * simplex_info.workDual_[iVar] * (scale.row_[iRow] * scale.cost_); double value_difference = fabs(local_row_value - solution.row_value[iRow]); double dual_difference = fabs(local_row_dual - solution.row_dual[iRow]); if (value_difference > scaled_primal_feasibility_tolerance) num_nonbasic_row_value_differences++; sum_nonbasic_row_value_differences += value_difference; if (value_difference > scaled_dual_feasibility_tolerance) num_nonbasic_row_dual_differences++; sum_nonbasic_row_dual_differences += dual_difference; } // Consider the basic variable associated with this row index iVar = simplex_basis.basicIndex_[ix]; if (iVar < simplex_lp.numCol_) { // Consider this basic column int iCol = iVar; double local_col_value = simplex_info.baseValue_[ix] * scale.col_[iCol]; double local_col_dual = 0; double value_difference = fabs(local_col_value - solution.col_value[iCol]); double dual_difference = fabs(local_col_dual - solution.col_dual[iCol]); if (value_difference > scaled_primal_feasibility_tolerance) num_basic_col_value_differences++; sum_basic_col_value_differences += value_difference; if (value_difference > scaled_dual_feasibility_tolerance) num_basic_col_dual_differences++; sum_basic_col_dual_differences += dual_difference; } else { // Consider this basic row iRow = iVar - simplex_lp.numCol_; double local_row_value = -simplex_info.baseValue_[ix] / scale.row_[iRow]; double local_row_dual = 0; double value_difference = fabs(local_row_value - solution.row_value[iRow]); double dual_difference = fabs(local_row_dual - solution.row_dual[iRow]); if (value_difference > scaled_primal_feasibility_tolerance) num_basic_row_value_differences++; sum_basic_row_value_differences += value_difference; if (value_difference > scaled_dual_feasibility_tolerance) num_basic_row_dual_differences++; sum_basic_row_dual_differences += dual_difference; } } double acceptable_difference_sum = scaled_primal_feasibility_tolerance + scaled_dual_feasibility_tolerance; bool significant_nonbasic_value_differences = sum_nonbasic_col_value_differences + sum_nonbasic_row_value_differences > 0; bool significant_basic_value_differences = sum_basic_col_value_differences + sum_basic_row_value_differences > 2 * acceptable_difference_sum; bool significant_nonbasic_col_dual_differences = sum_nonbasic_col_dual_differences > acceptable_difference_sum; bool significant_nonbasic_row_dual_differences = sum_nonbasic_row_dual_differences > acceptable_difference_sum; bool significant_basic_dual_differences = sum_basic_col_dual_differences + sum_basic_row_dual_differences > 0; if (significant_nonbasic_value_differences || significant_basic_value_differences || significant_nonbasic_col_dual_differences || significant_nonbasic_row_dual_differences || significant_basic_dual_differences) { printf( "In transition(): There are significant value and dual differences\n"); /* printf(" nonbasic_value_differences = %d\n", significant_nonbasic_value_differences); printf(" basic_value_differences = %d\n", significant_basic_value_differences); printf(" nonbasic_col_dual_differences = %d\n", significant_nonbasic_col_dual_differences); printf(" nonbasic_row_dual_differences = %d\n", significant_nonbasic_row_dual_differences); printf(" basic_dual_differences = %d\n", significant_basic_dual_differences); */ } else { printf( "In transition(): There are no significant value and dual " "differences\n"); } if (significant_nonbasic_value_differences) { if (sum_nonbasic_col_value_differences > 0) printf("Nonbasic column value differences: %6d (%11.4g)\n", num_nonbasic_col_value_differences, sum_nonbasic_col_value_differences); if (sum_nonbasic_row_value_differences > 0) printf("Nonbasic row value differences: %6d (%11.4g)\n", num_nonbasic_row_value_differences, sum_nonbasic_row_value_differences); } if (significant_basic_value_differences) { if (sum_basic_col_value_differences > acceptable_difference_sum) printf("Basic column value differences: %6d (%11.4g)\n", num_basic_col_value_differences, sum_basic_col_value_differences); if (sum_basic_row_value_differences > acceptable_difference_sum) printf("Basic row value differences: %6d (%11.4g)\n", num_basic_row_value_differences, sum_basic_row_value_differences); } if (significant_nonbasic_col_dual_differences) printf("Nonbasic column dual differences: %6d (%11.4g)\n", num_nonbasic_col_dual_differences, sum_nonbasic_col_dual_differences); if (significant_nonbasic_row_dual_differences) printf("Nonbasic row dual differences: %6d (%11.4g)\n", num_nonbasic_row_dual_differences, sum_nonbasic_row_dual_differences); if (significant_basic_dual_differences) { if (sum_basic_col_dual_differences > 0) printf("Basic column dual differences: %6d (%11.4g)\n", num_basic_col_dual_differences, sum_basic_col_dual_differences); if (sum_basic_row_dual_differences > 0) printf("Basic row dual differences: %6d (%11.4g)\n", num_basic_row_dual_differences, sum_basic_row_dual_differences); } printf( "grep_transition,%s,%.15g,%d,%g,%d,%g,%s,%d,%g,%d,%g,%d,%g,%d,%g,Primal,%" "d,%g,%d,%g,Dual,%d,%g,%d,%g\n", simplex_lp.model_name_.c_str(), simplex_info.primal_objective_value, scaled_solution_params.num_primal_infeasibilities, scaled_solution_params.sum_primal_infeasibilities, scaled_solution_params.num_dual_infeasibilities, scaled_solution_params.sum_dual_infeasibilities, utilHighsModelStatusToString(highs_model_object.scaled_model_status_) .c_str(), num_nonbasic_col_value_differences, sum_nonbasic_col_value_differences, num_nonbasic_row_value_differences, sum_nonbasic_row_value_differences, num_basic_col_value_differences, sum_basic_col_value_differences, num_basic_row_value_differences, sum_basic_row_value_differences, num_nonbasic_col_dual_differences, sum_nonbasic_col_dual_differences, num_nonbasic_row_dual_differences, sum_nonbasic_row_dual_differences, num_basic_col_dual_differences, sum_basic_col_dual_differences, num_basic_row_dual_differences, sum_basic_row_dual_differences); } #endif #ifdef IPX_ON HighsStatus ipxSolutionToHighsSolution( FILE* logfile, const HighsLp& lp, const std::vector<double>& rhs, const std::vector<char>& constraint_type, const int ipx_num_col, const int ipx_num_row, const std::vector<double>& ipx_x, const std::vector<double>& ipx_slack_vars, // const std::vector<double>& ipx_y, HighsSolution& highs_solution) { // Resize the HighsSolution highs_solution.col_value.resize(lp.numCol_); highs_solution.row_value.resize(lp.numRow_); // highs_solution.col_dual.resize(lp.numCol_); // highs_solution.row_dual.resize(lp.numRow_); const std::vector<double>& ipx_col_value = ipx_x; const std::vector<double>& ipx_row_value = ipx_slack_vars; // const std::vector<double>& ipx_col_dual = ipx_x; // const std::vector<double>& ipx_row_dual = ipx_y; // Row activities are needed to set activity values of free rows - // which are ignored by IPX vector<double> row_activity; bool get_row_activities = ipx_num_row < lp.numRow_; #ifdef HiGHSDEV // For debugging, get the row activities if there are any boxed // constraints get_row_activities = get_row_activities || ipx_num_col > lp.numCol_; #endif if (get_row_activities) row_activity.assign(lp.numRow_, 0); for (int col = 0; col < lp.numCol_; col++) { highs_solution.col_value[col] = ipx_col_value[col]; // highs_solution.col_dual[col] = ipx_col_dual[col]; if (get_row_activities) { // Accumulate row activities to assign value to free rows for (int el = lp.Astart_[col]; el < lp.Astart_[col + 1]; el++) { int row = lp.Aindex_[el]; row_activity[row] += highs_solution.col_value[col] * lp.Avalue_[el]; } } } int ipx_row = 0; int ipx_slack = lp.numCol_; int num_boxed_rows = 0; for (int row = 0; row < lp.numRow_; row++) { double lower = lp.rowLower_[row]; double upper = lp.rowUpper_[row]; if (lower <= -HIGHS_CONST_INF && upper >= HIGHS_CONST_INF) { // Free row - removed by IPX so set it to its row activity highs_solution.row_value[row] = row_activity[row]; // highs_solution.row_dual[row] = 0; } else { // Non-free row, so IPX will have it if ((lower > -HIGHS_CONST_INF && upper < HIGHS_CONST_INF) && (lower < upper)) { // Boxed row - look at its slack num_boxed_rows++; highs_solution.row_value[row] = ipx_col_value[ipx_slack]; // highs_solution.row_dual[row] = -ipx_col_dual[ipx_slack]; // Update the slack to be used for boxed rows ipx_slack++; } else { highs_solution.row_value[row] = rhs[ipx_row] - ipx_row_value[ipx_row]; // highs_solution.row_dual[row] = -ipx_row_dual[ipx_row]; } // Update the IPX row index ipx_row++; } } assert(ipx_row == ipx_num_row); assert(ipx_slack == ipx_num_col); // Flip dual according to lp.sense_ /* for (int iCol = 0; iCol < lp.numCol_; iCol++) { highs_solution.col_dual[iCol] *= (int)lp.sense_; } for (int iRow = 0; iRow < lp.numRow_; iRow++) { highs_solution.row_dual[iRow] *= (int)lp.sense_; } */ return HighsStatus::OK; } HighsStatus ipxBasicSolutionToHighsBasicSolution( FILE* logfile, const HighsLp& lp, const std::vector<double>& rhs, const std::vector<char>& constraint_type, const IpxSolution& ipx_solution, HighsBasis& highs_basis, HighsSolution& highs_solution) { // Resize the HighsSolution and HighsBasis highs_solution.col_value.resize(lp.numCol_); highs_solution.row_value.resize(lp.numRow_); highs_solution.col_dual.resize(lp.numCol_); highs_solution.row_dual.resize(lp.numRow_); highs_basis.col_status.resize(lp.numCol_); highs_basis.row_status.resize(lp.numRow_); const std::vector<double>& ipx_col_value = ipx_solution.ipx_col_value; const std::vector<double>& ipx_row_value = ipx_solution.ipx_row_value; const std::vector<double>& ipx_col_dual = ipx_solution.ipx_col_dual; const std::vector<double>& ipx_row_dual = ipx_solution.ipx_row_dual; const std::vector<ipx::Int>& ipx_col_status = ipx_solution.ipx_col_status; const std::vector<ipx::Int>& ipx_row_status = ipx_solution.ipx_row_status; // Set up meaningful names for values of ipx_col_status and ipx_row_status to // be used later in comparisons const ipx::Int ipx_basic = 0; const ipx::Int ipx_nonbasic_at_lb = -1; const ipx::Int ipx_nonbasic_at_ub = -2; const ipx::Int ipx_superbasic = -3; // Row activities are needed to set activity values of free rows - // which are ignored by IPX vector<double> row_activity; bool get_row_activities = ipx_solution.num_row < lp.numRow_; #ifdef HiGHSDEV // For debugging, get the row activities if there are any boxed // constraints get_row_activities = get_row_activities || ipx_solution.num_col > lp.numCol_; #endif if (get_row_activities) row_activity.assign(lp.numRow_, 0); int num_basic_variables = 0; for (int col = 0; col < lp.numCol_; col++) { bool unrecognised = false; if (ipx_col_status[col] == ipx_basic) { // Column is basic highs_basis.col_status[col] = HighsBasisStatus::BASIC; highs_solution.col_value[col] = ipx_col_value[col]; highs_solution.col_dual[col] = 0; } else if (ipx_col_status[col] == ipx_nonbasic_at_lb) { // Column is nonbasic at lower bound highs_basis.col_status[col] = HighsBasisStatus::LOWER; highs_solution.col_value[col] = ipx_col_value[col]; highs_solution.col_dual[col] = ipx_col_dual[col]; } else if (ipx_col_status[col] == ipx_nonbasic_at_ub) { // Column is nonbasic at upper bound highs_basis.col_status[col] = HighsBasisStatus::UPPER; highs_solution.col_value[col] = ipx_col_value[col]; highs_solution.col_dual[col] = ipx_col_dual[col]; } else if (ipx_col_status[col] == ipx_superbasic) { // Column is superbasic highs_basis.col_status[col] = HighsBasisStatus::ZERO; highs_solution.col_value[col] = ipx_col_value[col]; highs_solution.col_dual[col] = ipx_col_dual[col]; } else { unrecognised = true; #ifdef HiGHSDEV printf( "\nError in IPX conversion: Unrecognised value ipx_col_status[%2d] = " "%d\n", col, (int)ipx_col_status[col]); #endif } #ifdef HiGHSDEV if (unrecognised) printf("Bounds [%11.4g, %11.4g]\n", lp.colLower_[col], lp.colUpper_[col]); if (unrecognised) printf( "Col %2d ipx_col_status[%2d] = %2d; x[%2d] = %11.4g; z[%2d] = " "%11.4g\n", col, col, (int)ipx_col_status[col], col, ipx_col_value[col], col, ipx_col_dual[col]); #endif assert(!unrecognised); if (unrecognised) { HighsLogMessage(logfile, HighsMessageType::ERROR, "Unrecognised ipx_col_status value from IPX"); return HighsStatus::Error; } if (get_row_activities) { // Accumulate row activities to assign value to free rows for (int el = lp.Astart_[col]; el < lp.Astart_[col + 1]; el++) { int row = lp.Aindex_[el]; row_activity[row] += highs_solution.col_value[col] * lp.Avalue_[el]; } } if (highs_basis.col_status[col] == HighsBasisStatus::BASIC) num_basic_variables++; } int ipx_row = 0; int ipx_slack = lp.numCol_; int num_boxed_rows = 0; int num_boxed_rows_basic = 0; int num_boxed_row_slacks_basic = 0; for (int row = 0; row < lp.numRow_; row++) { bool unrecognised = false; double lower = lp.rowLower_[row]; double upper = lp.rowUpper_[row]; #ifdef HiGHSDEV int this_ipx_row = ipx_row; #endif if (lower <= -HIGHS_CONST_INF && upper >= HIGHS_CONST_INF) { // Free row - removed by IPX so make it basic at its row activity highs_basis.row_status[row] = HighsBasisStatus::BASIC; highs_solution.row_value[row] = row_activity[row]; highs_solution.row_dual[row] = 0; } else { // Non-free row, so IPX will have it if ((lower > -HIGHS_CONST_INF && upper < HIGHS_CONST_INF) && (lower < upper)) { // Boxed row - look at its slack num_boxed_rows++; double slack_value = ipx_col_value[ipx_slack]; double slack_dual = ipx_col_dual[ipx_slack]; double value = slack_value; double dual = -slack_dual; if (ipx_row_status[ipx_row] == ipx_basic) { // Row is basic num_boxed_rows_basic++; highs_basis.row_status[row] = HighsBasisStatus::BASIC; highs_solution.row_value[row] = value; highs_solution.row_dual[row] = 0; } else if (ipx_col_status[ipx_slack] == ipx_basic) { // Slack is basic num_boxed_row_slacks_basic++; highs_basis.row_status[row] = HighsBasisStatus::BASIC; highs_solution.row_value[row] = value; highs_solution.row_dual[row] = 0; } else if (ipx_col_status[ipx_slack] == ipx_nonbasic_at_lb) { // Slack at lower bound highs_basis.row_status[row] = HighsBasisStatus::LOWER; highs_solution.row_value[row] = value; highs_solution.row_dual[row] = dual; } else if (ipx_col_status[ipx_slack] == ipx_nonbasic_at_ub) { // Slack is at its upper bound assert(ipx_col_status[ipx_slack] == ipx_nonbasic_at_ub); highs_basis.row_status[row] = HighsBasisStatus::UPPER; highs_solution.row_value[row] = value; highs_solution.row_dual[row] = dual; } else { unrecognised = true; #ifdef HiGHSDEV printf( "\nError in IPX conversion: Row %2d (IPX row %2d) has " "unrecognised value ipx_col_status[%2d] = %d\n", row, ipx_row, ipx_slack, (int)ipx_col_status[ipx_slack]); #endif } // Update the slack to be used for boxed rows ipx_slack++; } else if (ipx_row_status[ipx_row] == ipx_basic) { // Row is basic highs_basis.row_status[row] = HighsBasisStatus::BASIC; highs_solution.row_value[row] = rhs[ipx_row] - ipx_row_value[ipx_row]; highs_solution.row_dual[row] = 0; } else { // Nonbasic row at fixed value, lower bound or upper bound assert(ipx_row_status[ipx_row] == -1); // const ipx::Int ipx_nonbasic_row = -1; double value = rhs[ipx_row] - ipx_row_value[ipx_row]; double dual = -ipx_row_dual[ipx_row]; if (constraint_type[ipx_row] == '>') { // Row is at its lower bound highs_basis.row_status[row] = HighsBasisStatus::LOWER; highs_solution.row_value[row] = value; highs_solution.row_dual[row] = dual; } else if (constraint_type[ipx_row] == '<') { // Row is at its upper bound highs_basis.row_status[row] = HighsBasisStatus::UPPER; highs_solution.row_value[row] = value; highs_solution.row_dual[row] = dual; } else if (constraint_type[ipx_row] == '=') { // Row is at its fixed value highs_basis.row_status[row] = HighsBasisStatus::LOWER; highs_solution.row_value[row] = value; highs_solution.row_dual[row] = dual; } else { unrecognised = true; #ifdef HiGHSDEV printf( "\nError in IPX conversion: Row %2d: cannot handle " "constraint_type[%2d] = %d\n", row, ipx_row, constraint_type[ipx_row]); #endif } } // Update the IPX row index ipx_row++; } #ifdef HiGHSDEV if (unrecognised) printf("Bounds [%11.4g, %11.4g]\n", lp.rowLower_[row], lp.rowUpper_[row]); if (unrecognised) printf( "Row %2d ipx_row_status[%2d] = %2d; s[%2d] = %11.4g; y[%2d] = " "%11.4g\n", row, this_ipx_row, (int)ipx_row_status[this_ipx_row], this_ipx_row, ipx_row_value[this_ipx_row], this_ipx_row, ipx_row_dual[this_ipx_row]); #endif assert(!unrecognised); if (unrecognised) { HighsLogMessage(logfile, HighsMessageType::ERROR, "Unrecognised ipx_row_status value from IPX"); return HighsStatus::Error; } if (highs_basis.row_status[row] == HighsBasisStatus::BASIC) num_basic_variables++; } assert(num_basic_variables == lp.numRow_); highs_basis.valid_ = true; assert(ipx_row == ipx_solution.num_row); assert(ipx_slack == ipx_solution.num_col); // Flip dual according to lp.sense_ for (int iCol = 0; iCol < lp.numCol_; iCol++) { highs_solution.col_dual[iCol] *= (int)lp.sense_; } for (int iRow = 0; iRow < lp.numRow_; iRow++) { highs_solution.row_dual[iRow] *= (int)lp.sense_; } #ifdef HiGHSDEV if (num_boxed_rows) printf("Of %d boxed rows: %d are basic and %d have basic slacks\n", num_boxed_rows, num_boxed_rows_basic, num_boxed_row_slacks_basic); #endif return HighsStatus::OK; } #endif std::string iterationsToString(const HighsIterationCounts& iterations_counts) { std::string iteration_statement = ""; bool not_first = false; int num_positive_count = 0; if (iterations_counts.simplex) num_positive_count++; if (iterations_counts.ipm) num_positive_count++; if (iterations_counts.crossover) num_positive_count++; if (num_positive_count == 0) { iteration_statement += "0 iterations; "; return iteration_statement; } if (num_positive_count > 1) iteration_statement += "("; int count; std::string count_str; count = iterations_counts.simplex; if (count) { count_str = std::to_string(count); if (not_first) iteration_statement += "; "; iteration_statement += count_str + " " + "Simplex"; not_first = true; } count = iterations_counts.ipm; if (count) { count_str = std::to_string(count); if (not_first) iteration_statement += "; "; iteration_statement += count_str + " " + "IPM"; not_first = true; } count = iterations_counts.crossover; if (count) { count_str = std::to_string(count); if (not_first) iteration_statement += "; "; iteration_statement += count_str + " " + "Crossover"; not_first = true; } if (num_positive_count > 1) { iteration_statement += ") Iterations; "; } else { iteration_statement += " iterations; "; } return iteration_statement; } void resetModelStatusAndSolutionParams(HighsModelObject& highs_model_object) { resetModelStatusAndSolutionParams( highs_model_object.unscaled_model_status_, highs_model_object.unscaled_solution_params_, highs_model_object.options_); resetModelStatusAndSolutionParams(highs_model_object.scaled_model_status_, highs_model_object.scaled_solution_params_, highs_model_object.options_); } void resetModelStatusAndSolutionParams(HighsModelStatus& model_status, HighsSolutionParams& solution_params, const HighsOptions& options) { model_status = HighsModelStatus::NOTSET; resetSolutionParams(solution_params, options); } void resetSolutionParams(HighsSolutionParams& solution_params, const HighsOptions& options) { // Set the feasibility tolerances - not affected by invalidateSolutionParams solution_params.primal_feasibility_tolerance = options.primal_feasibility_tolerance; solution_params.dual_feasibility_tolerance = options.dual_feasibility_tolerance; // Save a copy of the unscaled solution params to recover the iteration counts // and objective HighsSolutionParams save_solution_params; copySolutionObjectiveParams(solution_params, save_solution_params); // Invalidate the solution params then reset the feasibility // tolerances and recover the objective invalidateSolutionParams(solution_params); copySolutionObjectiveParams(save_solution_params, solution_params); } // Invalidate a HighsSolutionParams instance void invalidateSolutionParams(HighsSolutionParams& solution_params) { solution_params.objective_function_value = 0; invalidateSolutionStatusParams(solution_params); invalidateSolutionInfeasibilityParams(solution_params); } // Invalidate the solution status values in a HighsSolutionParams // instance. void invalidateSolutionStatusParams(HighsSolutionParams& solution_params) { solution_params.primal_status = PrimalDualStatus::STATUS_NOTSET; solution_params.dual_status = PrimalDualStatus::STATUS_NOTSET; } // Invalidate the infeasibility values in a HighsSolutionParams // instance. Setting the number of infeasibilities to negative values // indicates that they aren't known void invalidateSolutionInfeasibilityParams( HighsSolutionParams& solution_params) { solution_params.num_primal_infeasibilities = -1; solution_params.sum_primal_infeasibilities = 0; solution_params.max_primal_infeasibility = 0; solution_params.num_dual_infeasibilities = -1; solution_params.sum_dual_infeasibilities = 0; solution_params.max_dual_infeasibility = 0; } void copySolutionObjectiveParams( const HighsSolutionParams& from_solution_params, HighsSolutionParams& to_solution_params) { to_solution_params.objective_function_value = from_solution_params.objective_function_value; } void copyFromSolutionParams(HighsInfo& highs_info, const HighsSolutionParams& solution_params) { highs_info.primal_status = solution_params.primal_status; highs_info.dual_status = solution_params.dual_status; highs_info.objective_function_value = solution_params.objective_function_value; highs_info.num_primal_infeasibilities = solution_params.num_primal_infeasibilities; highs_info.max_primal_infeasibility = solution_params.max_primal_infeasibility; highs_info.sum_primal_infeasibilities = solution_params.sum_primal_infeasibilities; highs_info.num_dual_infeasibilities = solution_params.num_dual_infeasibilities; highs_info.max_dual_infeasibility = solution_params.max_dual_infeasibility; highs_info.sum_dual_infeasibilities = solution_params.sum_dual_infeasibilities; } bool isBasisConsistent(const HighsLp& lp, const HighsBasis& basis) { bool consistent = true; consistent = isBasisRightSize(lp, basis) && consistent; int num_basic_variables = 0; for (int iCol = 0; iCol < lp.numCol_; iCol++) { if (basis.col_status[iCol] == HighsBasisStatus::BASIC) num_basic_variables++; } for (int iRow = 0; iRow < lp.numRow_; iRow++) { if (basis.row_status[iRow] == HighsBasisStatus::BASIC) num_basic_variables++; } bool right_num_basic_variables = num_basic_variables == lp.numRow_; consistent = right_num_basic_variables && consistent; return consistent; } bool isSolutionRightSize(const HighsLp& lp, const HighsSolution& solution) { bool right_size = true; right_size = (int)solution.col_value.size() == lp.numCol_ && right_size; right_size = (int)solution.col_dual.size() == lp.numCol_ && right_size; right_size = (int)solution.row_value.size() == lp.numRow_ && right_size; right_size = (int)solution.row_dual.size() == lp.numRow_ && right_size; return right_size; } bool isBasisRightSize(const HighsLp& lp, const HighsBasis& basis) { bool right_size = true; right_size = (int)basis.col_status.size() == lp.numCol_ && right_size; right_size = (int)basis.row_status.size() == lp.numRow_ && right_size; return right_size; } void clearSolutionUtil(HighsSolution& solution) { solution.col_dual.clear(); solution.col_value.clear(); solution.row_dual.clear(); solution.row_value.clear(); } void clearBasisUtil(HighsBasis& basis) { basis.row_status.clear(); basis.col_status.clear(); basis.valid_ = false; }
41.753374
80
0.69429
[ "vector" ]
4de0754e692e0adf6d1375e9a8b9bf440d2642e7
19,249
cxx
C++
STEER/STEER/AliSymMatrix.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
STEER/STEER/AliSymMatrix.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
STEER/STEER/AliSymMatrix.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/**********************************************************************************************/ /* Fast symmetric matrix with dynamically expandable size. */ /* Only part can be used for matrix operations. It is defined as: */ /* fNCols: rows built by constructor (GetSizeBooked) */ /* fNRows: number of rows added dynamically (automatically added on assignment to row) */ /* GetNRowAdded */ /* fNRowIndex: total size (fNCols+fNRows), GetSize */ /* fRowLwb : actual size to used for given operation, by default = total size, GetSizeUsed */ /* */ /* Author: ruben.shahoyan@cern.ch */ /* */ /**********************************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <iostream> #include <float.h> #include <string.h> // #include <TClass.h> #include <TMath.h> #include "AliSymMatrix.h" #include "AliLog.h" // ClassImp(AliSymMatrix) AliSymMatrix* AliSymMatrix::fgBuffer = 0; Int_t AliSymMatrix::fgCopyCnt = 0; //___________________________________________________________ AliSymMatrix::AliSymMatrix() : fElems(0),fElemsAdd(0) { // default constructor fSymmetric = kTRUE; fgCopyCnt++; } //___________________________________________________________ AliSymMatrix::AliSymMatrix(Int_t size) : AliMatrixSq(),fElems(0),fElemsAdd(0) { //constructor for matrix with defined size fNrows = 0; fNrowIndex = fNcols = fRowLwb = size; fElems = new Double_t[fNcols*(fNcols+1)/2]; fSymmetric = kTRUE; Reset(); fgCopyCnt++; // } //___________________________________________________________ AliSymMatrix::AliSymMatrix(const AliSymMatrix &src) : AliMatrixSq(src),fElems(0),fElemsAdd(0) { // copy constructor fNrowIndex = fNcols = src.GetSize(); fNrows = 0; fRowLwb = src.GetSizeUsed(); if (fNcols) { int nmainel = fNcols*(fNcols+1)/2; fElems = new Double_t[nmainel]; nmainel = src.fNcols*(src.fNcols+1)/2; memcpy(fElems,src.fElems,nmainel*sizeof(Double_t)); if (src.GetSizeAdded()) { // transfer extra rows to main matrix Double_t *pnt = fElems + nmainel; int ncl = src.GetSizeBooked() + 1; for (int ir=0;ir<src.GetSizeAdded();ir++) { memcpy(pnt,src.fElemsAdd[ir],ncl*sizeof(Double_t)); pnt += ncl; ncl++; } } } else fElems = 0; fElemsAdd = 0; fgCopyCnt++; // } //___________________________________________________________ AliSymMatrix::~AliSymMatrix() { Clear(); if (--fgCopyCnt < 1 && fgBuffer) {delete fgBuffer; fgBuffer = 0;} } //___________________________________________________________ AliSymMatrix& AliSymMatrix::operator=(const AliSymMatrix& src) { // assignment operator if (this != &src) { TObject::operator=(src); if (GetSizeBooked()!=src.GetSizeBooked() && GetSizeAdded()!=src.GetSizeAdded()) { // recreate the matrix if (fElems) delete[] fElems; for (int i=0;i<GetSizeAdded();i++) delete[] fElemsAdd[i]; delete[] fElemsAdd; // fNrowIndex = src.GetSize(); fNcols = src.GetSize(); fNrows = 0; fRowLwb = src.GetSizeUsed(); fElems = new Double_t[GetSize()*(GetSize()+1)/2]; int nmainel = src.GetSizeBooked()*(src.GetSizeBooked()+1); memcpy(fElems,src.fElems,nmainel*sizeof(Double_t)); if (src.GetSizeAdded()) { // transfer extra rows to main matrix Double_t *pnt = fElems + nmainel;//*sizeof(Double_t); int ncl = src.GetSizeBooked() + 1; for (int ir=0;ir<src.GetSizeAdded();ir++) { ncl += ir; memcpy(pnt,src.fElemsAdd[ir],ncl*sizeof(Double_t)); pnt += ncl;//*sizeof(Double_t); } } // } else { memcpy(fElems,src.fElems,GetSizeBooked()*(GetSizeBooked()+1)/2*sizeof(Double_t)); int ncl = GetSizeBooked() + 1; for (int ir=0;ir<GetSizeAdded();ir++) { // dynamic rows ncl += ir; memcpy(fElemsAdd[ir],src.fElemsAdd[ir],ncl*sizeof(Double_t)); } } } // return *this; } //___________________________________________________________ AliSymMatrix& AliSymMatrix::operator+=(const AliSymMatrix& src) { // add operator if (GetSizeUsed() != src.GetSizeUsed()) { AliError("Matrix sizes are different"); return *this; } for (int i=0;i<GetSizeUsed();i++) for (int j=i;j<GetSizeUsed();j++) (*this)(j,i) += src(j,i); return *this; } //___________________________________________________________ AliSymMatrix& AliSymMatrix::operator-=(const AliSymMatrix& src) { // minus operator if (GetSizeUsed() != src.GetSizeUsed()) { AliError("Matrix sizes are different"); return *this; } for (int i=0;i<GetSizeUsed();i++) for (int j=i;j<GetSizeUsed();j++) (*this)(j,i) -= src(j,i); return *this; } //___________________________________________________________ void AliSymMatrix::Clear(Option_t*) { // clear dynamic part if (fElems) {delete[] fElems; fElems = 0;} // if (fElemsAdd) { for (int i=0;i<GetSizeAdded();i++) delete[] fElemsAdd[i]; delete[] fElemsAdd; fElemsAdd = 0; } fNrowIndex = fNcols = fNrows = fRowLwb = 0; // } //___________________________________________________________ Float_t AliSymMatrix::GetDensity() const { // get fraction of non-zero elements Int_t nel = 0; for (int i=GetSizeUsed();i--;) for (int j=i+1;j--;) if (!IsZero(GetEl(i,j))) nel++; return 2.*nel/( (GetSizeUsed()+1)*GetSizeUsed() ); } //___________________________________________________________ void AliSymMatrix::Print(Option_t* option) const { // print itself printf("Symmetric Matrix: Size = %d (%d rows added dynamically), %d used\n",GetSize(),GetSizeAdded(),GetSizeUsed()); TString opt = option; opt.ToLower(); if (opt.IsNull()) return; opt = "%"; opt += 1+int(TMath::Log10(double(GetSize()))); opt+="d|"; for (Int_t i=0;i<GetSizeUsed();i++) { printf(opt,i); for (Int_t j=0;j<=i;j++) printf("%+.3e|",GetEl(i,j)); printf("\n"); } } //___________________________________________________________ void AliSymMatrix::MultiplyByVec(const Double_t *vecIn,Double_t *vecOut) const { // fill vecOut by matrix*vecIn // vector should be of the same size as the matrix for (int i=GetSizeUsed();i--;) { vecOut[i] = 0.0; for (int j=GetSizeUsed();j--;) vecOut[i] += vecIn[j]*GetEl(i,j); } // } //___________________________________________________________ Bool_t AliSymMatrix::Multiply(const AliSymMatrix& right) { // multiply from the right int sz = GetSizeUsed(); if (sz != right.GetSizeUsed()) { AliError("Matrix sizes are different"); return kFALSE; } if (!fgBuffer || fgBuffer->GetSizeUsed()!=sz) { delete fgBuffer; fgBuffer = new AliSymMatrix(*this); } else (*fgBuffer) = *this; // for (int i=sz;i--;) { for (int j=i+1;j--;) { double val = 0.; for (int k=sz;k--;) val += fgBuffer->GetEl(i,k)*right.GetEl(k,j); SetEl(i,j,val); } } // return kTRUE; } //___________________________________________________________ AliSymMatrix* AliSymMatrix::DecomposeChol() { // Return a matrix with Choleski decomposition // Adopted from Numerical Recipes in C, ch.2-9, http://www.nr.com // consturcts Cholesky decomposition of SYMMETRIC and // POSITIVELY-DEFINED matrix a (a=L*Lt) // Only upper triangle of the matrix has to be filled. // In opposite to function from the book, the matrix is modified: // lower triangle and diagonal are refilled. // if (!fgBuffer || fgBuffer->GetSizeUsed()!=GetSizeUsed()) { delete fgBuffer; fgBuffer = new AliSymMatrix(*this); } else (*fgBuffer) = *this; // AliSymMatrix& mchol = *fgBuffer; // for (int i=0;i<GetSizeUsed();i++) { Double_t *rowi = mchol.GetRow(i); for (int j=i;j<GetSizeUsed();j++) { Double_t *rowj = mchol.GetRow(j); double sum = rowj[i]; for (int k=i-1;k>=0;k--) if (rowi[k]&&rowj[k]) sum -= rowi[k]*rowj[k]; if (i == j) { if (sum <= 0.0) { // not positive-definite AliDebugF(2,"The matrix is not positive definite [%e]: Choleski decomposition is not possible",sum); //Print("l"); return 0; } rowi[i] = TMath::Sqrt(sum); // } else rowj[i] = sum/rowi[i]; } } return fgBuffer; } //___________________________________________________________ Bool_t AliSymMatrix::InvertChol() { // Invert matrix using Choleski decomposition // AliSymMatrix* mchol = DecomposeChol(); if (!mchol) { AliInfo("Failed to invert the matrix"); return kFALSE; } // InvertChol(mchol); return kTRUE; // } //___________________________________________________________ void AliSymMatrix::InvertChol(AliSymMatrix* pmchol) { // Invert matrix using Choleski decomposition, provided the Cholseki's L matrix // Double_t sum; AliSymMatrix& mchol = *pmchol; // // Invert decomposed triangular L matrix (Lower triangle is filled) for (int i=0;i<GetSizeUsed();i++) { mchol(i,i) = 1.0/mchol(i,i); for (int j=i+1;j<GetSizeUsed();j++) { Double_t *rowj = mchol.GetRow(j); sum = 0.0; for (int k=i;k<j;k++) if (rowj[k]) { double &mki = mchol(k,i); if (mki) sum -= rowj[k]*mki; } rowj[i] = sum/rowj[j]; } } // // take product of the inverted Choleski L matrix with its transposed for (int i=GetSizeUsed();i--;) { for (int j=i+1;j--;) { sum = 0; for (int k=i;k<GetSizeUsed();k++) { double &mik = mchol(i,k); if (mik) { double &mjk = mchol(j,k); if (mjk) sum += mik*mjk; } } (*this)(j,i) = sum; } } // } //___________________________________________________________ Bool_t AliSymMatrix::SolveChol(Double_t *b, Bool_t invert) { // Adopted from Numerical Recipes in C, ch.2-9, http://www.nr.com // Solves the set of n linear equations A x = b, // where a is a positive-definite symmetric matrix. // a[1..n][1..n] is the output of the routine CholDecomposw. // Only the lower triangle of a is accessed. b[1..n] is input as the // right-hand side vector. The solution vector is returned in b[1..n]. // Int_t i,k; Double_t sum; // AliSymMatrix *pmchol = DecomposeChol(); if (!pmchol) { AliDebug(2,"SolveChol failed"); // Print("l"); return kFALSE; } AliSymMatrix& mchol = *pmchol; // for (i=0;i<GetSizeUsed();i++) { Double_t *rowi = mchol.GetRow(i); for (sum=b[i],k=i-1;k>=0;k--) if (rowi[k]&&b[k]) sum -= rowi[k]*b[k]; b[i]=sum/rowi[i]; } // for (i=GetSizeUsed()-1;i>=0;i--) { for (sum=b[i],k=i+1;k<GetSizeUsed();k++) if (b[k]) { double &mki=mchol(k,i); if (mki) sum -= mki*b[k]; } b[i]=sum/mchol(i,i); } // if (invert) InvertChol(pmchol); return kTRUE; // } //___________________________________________________________ Bool_t AliSymMatrix::SolveCholN(Double_t *bn, int nRHS, Bool_t invert) { // Adopted from Numerical Recipes in C, ch.2-9, http://www.nr.com // Solves the set of n linear equations A x = b, // where a is a positive-definite symmetric matrix. // a[1..n][1..n] is the output of the routine CholDecomposw. // Only the lower triangle of a is accessed. b[1..n] is input as the // right-hand side vector. The solution vector is returned in b[1..n]. // // This version solve multiple RHSs at once int sz = GetSizeUsed(); Int_t i,k; Double_t sum; // AliSymMatrix *pmchol = DecomposeChol(); if (!pmchol) { AliDebug(2,"SolveChol failed"); // Print("l"); return kFALSE; } AliSymMatrix& mchol = *pmchol; // for (int ir=0;ir<nRHS;ir++) { double *b = bn+ir*sz; // for (i=0;i<sz;i++) { Double_t *rowi = mchol.GetRow(i); for (sum=b[i],k=i-1;k>=0;k--) if (rowi[k]&&b[k]) sum -= rowi[k]*b[k]; b[i]=sum/rowi[i]; } // for (i=sz-1;i>=0;i--) { for (sum=b[i],k=i+1;k<sz;k++) if (b[k]) { double &mki=mchol(k,i); if (mki) sum -= mki*b[k]; } b[i]=sum/mchol(i,i); } } // if (invert) InvertChol(pmchol); return kTRUE; // } //___________________________________________________________ Bool_t AliSymMatrix::SolveChol(TVectorD &b, Bool_t invert) { return SolveChol((Double_t*)b.GetMatrixArray(),invert); } //___________________________________________________________ Bool_t AliSymMatrix::SolveChol(Double_t *brhs, Double_t *bsol,Bool_t invert) { memcpy(bsol,brhs,GetSizeUsed()*sizeof(Double_t)); return SolveChol(bsol,invert); } //___________________________________________________________ Bool_t AliSymMatrix::SolveChol(const TVectorD &brhs, TVectorD &bsol,Bool_t invert) { bsol = brhs; return SolveChol(bsol,invert); } //___________________________________________________________ void AliSymMatrix::AddRows(int nrows) { // add empty rows if (nrows<1) return; Double_t **pnew = new Double_t*[nrows+fNrows]; for (int ir=0;ir<fNrows;ir++) pnew[ir] = fElemsAdd[ir]; // copy old extra rows for (int ir=0;ir<nrows;ir++) { int ncl = GetSize()+1; pnew[fNrows] = new Double_t[ncl]; memset(pnew[fNrows],0,ncl*sizeof(Double_t)); fNrows++; fNrowIndex++; fRowLwb++; } delete[] fElemsAdd; fElemsAdd = pnew; // } //___________________________________________________________ void AliSymMatrix::Reset() { // if additional rows exist, regularize it if (fElemsAdd) { delete[] fElems; for (int i=0;i<fNrows;i++) delete[] fElemsAdd[i]; delete[] fElemsAdd; fElemsAdd = 0; fNcols = fRowLwb = fNrowIndex; fElems = new Double_t[GetSize()*(GetSize()+1)/2]; fNrows = 0; } if (fElems) memset(fElems,0,GetSize()*(GetSize()+1)/2*sizeof(Double_t)); // } //___________________________________________________________ /* void AliSymMatrix::AddToRow(Int_t r, Double_t *valc,Int_t *indc,Int_t n) { // for (int i=n;i--;) { // (*this)(indc[i],r) += valc[i]; // } // return; double *row; if (r>=fNrowIndex) { AddRows(r-fNrowIndex+1); row = &((fElemsAdd[r-fNcols])[0]); } else row = &fElems[GetIndex(r,0)]; // int nadd = 0; for (int i=n;i--;) { if (indc[i]>r) continue; row[indc[i]] += valc[i]; nadd++; } if (nadd == n) return; // // add to col>row for (int i=n;i--;) { if (indc[i]>r) (*this)(indc[i],r) += valc[i]; } // } */ //___________________________________________________________ Double_t* AliSymMatrix::GetRow(Int_t r) { // get pointer on the row if (r>=GetSize()) { int nn = GetSize(); AddRows(r-GetSize()+1); AliDebug(2,Form("create %d of %d\n",r, nn)); return &((fElemsAdd[r-GetSizeBooked()])[0]); } else return &fElems[GetIndex(r,0)]; } //___________________________________________________________ int AliSymMatrix::SolveSpmInv(double *vecB, Bool_t stabilize) { // Solution a la MP1: gaussian eliminations /// Obtain solution of a system of linear equations with symmetric matrix /// and the inverse (using 'singular-value friendly' GAUSS pivot) // Int_t nRank = 0; int iPivot; double vPivot = 0.; double eps = 1e-14; int nGlo = GetSizeUsed(); bool *bUnUsed = new bool[nGlo]; double *rowMax,*colMax=0; rowMax = new double[nGlo]; // if (stabilize) { colMax = new double[nGlo]; for (Int_t i=nGlo; i--;) rowMax[i] = colMax[i] = 0.0; for (Int_t i=nGlo; i--;) for (Int_t j=i+1;j--;) { double vl = TMath::Abs(Query(i,j)); if (IsZero(vl)) continue; if (vl > rowMax[i]) rowMax[i] = vl; // Max elemt of row i if (vl > colMax[j]) colMax[j] = vl; // Max elemt of column j if (i==j) continue; if (vl > rowMax[j]) rowMax[j] = vl; // Max elemt of row j if (vl > colMax[i]) colMax[i] = vl; // Max elemt of column i } // for (Int_t i=nGlo; i--;) { if (!IsZero(rowMax[i])) rowMax[i] = 1./rowMax[i]; // Max elemt of row i if (!IsZero(colMax[i])) colMax[i] = 1./colMax[i]; // Max elemt of column i } // } // for (Int_t i=nGlo; i--;) bUnUsed[i] = true; // if (!fgBuffer || fgBuffer->GetSizeUsed()!=GetSizeUsed()) { delete fgBuffer; fgBuffer = new AliSymMatrix(*this); } else (*fgBuffer) = *this; // if (stabilize) for (int i=0;i<nGlo; i++) { // Small loop for matrix equilibration (gives a better conditioning) for (int j=0;j<=i; j++) { double vl = Query(i,j); if (!IsZero(vl)) SetEl(i,j, TMath::Sqrt(rowMax[i])*vl*TMath::Sqrt(colMax[j]) ); // Equilibrate the V matrix } for (int j=i+1;j<nGlo;j++) { double vl = Query(j,i); if (!IsZero(vl)) fgBuffer->SetEl(j,i,TMath::Sqrt(rowMax[i])*vl*TMath::Sqrt(colMax[j]) ); // Equilibrate the V matrix } } // for (Int_t j=nGlo; j--;) fgBuffer->DiagElem(j) = TMath::Abs(QueryDiag(j)); // save diagonal elem absolute values // for (Int_t i=0; i<nGlo; i++) { vPivot = 0.0; iPivot = -1; // for (Int_t j=0; j<nGlo; j++) { // First look for the pivot, ie max unused diagonal element double vl; if (bUnUsed[j] && (TMath::Abs(vl=QueryDiag(j))>TMath::Max(TMath::Abs(vPivot),eps*fgBuffer->QueryDiag(j)))) { vPivot = vl; iPivot = j; } } // if (iPivot >= 0) { // pivot found nRank++; bUnUsed[iPivot] = false; // This value is used vPivot = 1.0/vPivot; DiagElem(iPivot) = -vPivot; // Replace pivot by its inverse // for (Int_t j=0; j<nGlo; j++) { for (Int_t jj=0; jj<nGlo; jj++) { if (j != iPivot && jj != iPivot) {// Other elements (!!! do them first as you use old matV[k][j]'s !!!) double &r = j>=jj ? (*this)(j,jj) : (*fgBuffer)(jj,j); r -= vPivot* ( j>iPivot ? Query(j,iPivot) : fgBuffer->Query(iPivot,j) ) * ( iPivot>jj ? Query(iPivot,jj) : fgBuffer->Query(jj,iPivot)); } } } // for (Int_t j=0; j<nGlo; j++) if (j != iPivot) { // Pivot row or column elements (*this)(j,iPivot) *= vPivot; (*fgBuffer)(iPivot,j) *= vPivot; } // } else { // No more pivot value (clear those elements) for (Int_t j=0; j<nGlo; j++) { if (bUnUsed[j]) { vecB[j] = 0.0; for (Int_t k=0; k<nGlo; k++) { (*this)(j,k) = 0.; if (j!=k) (*fgBuffer)(j,k) = 0; } } } break; // No more pivots anyway, stop here } } // if (stabilize) for (Int_t i=0; i<nGlo; i++) for (Int_t j=0; j<nGlo; j++) { double vl = TMath::Sqrt(colMax[i])*TMath::Sqrt(rowMax[j]); // Correct matrix V if (i>=j) (*this)(i,j) *= vl; else (*fgBuffer)(j,i) *= vl; } // for (Int_t j=0; j<nGlo; j++) { rowMax[j] = 0.0; for (Int_t jj=0; jj<nGlo; jj++) { // Reverse matrix elements double vl; if (j>=jj) vl = (*this)(j,jj) = -Query(j,jj); else vl = (*fgBuffer)(j,jj) = -fgBuffer->Query(j,jj); rowMax[j] += vl*vecB[jj]; } } for (Int_t j=0; j<nGlo; j++) { vecB[j] = rowMax[j]; // The final result } // delete [] bUnUsed; delete [] rowMax; if (stabilize) delete [] colMax; return nRank; }
29.705247
118
0.600655
[ "vector" ]
4de0dab06763608f20078f455fe84876db0ff584
15,613
cpp
C++
object/plant.cpp
dnartz/PvZ-Emulator
3954f36f4e0f22cee07d6a86003d3892f0938b8b
[ "BSD-2-Clause" ]
1
2022-03-29T23:49:55.000Z
2022-03-29T23:49:55.000Z
object/plant.cpp
dnartz/PvZ-Emulator
3954f36f4e0f22cee07d6a86003d3892f0938b8b
[ "BSD-2-Clause" ]
2
2021-03-10T18:17:07.000Z
2021-05-11T13:59:22.000Z
object/plant.cpp
dnartz/PvZ-Emulator
3954f36f4e0f22cee07d6a86003d3892f0938b8b
[ "BSD-2-Clause" ]
1
2021-10-18T18:29:47.000Z
2021-10-18T18:29:47.000Z
#include <cstring> #include "scene.h" #include "plant.h" #include "system/plant/plant.h" namespace pvz_emulator::object { const std::array<unsigned int, 49> plant::EFFECT_INTERVAL_TABLE = { 150, 2500, 0, 0, 0, 150, 0, 150, 150, 2500, 150, 0, 0, 150, 0, 0, 0, 0, 150, 0, 0, 0, 0, 0, 150, 2500, 150, 0, 150, 150, 0, 0, 300, 0, 300, 0, 0, 0, 2500, 300, 150, 2500, 200, 150, 300, 0, 0, 600, 0 }; const std::array<bool, 49> plant::CAN_ATTACK_TABLE = { true, false, false, false, false, true, false, true, true, false, true, false, false, true, false, false, false, false, true, false, false, false, false, false, true, false, true, false, true, true, false, false, true, false, true, false, false, false, false, true, true, false, true, true, true, false, false, false, false }; const std::array<unsigned int, 48> plant::COST_TABLE = { 100, 50, 150, 50, 25, 175, 150, 200, 0, 25, 75, 75, 75, 25, 75, 125, 25, 50, 325, 25, 125, 100, 175, 125, 0, 25, 125, 100, 125, 125, 125, 100, 100, 25, 100, 75, 50, 100, 50, 300, 250, 150, 150, 225, 200, 50, 125, 500 }; const std::array<unsigned int, 48> plant::CD_TABLE = { 750, 750, 5000, 3000, 3000, 750, 750, 750, 750, 750, 750, 750, 3000, 750, 5000, 5000, 750, 3000, 750, 3000, 5000, 750, 750, 3000, 3000, 3000, 750, 750, 750, 750, 3000, 750, 750, 750, 750, 750, 750, 750, 3000, 750, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000 }; void plant::get_hit_box(rect& rect) { switch (type) { case plant_type::tallnut: rect.x = x + 10; rect.y = y; rect.width = attack_box.width; rect.height = attack_box.height; break; case plant_type::pumpkin: rect.x = x; rect.y = y; rect.width = attack_box.width - 20; rect.height = attack_box.height; break; case plant_type::cob_cannon: rect.x = x; rect.y = y; rect.width = 140; rect.height = 80; break; default: rect.x = x + 10; rect.y = y; rect.width = attack_box.width - 20; rect.height = attack_box.height; } } void plant::get_attack_box(rect& rect, bool is_alt_attack) { if (is_alt_attack && type == plant_type::split_pea) { rect.x = 0; rect.y = y; rect.width = x + 16; rect.height = attack_box.height; return; } switch (type) { case plant_type::squash: rect.x = x + 20; rect.y = y; rect.width = attack_box.width - 35; rect.height = attack_box.height; return; case plant_type::chomper: rect.x = x + 80; rect.y = y; rect.width = 40; rect.height = attack_box.height; return; case plant_type::spikeweed: case plant_type::spikerock: rect.x = x + 20; rect.y = y; rect.width = attack_box.width - 50; rect.height = attack_box.height; return; case plant_type::potato_mine: rect.x = x; rect.y = y; rect.width = attack_box.width - 25; rect.height = attack_box.height; return; case plant_type::torchwood: rect.x = x + 50; rect.y = y; rect.width = 30; rect.height = attack_box.height; return; case plant_type::puffshroom: case plant_type::seashroom: rect.x = x + 60; rect.y = y; rect.width = 230; rect.height = attack_box.height; return; case plant_type::fumeshroom: rect.x = x + 60; rect.y = y; rect.width = 340; rect.height = attack_box.height; return; case plant_type::gloomshroom: rect.x = x - 80; rect.y = y - 80; rect.width = 240; rect.height = 240; return; case plant_type::tangle_kelp: rect.x = x; rect.y = y; rect.width = attack_box.width; rect.height = attack_box.height; return; case plant_type::cattail: rect.x = -800; rect.y = -600; rect.width = 1600; rect.height = 1200; return; default: rect.x = x + 60; rect.y = y; rect.width = 800; rect.height = attack_box.height; break; } } unsigned int plant::get_attack_flags(bool is_alt_attack) { switch (type) { case plant_type::cactus: return is_alt_attack ? static_cast<unsigned int>(attack_flags::ground): static_cast<unsigned int>(attack_flags::flying_balloon); case plant_type::cob_cannon: case plant_type::cherry_bomb: case plant_type::jalapeno: case plant_type::doomshroom: return attack_flags::digging_digger | attack_flags::dying_zombies | attack_flags::animating_zombies | attack_flags::lurking_snorkel | attack_flags::flying_balloon | attack_flags::ground | 0x8; case plant_type::squash: case plant_type::cabbagepult: case plant_type::melonpult: case plant_type::kernelpult: case plant_type::winter_melon: return attack_flags::lurking_snorkel | attack_flags::ground | 0x8; case plant_type::potato_mine: return attack_flags::digging_digger | attack_flags::lurking_snorkel | attack_flags::ground | 0x8; case plant_type::puffshroom: case plant_type::scaredyshroom: case plant_type::fumeshroom: case plant_type::chomper: case plant_type::seashroom: return static_cast<unsigned int>(attack_flags::ground); case plant_type::cattail: return attack_flags::flying_balloon | attack_flags::ground; break; case plant_type::tangle_kelp: return attack_flags::lurking_snorkel | attack_flags::ground; default: return attack_flags::animating_zombies | attack_flags::ground; } } void plant::set_sleep(bool flag) { if (is_sleeping == flag || is_squash_attacking() || is_smashed || edible == plant_edible_status::invisible_and_not_edible || is_dead) { return; } is_sleeping = flag; if (is_sleeping) { if (has_reanim(plant_reanim_name::anim_sleep)) { set_reanim_frame(plant_reanim_name::anim_sleep); } else { reanim.fps = 1; } } else { if (has_reanim(plant_reanim_name::anim_idle)) { set_reanim_frame(plant_reanim_name::anim_idle); } } } void plant::set_reanim(plant_reanim_name name, reanim_type type, float fps) { if (fps != 0) { reanim.fps = fps; } reanim.type = type; reanim.n_repeated = 0; reanim.progress = static_cast<float>(reanim.fps >= 0 ? 0 : 0.99999988); reanim.prev_progress = -1; set_reanim_frame(name); } const char* plant::type_to_string(plant_type type) { switch (type) { case plant_type::none: return "none"; case plant_type::pea_shooter: return "pea_shooter"; case plant_type::sunflower: return "sunflower"; case plant_type::cherry_bomb: return "cherry_bomb"; case plant_type::wallnut: return "wallnut"; case plant_type::potato_mine: return "potato_mine"; case plant_type::snow_pea: return "snow_pea"; case plant_type::chomper: return "chomper"; case plant_type::repeater: return "repeater"; case plant_type::puffshroom: return "puffshroom"; case plant_type::sunshroom: return "sunshroom"; case plant_type::fumeshroom: return "fumeshroom"; case plant_type::grave_buster: return "grave_buster"; case plant_type::hypnoshroom: return "hypnoshroom"; case plant_type::scaredyshroom: return "scaredyshroom"; case plant_type::iceshroom: return "iceshroom"; case plant_type::doomshroom: return "doomshroom"; case plant_type::lily_pad: return "lily_pad"; case plant_type::squash: return "squash"; case plant_type::threepeater: return "threepeater"; case plant_type::tangle_kelp: return "tangle_kelp"; case plant_type::jalapeno: return "jalapeno"; case plant_type::spikeweed: return "spikeweed"; case plant_type::torchwood: return "torchwood"; case plant_type::tallnut: return "tallnut"; case plant_type::seashroom: return "seashroom"; case plant_type::plantern: return "plantern"; case plant_type::cactus: return "cactus"; case plant_type::blover: return "blover"; case plant_type::split_pea: return "split_pea"; case plant_type::starfruit: return "starfruit"; case plant_type::pumpkin: return "pumpkin"; case plant_type::magnetshroom: return "magnetshroom"; case plant_type::cabbagepult: return "cabbagepult"; case plant_type::flower_pot: return "flower_pot"; case plant_type::kernelpult: return "kernelpult"; case plant_type::coffee_bean: return "coffee_bean"; case plant_type::garlic: return "garlic"; case plant_type::umbrella_leaf: return "umbrella_leaf"; case plant_type::marigold: return "marigold"; case plant_type::melonpult: return "melonpult"; case plant_type::gatling_pea: return "gatling_pea"; case plant_type::twin_sunflower: return "twin_sunflower"; case plant_type::gloomshroom: return "gloomshroom"; case plant_type::cattail: return "cattail"; case plant_type::winter_melon: return "winter_melon"; case plant_type::gold_magnet: return "gold_magnet"; case plant_type::spikerock: return "spikerock"; case plant_type::cob_cannon: return "cob_cannon"; case plant_type::imitater: return "imitater"; default: return nullptr; } } void plant::to_json( scene& scene, rapidjson::Writer<rapidjson::StringBuffer>& writer) { writer.StartObject(); writer.Key("id"); writer.Uint64(scene.plants.get_index(*this)); writer.Key("type"); writer.String(type_to_string(type)); writer.Key("status"); writer.String(status_to_string(status)); writer.Key("x"); writer.Int(x); writer.Key("y"); writer.Int(y); writer.Key("cannon"); writer.StartObject(); writer.Key("x"); writer.Int(x); writer.Key("y"); writer.Int(y); writer.EndObject(); writer.Key("hp"); writer.Int(hp); writer.Key("max_hp"); writer.Int(max_hp); writer.Key("attack_box"); rect rect; get_attack_box(rect); rect.to_json(writer); writer.Key("hit_box"); get_hit_box(rect); rect.to_json(writer); writer.Key("row"); writer.Uint(row); writer.Key("col"); writer.Uint(col); writer.Key("max_boot_delay"); writer.Uint(max_boot_delay); writer.Key("direction"); writer.String(direction == plant_direction::left ? "left" : "right"); writer.Key("target"); if (target == -1) { writer.Null(); } else { writer.Uint64(target); } writer.Key("imitater_target"); writer.String(type_to_string(imitater_target)); writer.Key("countdown"); writer.StartObject(); writer.Key("status"); writer.Int(countdown.status); writer.Key("generate"); writer.Int(countdown.generate); writer.Key("launch"); writer.Int(countdown.launch); writer.Key("eaten"); writer.Int(countdown.eaten); writer.Key("awake"); writer.Int(countdown.awake); writer.Key("effect"); writer.Int(countdown.effect); writer.Key("dead"); writer.Int(countdown.dead); writer.Key("blover_disappear"); writer.Int(countdown.blover_disappear); writer.EndObject(); writer.Key("reanim"); reanim.to_json(writer); writer.Key("edible"); switch (edible) { case plant_edible_status::visible_and_edible: writer.String("visible_and_edible"); break; case plant_edible_status::invisible_and_edible: writer.String("invisible_and_edible"); break; case plant_edible_status::invisible_and_not_edible: writer.String("invisible_and_not_edible"); break; default: writer.Null(); } writer.Key("threepeater_time_since_first_shot"); writer.Uint(threepeater_time_since_first_shot); writer.Key("split_pea_attack_flags"); writer.StartObject(); writer.Key("front"); writer.Bool(split_pea_attack_flags.front); writer.Key("back"); writer.Bool(split_pea_attack_flags.back); writer.EndObject(); writer.Key("is_dead"); writer.Bool(is_dead); writer.Key("is_smashed"); writer.Bool(is_smashed); writer.Key("is_sleeping"); writer.Bool(is_sleeping); writer.Key("can_attack"); writer.Bool(can_attack); writer.EndObject(); } const char* plant::status_to_string(plant_status status) { switch (status) { case plant_status::idle: return "idle"; case plant_status::wait: return "wait"; case plant_status::work: return "work"; case plant_status::squash_look: return "squash_look"; case plant_status::squash_jump_up: return "squash_jump_up"; case plant_status::squash_stop_in_the_air: return "squash_stop_in_the_air"; case plant_status::squash_jump_down: return "squash_jump_down"; case plant_status::squash_crushed: return "squash_crushed"; case plant_status::grave_buster_land: return "grave_buster_land"; case plant_status::grave_buster_idle: return "grave_buster_idle"; case plant_status::chomper_bite_begin: return "chomper_bite_begin"; case plant_status::chomper_bite_success: return "chomper_bite_success"; case plant_status::chomper_bite_fail: return "chomper_bite_fail"; case plant_status::chomper_chew: return "chomper_chew"; case plant_status::chomper_swallow: return "chomper_swallow"; case plant_status::potato_sprout_out: return "potato_sprout_out"; case plant_status::potato_armed: return "potato_armed"; case plant_status::spike_attack: return "spike_attack"; case plant_status::scaredyshroom_scared: return "scaredyshroom_scared"; case plant_status::scaredyshroom_scared_idle: return "scaredyshroom_scared_idle"; case plant_status::scaredyshroom_grow: return "scaredyshroom_grow"; case plant_status::sunshroom_small: return "sunshroom_small"; case plant_status::sunshroom_grow: return "sunshroom_grow"; case plant_status::sunshroom_big: return "sunshroom_big"; case plant_status::magnetshroom_working: return "magnetshroom_working"; case plant_status::magnetshroom_inactive_idle: return "magnetshroom_inactive_idle"; case plant_status::cactus_short_idle: return "cactus_short_idle"; case plant_status::cactus_grow_tall: return "cactus_grow_tall"; case plant_status::cactus_tall_idle: return "cactus_tall_idle"; case plant_status::cactus_get_short: return "cactus_get_short"; case plant_status::tangle_kelp_grab: return "tangle_kelp_grab"; case plant_status::cob_cannon_unaramed_idle: return "cob_cannon_unaramed_idle"; case plant_status::cob_cannon_charge: return "cob_cannon_charge"; case plant_status::cob_cannon_launch: return "cob_cannon_launch"; case plant_status::cob_cannon_aramed_idle: return "cob_cannon_aramed_idle"; case plant_status::kernelpult_launch_butter: return "kernelpult_launch_butter"; case plant_status::umbrella_leaf_block: return "umbrella_leaf_block"; case plant_status::umbrella_leaf_shrink: return "umbrella_leaf_shrink"; case plant_status::imitater_explode: return "imitater_explode"; case plant_status::flower_pot_placed: return "flower_pot_placed"; case plant_status::lily_pad_placed: return "lily_pad_placed"; default: return nullptr; } } }
30.67387
77
0.654134
[ "object" ]
4de29b2667b07e85c5cdf5925a41e0f8de57eb3e
1,320
cpp
C++
Leetcode/Letter_Combinations_of_a_telephone_number.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
1
2019-03-24T12:35:43.000Z
2019-03-24T12:35:43.000Z
Leetcode/Letter_Combinations_of_a_telephone_number.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
null
null
null
Leetcode/Letter_Combinations_of_a_telephone_number.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
null
null
null
//Given a digit string, return all possible letter combinations that the number could represent. //A mapping of digit to letters (just like on the telephone buttons) is given below. class Solution { private: map<char,vector<char> >M; public: void help(vector<string>&result,char digit) { vector<string>temp; if(result.size()==0) { for(int j=0;j<M[digit].size();j++) { string tt; tt=tt+M[digit][j]; temp.push_back(tt); } result=temp; return; } for(int i=0;i<result.size();i++) { for(int j=0;j<M[digit].size();j++) temp.push_back(result[i]+M[digit][j]); } result=temp; } vector<string> letterCombinations(string digits) { vector<string> out; M['2']={'a','b','c'}; M['3']={'d','e','f'}; M['4']={'g','h','i'}; M['5']={'j','k','l'}; M['6']={'m','n','o'}; M['7']={'p','q','r','s'}; M['8']={'t','u','v'}; M['9']={'w','x','y','z'}; if(digits.length()==0) return out; for(int i=0;i<digits.length();i++) help(out,digits[i]); return out; } };
25.384615
96
0.429545
[ "vector" ]
4e2a34762f0e79d0810f044e7ebd638ace0d9077
8,967
cpp
C++
src/prod/src/Reliability/Replication/ComFromBytesOperation.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Reliability/Replication/ComFromBytesOperation.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Reliability/Replication/ComFromBytesOperation.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Reliability::ReplicationComponent; using namespace Common; ComFromBytesOperation::ComFromBytesOperation( std::vector<Common::const_buffer> const & buffers, std::vector<ULONG> const & segmentSizes, FABRIC_OPERATION_METADATA const & metadata, OperationAckCallback const & ackCallback, FABRIC_SEQUENCE_NUMBER lastOperationInBatch) : ComOperation(metadata, Constants::InvalidEpoch, lastOperationInBatch), data_(), segmentSizes_(segmentSizes), ackCallback_(ackCallback), callbackState_(CallbackState::NotCalled) { InitBuffer(buffers); InitData(); } ComFromBytesOperation::ComFromBytesOperation( std::vector<Common::const_buffer> const & buffers, std::vector<ULONG> const & segmentSizes, FABRIC_OPERATION_METADATA const & metadata, FABRIC_EPOCH const & epoch, OperationAckCallback const & ackCallback, FABRIC_SEQUENCE_NUMBER lastOperationInBatch) : ComOperation(metadata, epoch, lastOperationInBatch), data_(), segmentSizes_(segmentSizes), ackCallback_(ackCallback), callbackState_(CallbackState::NotCalled) { InitBuffer(buffers); InitData(); } ComFromBytesOperation::ComFromBytesOperation( std::vector<BYTE> && data, std::vector<ULONG> const & segmentSizes, FABRIC_OPERATION_METADATA const & metadata, FABRIC_EPOCH const & epoch, OperationAckCallback const & ackCallback, FABRIC_SEQUENCE_NUMBER lastOperationInBatch) : ComOperation(metadata, epoch, lastOperationInBatch), data_(std::move(data)), segmentSizes_(segmentSizes), ackCallback_(ackCallback), callbackState_(CallbackState::NotCalled) { InitData(); } ComFromBytesOperation::ComFromBytesOperation( FABRIC_OPERATION_METADATA const & metadata, OperationAckCallback const & ackCallback, FABRIC_SEQUENCE_NUMBER lastOperationInBatch, Common::ComponentRoot const & root) : ComOperation(metadata, Constants::InvalidEpoch, lastOperationInBatch), ackCallback_(ackCallback), callbackState_(CallbackState::NotCalled) { rootSPtr_ = root.CreateComponentRoot(); } ComFromBytesOperation::~ComFromBytesOperation() { } void ComFromBytesOperation::InitData() { size_t size = data_.size(); if (this->segmentSizes_.size() != 0) { size_t totalSegmentSize = 0; for (ULONG segmentSize : this->segmentSizes_) { totalSegmentSize += segmentSize; } ASSERT_IF(totalSegmentSize != size, "{0} does not match {1}", totalSegmentSize, size); ULONG segmentWalker = 0; for (ULONG segmentSize : this->segmentSizes_) { FABRIC_OPERATION_DATA_BUFFER replicaBuffer; // for 0 size buffer, point the Buffer to any valid non-NULL address with BufferSize=0 replicaBuffer.Buffer = (0 == size) ? (BYTE*)&data_ : (this->data_.data() + segmentWalker); replicaBuffer.BufferSize = segmentSize; segmentWalker += segmentSize; this->segments_.push_back(replicaBuffer); } } } void ComFromBytesOperation::InitBuffer( std::vector<Common::const_buffer> const & buffers) { size_t size = 0; for (auto buffer : buffers) { size += buffer.len; } data_.reserve(size); for (auto buffer : buffers) { data_.insert(data_.end(), buffer.buf, buffer.buf + buffer.len); } } bool ComFromBytesOperation::IsEmpty() const { return data_.empty(); } bool ComFromBytesOperation::get_NeedsAck() const { Common::AcquireExclusiveLock lock(this->lock_); bool ret = false; switch (this->callbackState_) { case CallbackState::NotCalled: ret = true; break; case CallbackState::ReadyToRun: // #4780473 - pending ops on secondary with EOS do not keep root alive. hence wait for the running callback to finish // Scenario without EOS is that LSN 1 could be completing, with 2 and 3 waiting on the queue lock in secondaryreplicator onackreplicationoperation // 2 and 3 are in running state, which makes OQ believe that they are ack'd and hence releases all objects to finish any pending async op and destruct // when 2 and 3's callbacks run, they AV ret = true; break; case CallbackState::Running: case CallbackState::Completed: case CallbackState::Cancelled: ret = false; break; default: Assert::CodingError("Unknown callbackstate {0}", static_cast<int>(callbackState_)); } return ret; } void ComFromBytesOperation::OnAckCallbackStartedRunning() { Common::AcquireExclusiveLock lock(this->lock_); ASSERT_IFNOT( this->callbackState_ == CallbackState::ReadyToRun, "Callback must be in ready to run state before running. It is {0}", static_cast<int>(callbackState_)); callbackState_ = CallbackState::Running; } void ComFromBytesOperation::SetIgnoreAckAndKeepParentAlive(Common::ComponentRoot const & root) { Common::AcquireExclusiveLock lock(this->lock_); if (this->IsEndOfStreamOperation) { // For an end of stream operation that could have been enqueued into the operation queue (happens during Copy only), // we cannot ignore the ACK. So we will keep the root alive, but not ignore the ACK if (this->callbackState_ == CallbackState::NotCalled || this->callbackState_ == CallbackState::Running || this->callbackState_ == CallbackState::ReadyToRun) { rootSPtr_ = root.CreateComponentRoot(); } } else { if (this->callbackState_ == CallbackState::NotCalled) { this->callbackState_ = CallbackState::Cancelled; } else if (this->callbackState_ == CallbackState::Running || this->callbackState_ == CallbackState::ReadyToRun) { // Ack was required and now is ignored; // increase the ref count on the parent, // so in case ACK comes it will still be alive rootSPtr_ = root.CreateComponentRoot(); } // else it must be completed, we don't care } } HRESULT ComFromBytesOperation::Acknowledge() { bool isCallbackRunning = false; { Common::AcquireExclusiveLock lock(this->lock_); TESTASSERT_IF(this->callbackState_ == CallbackState::Completed, "Callback is already completed"); TESTASSERT_IF(this->callbackState_ == CallbackState::Running, "Callback is already running"); ASSERT_IF(this->callbackState_ == CallbackState::Cancelled && this->IsEndOfStreamOperation, "End of stream operation should never have its callbackstate cancelled"); if (this->callbackState_ == CallbackState::Completed || this->callbackState_ == CallbackState::Running || this->callbackState_ == CallbackState::ReadyToRun) { return ComUtility::OnPublicApiReturn(FABRIC_E_INVALID_OPERATION); } if (this->callbackState_ == CallbackState::NotCalled) { this->callbackState_ = CallbackState::ReadyToRun; isCallbackRunning = true; } } if (ackCallback_ && isCallbackRunning) { ackCallback_(*this); } else { OperationQueueEventSource::Events->OperationAck( Metadata.SequenceNumber); } if (isCallbackRunning) { // If the callback finished running, set it to completed and reset the root in case the secondary had closed // and created the root while the callback was running Common::AcquireExclusiveLock lock(this->lock_); ASSERT_IF( (this->callbackState_ != CallbackState::Running) && ackCallback_, "Callback must be in running state before completed when there is a valid ack callback. It is {0}", static_cast<int>(callbackState_)); this->callbackState_ = CallbackState::Completed; rootSPtr_.reset(); } else { TESTASSERT_IFNOT( this->rootSPtr_ == nullptr, "If callback did not run, root must be nullptr"); } return ComUtility::OnPublicApiReturn(S_OK); } HRESULT ComFromBytesOperation::GetData( /*[out]*/ ULONG * count, /*[out, retval]*/ FABRIC_OPERATION_DATA_BUFFER const ** buffers) { if ((count == NULL) || (buffers == NULL)) { return ComUtility::OnPublicApiReturn(E_POINTER); } *count = static_cast<ULONG>(this->segments_.size()); *buffers = this->segments_.data(); return ComUtility::OnPublicApiReturn(S_OK); }
32.846154
173
0.657968
[ "vector" ]
4e383e9ac4c25bb40de177d8a30cb5117b37762c
1,116
cpp
C++
src/common/typing/utypes/bounded_t.cpp
m-zayan/numerical_linalg
328b8de874d1253ba02b6d579fcc62e45ceda4f6
[ "MIT" ]
null
null
null
src/common/typing/utypes/bounded_t.cpp
m-zayan/numerical_linalg
328b8de874d1253ba02b6d579fcc62e45ceda4f6
[ "MIT" ]
2
2021-01-31T12:24:14.000Z
2021-01-31T12:25:33.000Z
src/common/typing/utypes/bounded_t.cpp
m-zayan/numerical_linalg
328b8de874d1253ba02b6d579fcc62e45ceda4f6
[ "MIT" ]
null
null
null
/* * bounded_t.cpp * * Author: Z. Mohamed */ #include "bounded_t.hpp" template<typename T> bounded_t<T>::bounded_t(std::vector<T> bounds) : bounds(bounds), signature(""), value(bounds[0]) { } template<typename T> bounded_t<T>::bounded_t(std::vector<T> bounds, std::string signature, T value) : bounds(bounds), signature(signature) { this->validate_bounds(value); this->value = value; } template<typename T> void bounded_t<T>::validate_bounds(T val) { for (size_t i = 0; i < this->bounds.size(); i++) { if (val == this->bounds[i]) { return; } } throw std::logic_error( "Invalid assignment op: " + this->signature + ", Value Out of Range, [lower_bound, upper_bound]"); } template<typename T> bounded_t<T>& bounded_t<T>::operator=(T value) { this->validate_bounds(value); this->value = value; return (*this); } template<typename T> bounded_t<T>::operator T() const { return this->value; } template<typename T> bounded_t<T>::~bounded_t() { } template<typename T> std::ostream& operator <<(std::ostream &os, const bounded_t<T> &bndt) { os << bndt.value; return os; }
16.909091
80
0.660394
[ "vector" ]
4e39182495f6c0e64ef940ee639be069f9d85fcb
2,468
cpp
C++
leetCodeSolution/sudokuSolver/solution.cpp
slowy07/c-lesson
89f3b90c75301d59f64a6659eb8da8a3f8be1582
[ "MIT" ]
2
2020-06-02T17:32:09.000Z
2020-11-29T01:24:52.000Z
leetCodeSolution/sudokuSolver/solution.cpp
slowy07/c-lesson
89f3b90c75301d59f64a6659eb8da8a3f8be1582
[ "MIT" ]
null
null
null
leetCodeSolution/sudokuSolver/solution.cpp
slowy07/c-lesson
89f3b90c75301d59f64a6659eb8da8a3f8be1582
[ "MIT" ]
2
2020-09-23T14:40:28.000Z
2020-11-26T12:32:44.000Z
class Solution { struct cell { uint8_t value; bitset<10> constraints; cell() : value(0), numPossibilities(9),constraints() {}; }; array<array<cell,9>,9> cells; bool set(int i, int j, int v) { cell& c = cells[i][j]; if (c.value == v) return true; if (c.constraints[v]) return false; c.constraints = bitset<10>(0x3FE); c.constraints.reset(v); c.numPossibilities = 1; c.value = v; for (int k = 0; k<9; k++) { if (i != k && !updateConstraints(k, j, v)) return false; if (j != k && !updateConstraints(i, k, v)) return false; int ix = (i / 3) * 3 + k / 3; int jx = (j / 3) * 3 + k % 3; if (ix != i && jx != j && !updateConstraints(ix, jx, v)) return false; } return true; } bool updateConstraints(int i, int j, int excludedValue) { cell& c = cells[i][j]; if (c.constraints[excludedValue]) { return true; } if (c.value == excludedValue) { return false; } c.constraints.set(excludedValue); if (--c.numPossibilities > 1) return true; for (int v = 1; v <= 9; v++) { if (!c.constraints[v]) { return set(i, j, v); } } assert(false); } vector<pair<int, int>> bt; bool findValuesForEmptyCells() { bt.clear(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (!cells[i][j].value) bt.push_back(make_pair(i, j)); } } sort(bt.begin(), bt.end(), [this](const pair<int, int>&a, const pair<int, int>&b) { return cells[a.first][a.second].numPossibilities < cells[b.first][b.second].numPossibilities; }); return backtrack(0); } bool backtrack(int k) { if (k >= bt.size()) return true; int i = bt[k].first; int j = bt[k].second; if (cells[i][j].value) return backtrack(k + 1); auto constraints = cells[i][j].constraints; array<array<cell,9>,9> snapshot(cells); for (int v = 1; v <= 9; v++) { if (!constraints[v]) { if (set(i, j, v)) { if (backtrack(k + 1)) return true; } cells = snapshot; } } return false; } public: void solveSudoku(vector<vector<char>> &board) { cells = array<array<cell,9>,9>(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] != '.' && !set(i, j, board[i][j] - '0')) return; } } if (!findValuesForEmptyCells()) return; // sudoku is unsolvable for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (cells[i][j].value) board[i][j] = cells[i][j].value + '0'; } } } };
21.840708
100
0.545381
[ "vector" ]
4e39f2860bf59ae719ba245f268d6ff12564ea2b
880
cpp
C++
0101-0200/198-house-robber/main.cpp
janreggie/leetcode
c59718e127b598c4de7d07c9c93064eb12b2e5c9
[ "MIT", "Unlicense" ]
null
null
null
0101-0200/198-house-robber/main.cpp
janreggie/leetcode
c59718e127b598c4de7d07c9c93064eb12b2e5c9
[ "MIT", "Unlicense" ]
null
null
null
0101-0200/198-house-robber/main.cpp
janreggie/leetcode
c59718e127b598c4de7d07c9c93064eb12b2e5c9
[ "MIT", "Unlicense" ]
null
null
null
#include <vector> #include <iostream> class Solution { public: int rob(const std::vector<int>& nums) { const size_t length{nums.size()}; if (length == 1) { return nums.at(0); } if (length == 2) { return nums.at(0) > nums.at(1) ? nums.at(0) : nums.at(1); } // accumulated[ii] = accumulated[ii+2] + nums[ii] or // accumulated[ii+3] + nums[ii], // whichever is greater std::vector<int> accumulated(nums); accumulated[length-3] += nums.at(length-1); for (size_t ii{length-4}; ii < length; --ii) { accumulated[ii] += (accumulated[ii+2] > accumulated[ii+3] ? accumulated[ii+2] : accumulated[ii+3]); } return accumulated[0] > accumulated[1] ? accumulated[0] : accumulated[1]; } }; int main() { const std::vector<int> houses{5,6,131,4,6,696,7,420}; Solution soln; std::cout << soln.rob(houses) << std::endl; }
25.142857
75
0.601136
[ "vector" ]
4e42274cd739a2c541728d858d021eb659a04be2
206
cpp
C++
Competitive Coding/Reverse a String.cpp
mrjayantk237/Hacktober_Fest_2021
6dcd022a7116b81310534dcd0da8d66c185ac410
[ "MIT" ]
21
2021-10-02T14:14:33.000Z
2022-01-12T16:27:49.000Z
Competitive Coding/Reverse a String.cpp
mrjayantk237/Hacktober_Fest_2021
6dcd022a7116b81310534dcd0da8d66c185ac410
[ "MIT" ]
10
2021-10-02T15:52:56.000Z
2021-10-31T14:13:23.000Z
Competitive Coding/Reverse a String.cpp
mrjayantk237/Hacktober_Fest_2021
6dcd022a7116b81310534dcd0da8d66c185ac410
[ "MIT" ]
64
2021-10-02T09:20:19.000Z
2021-10-31T20:21:01.000Z
void reverseString(vector<char>& s) { int j=s.size()-1; char a; for(int i=0;i<=j;i++){ a= s[i]; s[i]= s[j]; s[j]=a; j--; } }
18.727273
37
0.315534
[ "vector" ]
4e490fea8f5c01235255caceb365887ad6584253
2,543
cpp
C++
examples/visitor/Visitor.cpp
copasi/copasi-api
3e09ad8b33f602981471104b553ebaf14e9ae4b1
[ "Artistic-2.0" ]
1
2021-04-08T12:39:39.000Z
2021-04-08T12:39:39.000Z
examples/visitor/Visitor.cpp
copasi/copasi-api
3e09ad8b33f602981471104b553ebaf14e9ae4b1
[ "Artistic-2.0" ]
1
2021-05-17T15:33:13.000Z
2021-08-30T21:26:04.000Z
examples/visitor/Visitor.cpp
copasi/copasi-api
3e09ad8b33f602981471104b553ebaf14e9ae4b1
[ "Artistic-2.0" ]
1
2021-08-13T09:47:49.000Z
2021-08-13T09:47:49.000Z
// BEGIN: Copyright // Copyright (C) 2021 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved // END: Copyright // BEGIN: License // Licensed under the Artistic License 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 // https://opensource.org/licenses/Artistic-2.0 // END: License #include "Visitor.h" #include <cpsapi/core/cpsapiRoot.h> #include <cpsapi/core/cpsapiFactory.h> CPSAPI_NAMESPACE_USE int main(int argc, char *argv[]) { cpsapi::init(); cpsapi::addDataModel(); cpsapi::model().setProperty(cpsapiModel::Property::OBJECT_NAME, "model"); cpsapi::addCompartment("compartment"); cpsapi::model().addSpecies("species"); Visitor V; cpsapi::model().accept(V); cpsapi::release(); return 0; } // virtual void Visitor::visit(cpsapiObject * pObject, const cpsapiObject::Type & type) { // Sanity check if (pObject == nullptr || !*pObject) return; switch (type) { case cpsapiObject::Type::Model: std::cout << "visit cpsapiModel: " << static_cast< cpsapiModel * >(pObject)->getObject()->getCN() << std::endl; break; case cpsapiObject::Type::Compartment: std::cout << "visit cpsapiCompartment: " << static_cast< cpsapiCompartment * >(pObject)->getObject()->getCN() << std::endl; break; case cpsapiObject::Type::Species: std::cout << "visit cpsapiSpecies: " << static_cast< cpsapiSpecies * >(pObject)->getObject()->getCN() << std::endl; break; case cpsapiObject::Type::Object: std::cout << "visit cpsapiObject: " << static_cast< cpsapiObject * >(pObject)->getObject()->getCN() << std::endl; break; case cpsapiObject::Type::Container: std::cout << "visit cpsapiContainer: " << static_cast< cpsapiContainer * >(pObject)->getObject()->getCN() << std::endl; break; case cpsapiObject::Type::Value: std::cout << "visit cpsapiValue: " << static_cast< cpsapiValue * >(pObject)->getObject()->getCN() << std::endl; break; case cpsapiObject::Type::Reaction: std::cout << "visit cpsapiReaction: " << static_cast< cpsapiReaction * >(pObject)->getObject()->getCN() << std::endl; break; default: std::cout << "visit unhandled (" << cpsapiObject::TypeName[type] << "): " << static_cast< cpsapiObject * >(pObject)->getObject()->getCN() << std::endl; break; } }
30.638554
157
0.652772
[ "object", "model" ]
4e49be69ae62fbfbdecc2c1e8e7c92bee8760321
114,749
cpp
C++
code/BObject.cpp
omerdagan84/neomem
7d2f782bb37f1ab0ac6580d00672e114605afab7
[ "MIT" ]
1
2022-02-10T01:41:32.000Z
2022-02-10T01:41:32.000Z
code/BObject.cpp
omerdagan84/neomem
7d2f782bb37f1ab0ac6580d00672e114605afab7
[ "MIT" ]
null
null
null
code/BObject.cpp
omerdagan84/neomem
7d2f782bb37f1ab0ac6580d00672e114605afab7
[ "MIT" ]
null
null
null
// BObject #include "precompiled.h" #include "BData.h" #include "BDataLink.h" #include "BDataLong.h" #include "BDataPersonName.h" #include "BDataString.h" #include "BObject.h" #include "ConstantsDatabase.h" #include "BDoc.h" //. get rid of these dependencies #include "NeoMem.h" #include "Constants.h" #include "DialogEditProperty.h" #include "Hint.h" #include "PageObjectGeneral.h" #include "PropertySheetEx2.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // last parameter is version number IMPLEMENT_SERIAL(BObject, CObject, VERSIONABLE_SCHEMA | versionFileStructure) // Construction/Destruction //-------------------------------------------------------------------------- BObject::BObject(BDoc& doc, OBJID idClass, LPCTSTR pszName, OBJID idParent, OBJID idIcon, ULONG lngFlags) : m_lngObjectID(0), id(m_lngObjectID) { ASSERT_VALID(&doc); Init(); // set doc m_pDoc = &doc; // default class if (idClass == 0) idClass = classPaper; BObject* pobjClassDef = doc.GetObject(idClass); // default name, eg "New Fish" CString strName; // don't move into brackets - needs to stay alive till end if (pszName == 0) { pobjClassDef->GetClassDefNewName(strName); pszName = (LPCTSTR) strName; } // default location - current object, with exceptions if (idParent == 0) { //, should be a classdef property. just do a switch here for now if (idClass == classClass) idParent = folderClasses; else idParent = doc.GetCurrentObject()->id; } // default flags // The default flags come from the classdef. if (lngFlags == 0) { //x BDataFlags* pdatFlags = DYNAMIC_DOWNCAST(BDataFlags, pobjClassDef->GetPropertyData(propObjectFlags)); // if (pdatFlags) { // lngFlags = pdatFlags->GetFlags(); // delete pdatFlags; // } lngFlags = pobjClassDef->GetPropertyFlags(propObjectFlags); } // set properties m_lngClassID = idClass; //, use lpctstr. //, make #define PSZ and PCSZ SetName(pszName); BObject* pobjParent = doc.GetObject(idParent); SetParent(pobjParent); //, api should take id not pobj SetFlags(lngFlags); SetIconID(idIcon); //, leave as direct ref for now (too confusing yet!) //, /* // Special properties for folder objects //, put in bfolder? but ui may say new bobject(class=folder)... hmm... // oh, but bfolder calls bobjcect // but here we don't get default class. shit. if (idClass == classFolder) { // Default class BObject* pobjDefaultClass = dlg.m_pobjDefaultClass; if (pobjDefaultClass != 0) { ASSERT_VALID(pobjDefaultClass); //, BClassDef& objClassDef = (BClassDef&) objNew; //? objNew.SetPropertyLink(propDefaultClass, pobjDefaultClass->id, FALSE, FALSE); // Initialize column array based on default class objNew.SetColumnsBasedOnClass(pobjDefaultClass); } } */ // Validate object // ASSERT_VALID(&obj); // Add object to database (and tell views) doc.AddObject(this); } // better to use member initialization lists - copy and paste, // because calling another routine and assigning values would be so much slower // ^ oh, i see - i didn't see this text and changed them to an Init routine, // because the init lists had gotten out of sync, and thought it was dangerous. // you would want it fast because this is BObject. BObject::BObject() : m_lngObjectID(0), id(m_lngObjectID) { Init(); } BObject::BObject(OBJID idClass) : m_lngObjectID(0), id(m_lngObjectID) { Init(); m_lngClassID = idClass; } void BObject::Init() { m_lngObjectID = 0; m_lngClassID = 0; m_lngFlags = 0; m_lngIconID = 0; m_paProperties = NULL; m_paChildren = NULL; m_pobjParent = NULL; m_pdat = NULL; m_pDoc = NULL; m_bytViewHeight = 50; // 50% default } // BObject factory // Only doc is required // static BObject& BObject::New(BDoc& doc, OBJID idClass, LPCTSTR pszName, OBJID idParent, OBJID idIcon, ULONG lngFlags) { BObject* pobj = new BObject(doc, idClass, pszName, idParent, idIcon, lngFlags); ASSERT(pobj); return *pobj; } BObject::~BObject() { // Clear the object, release all its children and properties recursively, and release // the collection objects themselves. // Release object data if (m_pdat) { ASSERT_VALID(m_pdat); delete m_pdat; // destructor for bdata objects will release any heap memory } // Release child objects recursively (destructor recursively deletes child objects) if (m_paChildren) { ASSERT_VALID(m_paChildren); delete m_paChildren; } // Release property objects recursively (descructor recursively deletes property objects) if (m_paProperties) { delete m_paProperties; } } /* // Copy constructor (will be good for right click Copy...) BObject::BObject( const BObject& a ) { mlngClassID = a.mlngClassID; mstrText = a.mstrText; } BObject& BObject::operator=( const BObject& a ) { m_years = a.m_years; return *this; } BOOL BObject::operator==(BObject a) { return m_years == a.m_years; } */ // Save to or load object from file. void BObject::Serialize(CArchive& ar) { CObject::Serialize(ar); // Always call base class Serialize. // m_myob.Serialize(ar); // Call Serialize on embedded member. // m_pOther->Serialize(ar); // Call Serialize on objects of known exact type. // use << for dynamic pointer for which the exact type is not known (eg m_pdat) if (ar.IsStoring()) { // Keep track of old versions here for reference // Save to file // Note: We don't serialize m_pobjParent because that is reconstructed in loading the file ar << m_lngObjectID; ar << m_lngClassID; ar << m_lngIconID; ar << m_lngFlags; ar << m_pdat; ar << m_paChildren; ar << m_paProperties; ar << m_bytViewHeight; //, remove in v2 // Update progress bar app.GetProgressBar().StepIt(); } else // Read object from file { // Store pointer to document in this bobject m_pDoc = DYNAMIC_DOWNCAST(BDoc, ar.m_pDocument); ASSERT_VALID(m_pDoc); // Get version of object as stored in file // (not actually necessary until the schema changes) // int nFileVersion = ar.GetObjectSchema(); // switch (nFileVersion) // { // case 1: // Read in current version of this object // Load from file ar >> m_lngObjectID; ar >> m_lngClassID; // if (m_pDoc->m_nObject==372 && m_lngClassID==500336) // TRACE("hi\n"); // TRACE("reading obj %d (id %d, classid %d):\n", m_pDoc->m_nObject, m_lngObjectID, m_lngClassID); ar >> m_lngIconID; ar >> m_lngFlags; ar >> m_pdat; ar >> m_paChildren; ar >> m_paProperties; ar >> m_bytViewHeight; //, remove in v2 // break; // case 2: // // read in future version of this object // break; // default: // // report unknown version of this object // break; // } // Make sure we're marked as owning the children and property objects if (m_paChildren) m_paChildren->SetOwnership(TRUE); if (m_paProperties) m_paProperties->SetOwnership(TRUE); //, Clear rtf position property? // could eventually define this prop to be non-serializable // if (m_lngClassID == propRtfInsertionPoint) // { // ASSERT(m_pdat->IsKindOf(RUNTIME_CLASS(BDataLong))); // BDataLong* pdatLong = (BDataLong*) m_pdat; // pdatLong->m_lngValue = 0; // } // Remove high priority flag if any (temp) // m_lngFlags &= ~flagHighPriority; /* // Convert from BDataArray/BDataColumnInfo to BDataColumns! // if the classid of this object is propColumnInfoArray or propObjectColumnInfoArray, do this. if (m_lngClassID == propColumnInfoArray || m_lngClassID == propObjectColumnInfoArray) { // m_pdat should be a bdataarray object containing bdatacolumninfo objects // verify this ASSERT(m_pdat->IsKindOf(RUNTIME_CLASS(BDataArray))); BDataArray* pdatArray = (BDataArray*) m_pdat; // walk through the array, getting the column info and adding it to a bdatacolumns object BDataColumns* pdatCols = new BDataColumns; ASSERT_VALID(pdatCols); int nCols = pdatArray->m_apdat.GetSize(); for (int i = 0; i < nCols; i++) { BDataColumnInfo* pc = DYNAMIC_DOWNCAST(BDataColumnInfo, pdatArray->m_apdat.GetAt(i)); ASSERT_VALID(pc); OBJID lngPropertyID = pc->idProperty; int nWidth = pc->m_nColWidth; // int nAlignment = pc->m_nColAlignment; pdatCols->InsertColumn(lngPropertyID, m_pDoc); pdatCols->SetColumnWidth(i, nWidth); } // now delete the old bdataarray and replace it with our new bdatacolumns object delete m_pdat; m_pdat = pdatCols; } */ /* // Convert from BDataArray/BDataArray/BDataView to BDataViews // If the classid of this object is propViewArrangement or propObjectViewArrangement, do this. if (m_lngClassID == propViewArrangement || m_lngClassID == propObjectViewArrangement) { // m_pdat should be a bdataarray object containing bdataarray objects // verify this ASSERT(m_pdat->IsKindOf(RUNTIME_CLASS(BDataArray))); BDataArray* pdatArray = (BDataArray*) m_pdat; int nIndex = 0; // walk through the array, getting the view arrays, and adding the views to a bdataviews object BDataViews* pdatViews = new BDataViews; ASSERT_VALID(pdatViews); pdatViews->m_avi.SetSize(10); // good enough for now // walk through tabs int nTabs = pdatArray->m_apdat.GetSize(); for (int nTab = 0; nTab < nTabs; nTab++) { // for each tab, get the view array BDataArray* pdatViewArray = DYNAMIC_DOWNCAST(BDataArray, pdatArray->m_apdat[nTab]); ASSERT_VALID(pdatViewArray); int nViews = pdatViewArray->m_apdat.GetSize(); // walk through view array, adding each view to our new array for (int nView = 0; nView < nViews; nView++) { BDataView* pv = DYNAMIC_DOWNCAST(BDataView, pdatViewArray->m_apdat[nView]); ASSERT_VALID(pv); // pdatViews->InsertView(nTab, nView, lngViewID, lngViewHeight); ViewInfo& rvi = pdatViews->m_avi[nIndex]; rvi.m_lngViewID = pv->m_lngViewID; rvi.m_lngViewHeight = pv->m_lngViewHeight; nIndex++; } // at the end of each tab, add a 0 0 viewinfo object ViewInfo& rvi = pdatViews->m_avi[nIndex]; rvi.m_lngViewID = 0; rvi.m_lngViewHeight = 0; nIndex++; } // Truncate array pdatViews->m_avi.SetSize(nIndex); // Now delete the old bdataarray and replace it with our new bdataviews object // note: this will delete all contained arrays and bdataview objects delete m_pdat; m_pdat = pdatViews; } */ /* // Convert from bdataname to bdatapersonname // If the classid of this object is person, do this. if (m_lngClassID == classPerson) { ASSERT(m_pdat->IsKindOf(RUNTIME_CLASS(BDataName))); BDataName* pdatOld = (BDataName*) m_pdat; BDataPersonName* pdatNew = new BDataPersonName; pdatNew->m_strFirst = pdatOld->m_strFirst; pdatNew->m_strMiddle = pdatOld->m_strMiddle; pdatNew->m_strLast = pdatOld->m_strLast; pdatNew->m_strSuffix = pdatOld->m_strSuffix; pdatNew->m_strNickname = pdatOld->m_strNickname; delete m_pdat; m_pdat = pdatNew; } */ /* // Convert from bdatalinks to bdatalink if (m_pdat->IsKindOf(RUNTIME_CLASS(BDataLinks))) { BDataLinks* pdatLinks = (BDataLinks*) m_pdat; BDataLink* pdatLink = new BDataLink; pdatLink->SetMultiple(); // walk through array int nItems = pdatLinks->m_apobj.GetSize(); for (int i = 0; i < nItems; i++) { BObject* pobj = (BObject*) pdatLinks->m_apobj.GetAt(i); ASSERT_VALID(pobj); pdatLink->AddLink(pobj); } delete pdatLinks; m_pdat = pdatLink; } */ // If this is an object (as opposed to a property), add it to the document's index if (m_lngObjectID) { // Add the object to the index // Note: If for some reason the ObjectID is already occupied, this routine will // try getting the next valid ID until it finds an empty space m_pDoc->AddObjectToIndex(this); // Also walk through the children and set their parent property to point to this object // BUG:: Old version of SetParent just set m_pobjParent, then I changed it for some other // part of the program, and this wound up creating a copy of each object on load. // Problem was semantics - should have created another routine called Move. // Er, this is BObjects.SetParent, not BObject. But ditch that routine, // since this is the only place it's used. if (m_paChildren) { // m_paChildren->SetParent(this); ASSERT_VALID(m_paChildren); int nItems = m_paChildren->GetSize(); for (int i = 0; i < nItems; i++) { BObject* pobj = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(i)); ASSERT_VALID(pobj); // Set the object's parent to the new parent pobj->m_pobjParent = this; } } } if (m_lngObjectID) //trace(" Read ObjectID %d: \"%s\"\n", m_lngObjectID, (LPCTSTR) GetPropertyString(propName)); // Update progress bar app.GetProgressBar().StepIt(); } } // Diagnostics //--------------------------------------------------------------------------------------------------- #ifdef _DEBUG void BObject::AssertValid() const { CObject::AssertValid(); // ASSERT(m_years > 0); } void BObject::Dump(CDumpContext& dc) const { CObject::Dump(dc); //dc << m_years; } #endif //_DEBUG // Methods //--------------------------------------------------------------------------------------------------- // Get the icon used to represent this object, looking up the class chain if necessary //, could store the looked up nIndex also for speed - just don't serialize it OBJID BObject::GetIconID() { ASSERT_VALID(this); // Return custom icon, if defined if (m_lngIconID) return m_lngIconID; // If the IconID is zero, then we get the IconID from the object's classdef and class chain return GetDefaultIconID(); } // Get the default icon for this object, looking up the class chain if necessary OBJID BObject::GetDefaultIconID() { ASSERT_VALID(this); // Special case: if object is an Icon, then display itself as the icon if (m_lngClassID == classIcon) return m_lngObjectID; // If we're not on a classdef, get the object's classdef BObject* pobjClassDef = 0; if (m_lngClassID != classClass) { // First look to the object's classdef pobjClassDef = m_pDoc->GetObject(m_lngClassID); if (pobjClassDef->m_lngIconID) // leave these as direct refs, not method calls. return pobjClassDef->m_lngIconID; // found icon, return it } else // We're already on a classdef, so just look up the class chain pobjClassDef = this; // If not there, then walk up through class chain till reach the root class do { pobjClassDef = pobjClassDef->GetParent(); if (pobjClassDef == NULL) return iconDefault; // just in case ASSERT_VALID(pobjClassDef); if (pobjClassDef->m_lngIconID) return pobjClassDef->m_lngIconID; // found icon finally, return it if (pobjClassDef->GetObjectID() == rootSystem) return iconDefault; // reached the end of the line and no icon defined, so return default } while (TRUE); } // Gets the index for the icon associated with this object // Will return the icon associated with the object's class if the // object has not specified a custom icon. int BObject::GetIconIndex() { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); OBJID lngIconID = GetIconID(); // Return the index of the IconID in the image list return m_pDoc->GetIconIndex(lngIconID); } // Set the bobject's text representation (name) // Different objects may use different properties to represent their text name // (eg person object parses this text into first middle last names, etc, stored in bdatapersonname object) void BObject::SetName(const CString& strText) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); // If no bdata object exists yet we'll need to create one appropriate for this class. if (m_pdat == NULL) { BData* pData = m_pDoc->CreateBData(m_lngClassID); SetData(pData); } ASSERT_VALID(m_pdat); // Pass the property def of the name property so the BData object will know how to handle parsing. BObject* pobjPropDef = m_pDoc->GetObject(m_lngClassID); m_pdat->SetBDataText(strText, pobjPropDef); } // Sets object's underlying data, i.e. transfer ownership of the BData object to this BObject. // So don't delete pdat after calling this routine! // Will dispose of any existing BData object attached to this BObject. BOOL BObject::SetData(BData* pdat) { ASSERT_VALID(this); ASSERT_VALID(pdat); // Delete any existing data object first. // But note: if user is passing the same data as already exists, we don't want to delete it! if (m_pdat != NULL && m_pdat != pdat) delete m_pdat; m_pdat = pdat; return TRUE; } // Add an object to the list of children for this BObject. // Child's parent should be NULL on entry. // Will create a child list if none exists. // Will optionally check the child list for the new child before adding it so no // duplicate entries are formed. // Returns True if successful, False if not. //, might want to insert alphabetically - pass param //, or could set a flag indicating that the list is unsorted BOOL BObject::AddChild(BObject *pobjChild, BOOL bCheckForDuplicates) { ASSERT_VALID(this); ASSERT_VALID(pobjChild); ASSERT(pobjChild->m_pobjParent == NULL); // Create new child list if not already there if (m_paChildren == NULL) { m_paChildren = new BObjects; m_paChildren->SetOwnership(TRUE); // this array will own the bobjects it points to } ASSERT_VALID(m_paChildren); // Make sure the child is not already in the array. // Optional because it's slow - currently only needed with synchronize routines. BOOL bAlreadyThere = FALSE; if (bCheckForDuplicates) { bAlreadyThere = (m_paChildren->FindObject(pobjChild, FALSE) != -1); } // Now add the new child object to the child array, if it's not already there. if (!bAlreadyThere) m_paChildren->Add(pobjChild); // may throw memory exception // Now set the parent of the child object pobjChild->m_pobjParent = this; // Make sure everything is set correctly ASSERT(pobjChild->m_pobjParent == this); ASSERT(this->m_paChildren->FindObject(pobjChild, FALSE) != -1); return TRUE; } // Remove the specified object from this object's children collection and set its parent to NULL. // Returns True if successful. BOOL BObject::RemoveChild(BObject* pobjChild) { ASSERT_VALID(this); ASSERT_VALID(pobjChild); ASSERT_VALID(pobjChild->m_pobjParent); ASSERT(pobjChild->m_pobjParent == this); if (m_paChildren) { ASSERT_VALID(m_paChildren); int nIndex = m_paChildren->FindObject(pobjChild); ASSERT(nIndex >= 0); if (nIndex >= 0) { m_paChildren->RemoveAt(nIndex); pobjChild->m_pobjParent = NULL; //, might want to delete the child collection if we're down to zero return TRUE; } } return FALSE; } // Routines //----------------------------------------------------------------------------------- // Add a property to the list of properties for this BObject. // Will create a property list if none exists. // Returns True if successful, False if not. // Note: This is only called by FindProperty. // Note: If you want to add a property to the class of an object, use something like // classFish.SetPropertyLinksAdd(propObjectProperties, propCategory.id); //, could pass parameters here so can specify position to add new property at BOOL BObject::AddProperty(BObject *pobjProperty) { ASSERT_VALID(this); ASSERT_VALID(pobjProperty); // Create new property list if not already there if (m_paProperties == NULL) { m_paProperties = new BObjects; m_paProperties->SetOwnership(TRUE); // this array will own the bobjects it points to } ASSERT_VALID(m_paProperties); // Now add the new property to the properties list //, depending on parameters, use AddTail, AddHead, InsertBefore, or InsertAfter // POSITION pos = m_paProperties->AddTail(pProperty); m_paProperties->Add(pobjProperty); // may throw memory exception return TRUE; } // Delete the specified property value from the collection of properties. // This will also set the document modified flag and update all views. // Also will ask user if bAskUser is True. // Note: This will not let pseudo properties be deleted (eg classname, classid, objectid, etc) // Returns True if successful. BOOL BObject::DeleteProperty(OBJID lngPropertyID, BOOL bSetModifiedFlag /* = TRUE */, BOOL bUpdateViews /* = TRUE */, BOOL bAskUser /* = FALSE */) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); //, fall out if a pseudoprop if (m_paProperties) { ASSERT_VALID(m_paProperties); int nIndex = m_paProperties->FindObjectClassID(lngPropertyID); if (nIndex != -1) { // Ask user if (bAskUser) { CString str; CString strValue = GetPropertyString(lngPropertyID); strValue.Remove('\n'); strValue.Remove('\r'); if (strValue.GetLength() > 40) strValue = strValue.Left(40) + _T("..."); str.Format("Are you sure you want to delete the property value '%s'?", (LPCTSTR) strValue); if (IDNO == AfxMessageBox(str, MB_ICONQUESTION + MB_YESNO)) { return FALSE; } } // Bug: Forgot to delete the bobject also! Caused memory leak BObject* pobjProp = DYNAMIC_DOWNCAST(BObject, m_paProperties->GetAt(nIndex)); ASSERT_VALID(pobjProp); // Remove the item from the array //, might want to override and delete the array if down to zero also m_paProperties->RemoveAt(nIndex); // Now nobody owns this bobject, so we can delete it delete pobjProp; // Set document modified flag if (bSetModifiedFlag) m_pDoc->SetModifiedFlag(); // Update views //, make different methods for the different types of hint - will keep me from messing up CHint objects if (bUpdateViews) { CHint h; h.pobjObject = this; h.idProperty = lngPropertyID; m_pDoc->UpdateAllViewsEx(NULL, hintPropertyChange, &h); } return TRUE; } } return FALSE; } //, need to clean all this code up at some point - print it all out, etc. // Find the specified property in this object's properties collection. // Returns a pointer to the property object, or NULL if not found. // If the property is an inheritable property, then will search through the classdef properties // and up the class chain. // If bAddIfNotFound is True, then will add the property to this object's property collection. // Also if the property is not already in this object's classdef's associated properties, then // it will add it there also. //, what about pseudo properties? BObject* BObject::FindProperty(OBJID lngPropertyID, BOOL bAddIfNotFound) { ASSERT_VALID(this); //, handle pseudo properties here? // Search through this object's properties collection first. if (m_paProperties) { ASSERT_VALID(m_paProperties); int nItems = m_paProperties->GetSize(); for (int i = 0; i < nItems; i++) { BObject* pobjPropertyValue = DYNAMIC_DOWNCAST(BObject, m_paProperties->GetAt(i)); ASSERT_VALID(pobjPropertyValue); if (pobjPropertyValue->GetClassID() == lngPropertyID) { // Found, return the property value bobject return pobjPropertyValue; } } } // Property was not found in this object, so look to its class or up the class chain. // Do this for certain special properties which inherit their values from the class chain. // eg propDefaultClass -> propObjectDefaultClass // These are hardcoded for now. // NOTE: There is a relationship between the ObjectID's for the object version and the // classdef version of the property - add 500 to get to the classdef version BOOL bSearchClassChain = FALSE; BOOL bGetClassDef = FALSE; if (!bAddIfNotFound) { switch (lngPropertyID) { case propDefaultClass: case propColumnInfoArray: case propViewArrangement: lngPropertyID += 500; // convert to classdef version of the property bSearchClassChain = TRUE; // search up the class chain bGetClassDef = TRUE; // get the object's classdef break; case propObjectDefaultClass: case propObjectColumnInfoArray: case propObjectViewArrangement: bSearchClassChain = TRUE; // search up the class chain break; } //, see which version produces better code... /* if ((lngPropertyID >= propDefaultClass) && (lngPropertyID <= propObjectViewArrangement)) { bSearchClassChain = TRUE; // Convert to classdef version of the property if (lngPropertyID < propObjectDefaultClass) lngPropertyID += 500; } */ // If we need to search up the class chain for an inherited value, do so now. if (bSearchClassChain) { if (bGetClassDef) { // Get the object's classdef initially BObject* pobjClass = m_pDoc->GetObject(m_lngClassID); if (pobjClass) return pobjClass->FindProperty(lngPropertyID, bAddIfNotFound); } else { // Get the classdef's parent recursively until you reach the end of the line BObject* pobjParent = this->GetParent(); if (pobjParent) { ASSERT_VALID(pobjParent); // Exit if you've reached the system root - property was never found if (pobjParent->GetObjectID() == rootSystem) return NULL; return pobjParent->FindProperty(lngPropertyID, bAddIfNotFound); } } } } // The property was not found, so add it to this object's property collection, // if parameter specifies this. if (bAddIfNotFound) { BObject* pobjPropertyValue = new BObject(lngPropertyID); ASSERT_VALID(pobjPropertyValue); pobjPropertyValue->SetDoc(m_pDoc); // set document pointer // Create a bdata object as appropriate for this property, if specified // (If you're calling FindProperty in order to Set a value, you don't need this) // don't need this as we now create a copy of the bdata found wherever it's from // if (bCreateBData) { // BData* pdat = m_pDoc->CreateBData(lngPropertyID); // ASSERT_VALID(pdat); // pobjPropertyValue->m_pdat = pdat; // store it in the property object we just created // } // Add property to this object's property collection. // Note: This will create a properties collection if none exists. AddProperty(pobjPropertyValue); // Also add the property to the object's classdef's associated properties if not already there. BObject* pobjClass = GetClassObject(); ASSERT_VALID(pobjClass); pobjClass->ClassDefAddProperty(lngPropertyID); return pobjPropertyValue; } return NULL; } COleDateTime& BObject::GetPropertyDate(OBJID lngPropertyID) { ASSERT_VALID(this); ASSERT(lngPropertyID); ASSERT_VALID(m_pDoc); BDataDate* pdat = DYNAMIC_DOWNCAST(BDataDate, GetPropertyData(lngPropertyID, TRUE)); //. check for string // or always return pdat? return pdat->GetDate(); /* // getpropdata BObject* pobjPropertyValue = FindProperty(lngPropertyID, FALSE); if (pobjPropertyValue) { ASSERT_VALID(pobjPropertyValue); BData* pdat = pobjPropertyValue->GetData()->CreateCopy(); ASSERT_VALID(pdat); return pdat; } // Property not found - create a temporary bdata object if requested. // Don't always want to create a temp bdata object, eg GetProperties calls this with propObjectProperties. // Same for icons - does GetPropertyData to test if has icon data or not - needs NULL. if (bCreateTempBDataIfNotFound) { // If no BData exists in the object or up the class chain, then create a temporary one // as appropriate for the property and save it BData* pdat = m_pDoc->CreateBData(lngPropertyID); ASSERT_VALID(pdat); return pdat; } // getpropstring // Find the specified property in the property collection, and return its text representation. // For some properties, we want to get a pointer to the class or base class's property object, // ie get the inherited (default) value. BObject* pobjPropertyValue = FindProperty(lngPropertyID, FALSE); if (pobjPropertyValue) { // Rather than calling this routine again, could duplicate the code here. // Also, that way we could pass lngpropid to the bdata gettext, which sometimes needs it. ASSERT_VALID(pobjPropertyValue); if (pobjPropertyValue->GetData() == NULL) { // No bdata object exists yet - we need to create one appropriate for this class pobjPropertyValue->m_pdat = m_pDoc->CreateBData(pobjPropertyValue->GetClassID()); } ASSERT_VALID(pobjPropertyValue->GetData()); return pobjPropertyValue->GetData()->GetBDataText(m_pDoc, lngPropertyID); } else // Property was not found - need to return zero-length string. // we're using lpctstr so this should be okay return ""; */ } BOOL BObject::SetPropertyDate(OBJID lngPropertyID, LPCTSTR pszText, BOOL bSetModifiedFlag, BOOL bUpdateViews) { ASSERT_VALID(this); ASSERT(lngPropertyID); ASSERT(pszText); //? or could pass zero to clear value? ASSERT_VALID(m_pDoc); // BDataDate* pdat = new BDataDate(pszText); // SetData(pdat); //, darn this was so nice..., even though all wrong // SetData(new BDataDate(pszText)); //, won't work because temp obj will be deleted, i think //. Get the property definition and property type so we know what to do. // eg some properties are relationships (two way) and // we need to know what the mirror property is so we can set that as well. // BObject* pobjPropertyType = pobjPropertyDef->GetPropertyLink(propPropertyType); // If new string is empty, just delete the property if (strlen(pszText) == 0) { // why wouldn't you mark doc as changed and alert ui? oh, because it's set below DeleteProperty(lngPropertyID, FALSE, FALSE); } else { //x BObject* pobjPropertyValue = FindProperty(lngPropertyID, TRUE); //x ASSERT_VALID(pobjPropertyValue); //x pobjPropertyValue->SetName(pszText); BDataDate* pdat = DYNAMIC_DOWNCAST(BDataDate, GetPropertyData(lngPropertyID, TRUE)); pdat->SetBDataText(pszText, NULL, FALSE); // setpropdate doesn't have a bshowerrormsg flag, so just set to false SetPropertyData(lngPropertyID, pdat, FALSE, FALSE); // flags set below // no need to delete pdat, as setpropdat takes ownership of it } // Set document modified flag if specified if (bSetModifiedFlag) m_pDoc->SetModifiedFlag(TRUE); // Update all views if specified if (bUpdateViews) { CHint h; h.pobjObject = this; h.idProperty = lngPropertyID; m_pDoc->UpdateAllViewsEx(NULL, hintPropertyChange, &h); } return TRUE; } // Set a property value, adding a property object if necessary. // Returns True if property value set successfully or False if not. // (Eg might be parsing something and format is invalid, so returns False). // Return False for read-only properties. BOOL BObject::SetPropertyString(OBJID lngPropertyID, LPCTSTR pszText, BOOL bSetModifiedFlag /* = TRUE */, BOOL bUpdateViews /* = TRUE */) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); ASSERT(pszText); // 2012-10 new // Check if property is read-only and give message. BObject* pobjPropertyDef = m_pDoc->GetObject(lngPropertyID); if (pobjPropertyDef->GetFlag(flagPropValueReadOnly)) { //,, move this out of db into ui AfxMessageBox("This property value is read-only and cannot be changed.", MB_ICONINFORMATION); return FALSE; } // Handle pseudo properties first switch (lngPropertyID) { case propName: // Set the name (text representation) of the object SetName(pszText); break; case propObjectID: { // Parse string into long integer OBJID lngNewObjectID = atol(pszText); //, we'll need some special handling to make sure we don't overwrite an existing objectid // eg say bValid = SetObjectID(pdat->m_lng); m_lngObjectID = lngNewObjectID; break; } case propSize: { // read-only property return FALSE; break; } case propClassName: { // Classname is a string pseudo property, want to handle with bdatalink object. // Create a temporary bdata object to handle the parsing (since that's what bdatalink settext does). //, for error checking, could say // bValid = SetClassID(pobjClass->GetObjectID()); // this code would make sure the id exists, that it's a class, and handle // converting any special properties to the new class (?) // Parse string into link to a class object using a temporary BDataLink object BDataLink* pdatLink = new BDataLink(); ASSERT_VALID(pdatLink); // The propertydef will tell the BDataLink object where to start searching for matches // BObject* pobjPropertyDef = m_pDoc->GetObject(propClassName); if (pdatLink->SetBDataText(pszText, pobjPropertyDef)) { // Bug: Was setting m_lngClassID instead of calling SetClassID! // m_lngClassID = pdatLink->GetLinkObjectID(); OBJID lngNewClassID = pdatLink->GetLinkObjectID(); SetClassID(lngNewClassID); delete pdatLink; } else { // Unable to parse text - return False delete pdatLink; return FALSE; } break; } case propFlags: { m_lngFlags = BDataFlags::StringToFlags(pszText); break; } default: { //. Get the property definition and property type so we know what to do. // eg some properties are relationships (two way) and // we need to know what the mirror property is so we can set that as well. // BObject* pobjPropertyType = pobjPropertyDef->GetPropertyLink(propPropertyType); // If new string is empty, just delete the property if (strlen(pszText) == 0) { DeleteProperty(lngPropertyID, FALSE, FALSE); } else { BObject* pobjPropertyValue = FindProperty(lngPropertyID, TRUE); ASSERT_VALID(pobjPropertyValue); pobjPropertyValue->SetName(pszText); } break; } } // Set document modified flag if specified if (bSetModifiedFlag) m_pDoc->SetModifiedFlag(TRUE); // Update all views if specified if (bUpdateViews) { CHint h; h.pobjObject = this; h.idProperty = lngPropertyID; m_pDoc->UpdateAllViewsEx(NULL, hintPropertyChange, &h); } return TRUE; } /* BOOL BObject::SetDescription(LPCTSTR pszText) { return this->SetPropertyString(propDescription, pszText); } */ // Get text property value. // pass true for bMachineValue to get machine-readable version of data. used by export. // Warning: Since this uses m_strTextCache, you can't string a bunch of these calls // on one line, eg in a CString Format call //xLPCTSTR BObject::GetPropertyString(OBJID lngPropertyID, BOOL bCreateTempBDataIfNotFound) CString BObject::GetPropertyString(OBJID lngPropertyID) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); // Handle pseudo properties first switch (lngPropertyID) { case propName: { // Return the text representation of the object (the name) if (m_pdat == NULL) { // No bdata object exists yet - we need to create one appropriate for this class m_pdat = m_pDoc->CreateBData(m_lngClassID); } ASSERT_VALID(m_pdat); return m_pdat->GetBDataText(m_pDoc, lngPropertyID); /* // could handle read-only summary here... LPCTSTR psz = m_pdat->GetBDataText(m_pDoc, lngPropertyID); if (*psz == 0) return "hi!"; else return psz; */ } break; case propSize: { ULONG lngSize = GetMemoryUsed(FALSE); m_strTextCache.FormatBytes(lngSize); return m_strTextCache; } break; case propClassID: { ASSERT (m_lngClassID); m_strTextCache.Format("%d", m_lngClassID); return m_strTextCache; } break; case propClassName: { // Return the name of the object's class // if (m_lngClassID) // { ASSERT (m_lngClassID); BObject* pobjClassDef = m_pDoc->GetObject(m_lngClassID); return pobjClassDef->GetPropertyString(propName); // } // else // return "ClassID is 0"; } break; case propParentID: { BObject* pobjParent = GetParent(); if (pobjParent) { ASSERT_VALID(pobjParent); m_strTextCache.Format("%d", pobjParent->GetObjectID()); } else { m_strTextCache = CString("0"); } return m_strTextCache; } break; case propParentName: { BObject* pobjParent = GetParent(); // Return the name of the object's parent (location) if (pobjParent) { ASSERT_VALID(pobjParent); return pobjParent->GetPropertyString(propName); } else // Return reference to an empty string (can't return "" because would // return a reference to a temporary object) // we're using lpctstr so this should be okay return ""; } break; case propObjectID: // how do we handle this? // ie for this object, say it's the Icons folder, // we're displaying its properties // this method wants to return a reference to a cstring // but what cstring? this is a pseudo property // and you can't return a reference to a local cstring because it will get deleted // well for now, let's use the text cache (same as used by name though) { m_strTextCache.Format("%d", m_lngObjectID); return m_strTextCache; } break; case propPlainText: { // get plain text version of rtf text contents CString strRtf = GetPropertyString(propRtfText); app.ConvertRtfToPlain(strRtf, m_strTextCache); return m_strTextCache; } break; case propFlags: { return BDataFlags::FlagsToString(m_lngFlags); } break; default: { // Find the specified property in the property collection, and return its text representation. // For some properties, we want to get a pointer to the class or base class's property object, // ie get the inherited (default) value. BObject* pobjPropertyValue = FindProperty(lngPropertyID, FALSE); if (pobjPropertyValue) { // Rather than calling this routine again, could duplicate the code here. // Also, that way we could pass lngpropid to the bdata gettext, which sometimes needs it. ASSERT_VALID(pobjPropertyValue); if (pobjPropertyValue->GetData() == NULL) { // No bdata object exists yet - we need to create one appropriate for this class BData* pdatNew = m_pDoc->CreateBData(pobjPropertyValue->GetClassID()); pobjPropertyValue->SetData(pdatNew); } ASSERT_VALID(pobjPropertyValue->GetData()); return pobjPropertyValue->GetData()->GetBDataText(m_pDoc, lngPropertyID); } else // Property was not found - need to return zero-length string. // we're using lpctstr so this should be okay return ""; } break; } } //xULONG BObject::GetPropertyFlags(OBJID idProperty, BOOL bCreateTempBDataIfNotFound) ULONG BObject::GetPropertyFlags(OBJID idProperty) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); // Handle pseudo properties first switch (idProperty) { case propFlags: { // return BDataFlags::FlagsToString(m_lngFlags); return m_lngFlags; } break; default: { // Find the specified property in the property collection, and return its flag value. // For some properties, we want to get a pointer to the class or base class's property object, // ie get the inherited (default) value. BObject* pobjPropertyValue = FindProperty(idProperty, FALSE); if (pobjPropertyValue) { // Rather than calling this routine again, could duplicate the code here. // Also, that way we could pass lngpropid to the bdata gettext, which sometimes needs it. ASSERT_VALID(pobjPropertyValue); if (pobjPropertyValue->GetData() == NULL) { // No bdata object exists yet - we need to create one appropriate for this class pobjPropertyValue->m_pdat = m_pDoc->CreateBData(pobjPropertyValue->GetClassID()); } BDataFlags* pdat = DYNAMIC_DOWNCAST(BDataFlags, pobjPropertyValue->GetData()); ASSERT_VALID(pdat); ULONG lngFlags = pdat->GetFlags(); return lngFlags; } else // Property was not found return 0; } break; } } //x /* BDataColumns* BObject::GetPropertyColumns(OBJID idProperty) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); // Find the specified property in the property collection, and return its value. // For some properties, we want to get a pointer to the class or base class's property object, // ie get the inherited (default) value. BObject* pobjPropertyValue = FindProperty(idProperty, FALSE); if (pobjPropertyValue) { // Rather than calling this routine again, could duplicate the code here. // Also, that way we could pass lngpropid to the bdata gettext, which sometimes needs it. ASSERT_VALID(pobjPropertyValue); if (pobjPropertyValue->GetData() == NULL) { // No bdata object exists yet - we need to create one appropriate for this class pobjPropertyValue->m_pdat = m_pDoc->CreateBData(pobjPropertyValue->GetClassID()); } //, sheesh. anyway to clear this up? BDataColumns* pdat = DYNAMIC_DOWNCAST(BDataColumns, pobjPropertyValue->GetData()); ASSERT_VALID(pdat); BData* pcopy = pdat->CreateCopy(); ASSERT_VALID(pcopy); BDataColumns* pcopy2 = DYNAMIC_DOWNCAST(BDataColumns, pcopy); ASSERT_VALID(pcopy2); return pcopy2; } else // Property was not found return NULL; } */ // Set the underlying data for a property. // Makes a COPY of the BData object and saves it. // Each property BObject stores its data in the m_pdat member, which is a pointer to a BData object. BOOL BObject::SetPropertyData(OBJID lngPropertyID, BData *pdatOrig, BOOL bSetModifiedFlag /* = TRUE */, BOOL bUpdateViews /* = TRUE */) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); ASSERT_VALID(pdatOrig); // Make copy of the BData object BData* pdat = pdatOrig->CreateCopy(); // Handle pseudo properties first switch (lngPropertyID) { case propName: { // Save bdata to bobject. // This will work for both normal names (ie stored in bdatastring object) and people names // (stored in bdatapersonname object). if (m_pdat) delete m_pdat; m_pdat = pdat; break; } case propClassName: { // Note: pdat is a pointer to a temporary bdata object. BDataLink* pdatLink = DYNAMIC_DOWNCAST(BDataLink, pdat); ASSERT_VALID(pdatLink); // Bug: Was setting m_lngClassID directly instead of calling SetClassID, so name type wasn't being changed // m_lngClassID = pdatLink->GetLinkObjectID(); OBJID lngNewClassID = pdatLink->GetLinkObjectID(); SetClassID(lngNewClassID); //, memory leak? test // delete pdat; break; } default: { // For most properties, we just set the pointer to the new BData object. // If property doesn't already exist, it will be created. BObject* pobjPropertyValue = FindProperty(lngPropertyID, TRUE); ASSERT_VALID(pobjPropertyValue); pobjPropertyValue->SetData(pdat); break; } } // Set document modified flag if specified if (bSetModifiedFlag) m_pDoc->SetModifiedFlag(TRUE); // Update all views if specified if (bUpdateViews) { CHint h; h.pobjObject = this; h.idProperty = lngPropertyID; m_pDoc->UpdateAllViewsEx(NULL, hintPropertyChange, &h); } return TRUE; } // Get a COPY of the underlying data object associated with a property. // Be sure to delete the bdata object when done with it. // To modify a value, write it back to the object with SetPropertyData. BData* BObject::GetPropertyData(OBJID lngPropertyID, BOOL bCreateTempBDataIfNotFound) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); //.. bad - this same code is in GetPropertyString - put in FindProperty? // BObject* pobjPropertyValue = FindProperty(lngPropertyID, FALSE); // Handle pseudo properties first switch (lngPropertyID) { case propName: { // Return the text representation of the object (the name) // Create a new one if necessary // Note: Object name BData's are always stored in the BObject's m_pdat pointer. if (m_pdat == 0) { // No bdata object exists yet - we need to create one appropriate for this class // (eg BDataString or BDataPersonName) m_pdat = m_pDoc->CreateBData(m_lngClassID); } ASSERT_VALID(m_pdat); // create copy BData* pdat = m_pdat->CreateCopy(); ASSERT_VALID(pdat); return pdat; break; } case propClassName: { //. how could you return a bdata object for classname? // it would be a bdatalink // create a temporary bdata object of type bdatalink (as determined by propClassName's property type of proptypeLink) // the value of the link is the object's classdef // so would need to initialize the bdatalink object to point to the m_lngClassID object // user selects a different class // uieditvalue would change the bdatalink's m_pobj pointer to point to the new class object // and would broadcast the hintPropertyChange to all views // but how would that change get written back to the actual m_lngClassID variable? // the UIEditValue could handle that - ie check to see if the propertydef is a pseudo property // if so, do any special handling required // now what about F2 handler? // ie user is on classname pseudo property // and hits F2 // types in a new class name, say "Tape" // hits enter // ui code calls SetPropertyString(propClassName, "Tape") // SetPropertyString code will pass the string to the appropriate bdata object for parsing // Create a temporary BData object appropriate for the propertydef (based on its property type) BData* pdat = m_pDoc->CreateBData(lngPropertyID); ASSERT_VALID(pdat); BDataLink* pdatLink = DYNAMIC_DOWNCAST(BDataLink, pdat); ASSERT_VALID(pdatLink); // Set link to point to this object's classdef BObject* pobjClass = m_pDoc->GetObject(m_lngClassID); pdatLink->SetLink(pobjClass); // Return a pointer to the temporary bdata object ASSERT_VALID(pdatLink); return pdatLink; break; } case propParentName: { // but how would that change get written back to the actual m_lngParentID variable? // the UIEditValue could handle that - ie check to see if the propertydef is a pseudo property // if so, do any special handling required // Create a temporary BData object appropriate for the propertydef (based on its property type) BData* pdat = m_pDoc->CreateBData(lngPropertyID); ASSERT_VALID(pdat); BDataLink* pdatLink = DYNAMIC_DOWNCAST(BDataLink, pdat); ASSERT_VALID(pdatLink); // Set link to point to this object's parent (may be zero if it's the root object) BObject* pobjParent = GetParent(); if (pobjParent) ASSERT_VALID(pobjParent); pdatLink->SetLink(pobjParent); // zero is okay here // Return a pointer to the temporary bdata object ASSERT_VALID(pdatLink); return pdatLink; break; } case propObjectID: { // Create a temporary BData object appropriate for the propertydef (based on its property type) BData* pdat = m_pDoc->CreateBData(lngPropertyID); ASSERT_VALID(pdat); BDataLong* pdatLong = DYNAMIC_DOWNCAST(BDataLong, pdat); ASSERT_VALID(pdatLong); pdatLong->SetValue(m_lngObjectID); // Return a pointer to the temporary bdata object ASSERT_VALID(pdatLong); return pdatLong; break; } case propPlainText: { // Create a temporary BData object BDataString* pdat = new BDataString; ASSERT_VALID(pdat); // get plain text version of rtf text contents, and store it in the bdata CString strRtf = GetPropertyString(propRtfText); app.ConvertRtfToPlain(strRtf, m_strTextCache); pdat->SetBDataText(m_strTextCache, 0, FALSE); // app.ConvertRtfToPlain(pszRtf, pdat->m_strText); // protected member // Return a pointer to the temporary bdata object ASSERT_VALID(pdat); return pdat; break; } default: { BObject* pobjPropertyValue = FindProperty(lngPropertyID, FALSE); if (pobjPropertyValue) { ASSERT_VALID(pobjPropertyValue); // this code was in getpropstring, and seemed good to have here also, //, though bobject should ensure mpdoc is not null if (pobjPropertyValue->GetData() == NULL) { // No bdata object exists yet - we need to create one appropriate for this class BData* pdatNew = m_pDoc->CreateBData(pobjPropertyValue->GetClassID()); pobjPropertyValue->SetData(pdatNew); } ASSERT_VALID(pobjPropertyValue->GetData()); BData* pdat = pobjPropertyValue->GetData()->CreateCopy(); ASSERT_VALID(pdat); return pdat; } } } // how can this be ever reached if the default case returns from this fn? // oh, there's an if... // Property not found - create a temporary bdata object if requested. // Don't always want to create a temp bdata object, eg GetProperties calls this with propObjectProperties. // Same for icons - does GetPropertyData to test if has icon data or not - needs NULL. if (bCreateTempBDataIfNotFound) { // If no BData exists in the object or up the class chain, then create a temporary one // as appropriate for the property and save it BData* pdat = m_pDoc->CreateBData(lngPropertyID); ASSERT_VALID(pdat); return pdat; } return NULL; } // Set long property value. BOOL BObject::SetPropertyLong(OBJID lngPropertyID, ULONG lngValue, BOOL bSetModifiedFlag /* = TRUE */, BOOL bUpdateViews /* = TRUE */) { ASSERT_VALID(this); //. handle pseudo properties here // Find/create property BObject* pobjPropertyValue = FindProperty(lngPropertyID, TRUE); ASSERT_VALID(pobjPropertyValue); // Create new data object to hold data and initialize it //, more efficient to use existing bdata object // if (pobjPropertyValue->m_pdat == NULL) // { // pobjPropertyValue->m_pdat = new BDataLong; // } BDataLong* pdat = new BDataLong; ASSERT_VALID(pdat); pdat->SetValue(lngValue); // Store the data in the property object pobjPropertyValue->SetData(pdat); // Set document modified flag if specified if (bSetModifiedFlag) m_pDoc->SetModifiedFlag(TRUE); // Update all views if specified if (bUpdateViews) { CHint h; h.pobjObject = this; h.idProperty = lngPropertyID; m_pDoc->UpdateAllViewsEx(NULL, hintPropertyChange, &h); } return TRUE; } // GetPropertyLong //, how do we return NULL? need a variant type? //xULONG BObject::GetPropertyLong(OBJID lngPropertyID, BOOL bCreateTempBDataIfNotFound) ULONG BObject::GetPropertyLong(OBJID lngPropertyID) { ASSERT_VALID(this); ASSERT(lngPropertyID); //x ASSERT(bCreateTempBDataIfNotFound == FALSE); // for now // Handle pseudo properties first switch (lngPropertyID) { case propObjectID: return m_lngObjectID; case propSize: return GetMemoryUsed(FALSE); } BObject* pobjPropertyValue = FindProperty(lngPropertyID, FALSE); if (pobjPropertyValue) { ASSERT_VALID(pobjPropertyValue); BDataLong* pdat = DYNAMIC_DOWNCAST(BDataLong, pobjPropertyValue->GetData()); ASSERT_VALID(pdat); return pdat->GetValue(); } /* else // Set default values here, since no property value was found { switch (lngPropertyID) { // By default, any link property should allow multiple links. case propAllowedNumberOfLinks: return -1; } } */ return 0; } // Set object that the specified property links to. // Note: If idObj is zero, will delete the property bobject. BOOL BObject::SetPropertyLink(OBJID idProperty, OBJID idObj, BOOL bSetModifiedFlag, BOOL bUpdateViews) { ASSERT_VALID(this); ASSERT(idProperty); if (idObj) { // Find/create property value bobject BObject* pobjPropertyValue = FindProperty(idProperty, TRUE); ASSERT_VALID(pobjPropertyValue); // Create new data object to hold data and initialize it //, more efficient to use existing bdata object // if (pobjPropertyValue->m_pdat == NULL) { // pobjPropertyValue->m_pdat = new BDataLong; // } BDataLink* pdat = new BDataLink; ASSERT_VALID(pdat); BObject* pobj = m_pDoc->GetObject(idObj); pdat->SetLink(pobj); //,, memory leak, no? need to delete what's already there // Store the data in the property object pobjPropertyValue->SetData(pdat); } else { // Link object is zero, so delete the property bobject. DeleteProperty(idProperty, FALSE, FALSE); } // Set document modified flag if specified if (bSetModifiedFlag) m_pDoc->SetModifiedFlag(TRUE); // Update all views if specified if (bUpdateViews) { CHint h; h.pobjObject = this; h.idProperty = idProperty; m_pDoc->UpdateAllViewsEx(NULL, hintPropertyChange, &h); } return TRUE; } BOOL BObject::SetPropertyLinks(OBJID idProperty, CObArray* pa, BOOL bSetModifiedFlag, BOOL bUpdateViews) { ASSERT_VALID(this); ASSERT(idProperty); if (pa) { ASSERT_VALID(pa); // Find/create property value bobject BObject* pobjPropertyValue = FindProperty(idProperty, TRUE); ASSERT_VALID(pobjPropertyValue); BDataLink* pdat = DYNAMIC_DOWNCAST(BDataLink, pobjPropertyValue->GetData()); if (!pdat) { // Create new data object to hold data and initialize it pdat = DYNAMIC_DOWNCAST(BDataLink, m_pDoc->CreateBData(idProperty)); pdat->SetMultiple(); // store in pobj pobjPropertyValue->SetData(pdat); } ASSERT(pdat); ASSERT(pdat->IsMultiple()); //, eh //, ugh merge bdatalink with bobjects and standardize all this CObArray* paObject = pdat->GetLinkArray(); ASSERT_VALID(paObject); // always true? paObject->Append(*pa); } else { // Link object is zero, so delete the property bobject. DeleteProperty(idProperty, FALSE, FALSE); } // Set document modified flag if specified if (bSetModifiedFlag) m_pDoc->SetModifiedFlag(TRUE); // Update all views if specified if (bUpdateViews) { CHint h; h.pobjObject = this; h.idProperty = idProperty; m_pDoc->UpdateAllViewsEx(NULL, hintPropertyChange, &h); } return TRUE; } //x /* BOOL BObject::SetPropertyColumnsAdd(OBJID idProperty, OBJID idObj, BOOL bSetModifiedFlag, BOOL bUpdateViews) { ASSERT_VALID(this); ASSERT(idProperty); ASSERT(idObj); BDataColumns* pdatColumns = this->GetPropertyColumns(idProperty); //x pdatColumns->InsertColumn(idObj, &doc); pdatColumns->InsertColumn(idObj, m_pDoc); this->SetPropertyData(idProperty, pdatColumns, bSetModifiedFlag, bUpdateViews); delete pdatColumns; return TRUE; } */ // Add an object to a multilink property BOOL BObject::SetPropertyLinksAdd(OBJID idProperty, OBJID idObj, BOOL bSetModifiedFlag, BOOL bUpdateViews) { ASSERT_VALID(this); ASSERT(idProperty); ASSERT(idObj); // Find/create property value bobject //,, make a BPropValue class? BObject* pobjPropertyValue = FindProperty(idProperty, TRUE); ASSERT_VALID(pobjPropertyValue); // similarly the bdata may or may not exist yet, but there's // no similar function to get/add one? //x pobjPropertyValue->SetPropertyData(idProperty, pdat BDataLink* pdat = DYNAMIC_DOWNCAST(BDataLink, pobjPropertyValue->GetData()); if (!pdat) { pdat = DYNAMIC_DOWNCAST(BDataLink, m_pDoc->CreateBData(idProperty)); pdat->SetMultiple(); // store in pobj pobjPropertyValue->SetData(pdat); } ASSERT(pdat); ASSERT(pdat->IsMultiple()); pdat->AddLinkID(idObj, m_pDoc); // Set document modified flag if specified if (bSetModifiedFlag) m_pDoc->SetModifiedFlag(TRUE); // Update all views if specified if (bUpdateViews) { CHint h; h.pobjObject = this; h.idProperty = idProperty; m_pDoc->UpdateAllViewsEx(NULL, hintPropertyChange, &h); } return TRUE; } //xOBJID BObject::GetPropertyLink(OBJID lngPropertyID, BOOL bCreateTempBDataIfNotFound) OBJID BObject::GetPropertyLink(OBJID lngPropertyID) { ASSERT_VALID(this); ASSERT(lngPropertyID); //x ASSERT(bCreateTempBDataIfNotFound == FALSE); // not used switch (lngPropertyID) { case propClassID: return m_lngClassID; //, case propIconID: // return m_lngIconID; // but could be zero... case propLocation: return m_pobjParent->id; } BObject* pobjPropertyValue = FindProperty(lngPropertyID, FALSE); if (pobjPropertyValue) { ASSERT_VALID(pobjPropertyValue); BDataLink* pdat = DYNAMIC_DOWNCAST(BDataLink, pobjPropertyValue->GetData()); if (pdat) { ASSERT_VALID(pdat); BObject* pobjLink = pdat->GetLink(); if (pobjLink) { ASSERT_VALID(pobjLink); return pobjLink->id; } } } return 0; } //x /* //ObjIDArray BObject::GetPropertyLinks(OBJID lngPropertyID, BOOL bCreateTempBDataIfNotFound) void BObject::GetPropertyLinks(OBJID lngPropertyID, ObjIDArray& a) //ObjIDArray* BObject::GetPropertyLinks(OBJID lngPropertyID) { ASSERT_VALID(this); ASSERT(lngPropertyID); //x ASSERT(bCreateTempBDataIfNotFound == FALSE); // not used BObject* pobjPropertyValue = FindProperty(lngPropertyID, FALSE); if (pobjPropertyValue) { ASSERT_VALID(pobjPropertyValue); BDataLink* pdat = DYNAMIC_DOWNCAST(BDataLink, pobjPropertyValue->GetData()); if (pdat) { ASSERT_VALID(pdat); ASSERT(pdat->IsMultiple()); // ObjIDArray* pida = new ObjIDArray(); // CObArray* pp = pdat->GetLinkArray(); CUIntArray b; int nObjs = pdat->GetObjectIDArray(b); //, use this and delete the above method // CObArray* pp = pdat->GetLinkArray(); //, better way? a.SetSize(b.GetSize()); for (int i = 0; i < b.GetSize(); i++) a.SetAt(i, b.GetAt(i)); // pida->SetSize(pp->GetSize()); // for (int i = 0; i < pp->GetSize(); i++) // pida->SetAt(i, pp->GetAt(i)); // return pida; // return a; } } } */ // Returns COPY of link array - caller must delete it CObArray* BObject::GetPropertyLinks(ULONG lngPropertyID) { ASSERT_VALID(this); ASSERT(lngPropertyID); BObject* pobjPropertyValue = FindProperty(lngPropertyID, FALSE); if (pobjPropertyValue) { ASSERT_VALID(pobjPropertyValue); BDataLink* pdat = DYNAMIC_DOWNCAST(BDataLink, pobjPropertyValue->GetData()); if (pdat) { ASSERT_VALID(pdat); ASSERT(pdat->IsMultiple()); CObArray* plocal = pdat->GetLinkArray(); ASSERT_VALID(plocal); // MFC: no copy constructor? gives weird cobject errors // CObArray* pcopy = new CObArray(*plocal); CObArray* pcopy = new CObArray(); pcopy->Append(*plocal); return pcopy; } } return NULL; } // Get number of children, recursively if specified, and including properties if specified. int BObject::GetChildCount(BOOL bRecurse /* = FALSE */, BOOL bIncludeProperties /* = FALSE */) const { ASSERT_VALID(this); int nChildren = 0; if (m_paChildren) { ASSERT_VALID(m_paChildren); // Add number of children to count int nItems = m_paChildren->GetSize(); nChildren += nItems; // If recursive, walk through the children, summing the number of their children also if (bRecurse) { for (int i = 0; i < nItems; i++) { BObject* pobjChild = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(i)); ASSERT_VALID(pobjChild); nChildren += pobjChild->GetChildCount(bRecurse, bIncludeProperties); } } } if (bIncludeProperties && m_paProperties) { ASSERT_VALID(m_paProperties); // Add number of properties to count int nItems = m_paProperties->GetSize(); nChildren += nItems; } return nChildren; } // Returns 1+ if has children, 0 if doesn't. int BObject::HasChildren() const { ASSERT_VALID(this); if (m_paChildren) { ASSERT_VALID(m_paChildren); return m_paChildren->GetSize(); } return 0; } // Display properties of object. void BObject::DisplayProperties() { ASSERT_VALID(this); //, add these to page: // Flags (checkboxes or checklistbox) // Icon (display and let user change) // Children (count and size, recursive) // Properties (listview with values) // maybe the page could load a cviewproperties object? // i think eventually that would be the best - then could modify properties for any object // from anywhere in the app // eg in a family tree, or scrapbook, or map... CPropertySheetEx2 sh; CPageObjectGeneral pg; sh.m_psh.dwFlags |= PSH_NOAPPLYNOW; // turn off apply button sh.AddPage(&pg); CString strName = GetPropertyString(propName); sh.SetTitle(strName, PSH_PROPTITLE); pg.m_pobj = this; if (sh.DoModal() == IDOK) { // Note: OnApply will have already applied changes to the object and notified the views. } } // Check if an object is a child or grandchild etc of another object. // see also IsChildOf BOOL BObject::IsChild(BObject* pobjPossibleParent) const { ASSERT_VALID(this); const BObject* pobj = this; // Look up through object's parent chain for the possible parent object while (pobj->m_pobjParent) { pobj = pobj->m_pobjParent; if (pobj == pobjPossibleParent) return TRUE; } return FALSE; } // Check if object is in child collection of specified parent object. // see also IsChild BOOL BObject::IsChildOf(BObject* pobjPossibleParent, BOOL bRecurse) const { ASSERT_VALID(this); ASSERT_VALID(pobjPossibleParent); if (pobjPossibleParent->GetChildren()) { ASSERT_VALID(pobjPossibleParent->GetChildren()); if (pobjPossibleParent->GetChildren()->FindObject(this, bRecurse) != -1) return TRUE; } return FALSE; } // Get the size of the object in bytes, including itself, all its properties, and optionally // its children recursively. ULONG BObject::GetMemoryUsed(BOOL bRecurse) const { ASSERT_VALID(this); ULONG nBytes = 0; nBytes += sizeof(BObject); //, add size of string cache? // CString m_strTextCache; // This is a cache for the text-representation for this data object // Add size of bdata object if (m_pdat) { ASSERT_VALID(m_pdat); nBytes += m_pdat->GetMemoryUsed(TRUE); } // Walk through properties, adding their sizes if (m_paProperties) { ASSERT_VALID(m_paProperties); nBytes += sizeof(BObjects); // Add size of array object int nProperties = m_paProperties->GetSize(); for (int i = 0; i < nProperties; i++) { BObject* pobjProperty = DYNAMIC_DOWNCAST(BObject, m_paProperties->GetAt(i)); ASSERT_VALID(pobjProperty); nBytes += pobjProperty->GetMemoryUsed(TRUE); } } // Walk through children, getting their sizes also if (bRecurse) { if (m_paChildren) { ASSERT_VALID(m_paChildren); nBytes += sizeof(BObjects); // Add size of array object int nChildren = m_paChildren->GetSize(); for (int i = 0; i < nChildren; i++) { BObject* pobjChild = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(i)); ASSERT_VALID(pobjChild); nBytes += pobjChild->GetMemoryUsed(TRUE); } } } return nBytes; } // Get array of PropertyDef objects that are applicable to this object. // Walks up class chain to get inherited properties, filling array with pointers // to propdefs. // If bInheritedOnly is True, will only get propertydefs as inherited by this // class's class hierarchy. // If bThisIsAClass is True, will treat this object as a class. Note this could be a // class but you want to treat is as an object, as when viewing Property View for // a classdef. // Returns number of propertydefs in array. int BObject::GetPropertyDefs(CObArray& aPropertyDefs, BOOL bInheritedOnly, BOOL bThisIsAClass) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); //, make global const, enforce this const int nMaxClassDepth = 10; // Maximum depth of class hierarchy // Initialize array CObArray apClasses; apClasses.SetSize(nMaxClassDepth); int nClasses = 0; // If this object is itself a classdef, then we need to add it to the array first, // otherwise, the first class is the class of this object. // Note: Only do this if requesting inherited propdefs only, which is done in class wizard properties page. BObject* pobjClass = 0; // if (m_lngClassID == classClass) // if (bInheritedOnly && (m_lngClassID == classClass)) if (bThisIsAClass && (m_lngClassID == classClass)) pobjClass = this; else pobjClass = m_pDoc->GetObject(m_lngClassID); // Walk up the class chain, pushing classdef pointers to a stack // when reach the root, add its propObjectProperties array to our array // then walk down the stack, adding propObjectProperties arrays to our array // at end of stack, add the object's property array to our array, eliminating duplicate properties do { ASSERT_VALID(pobjClass); // Save the pointer to the class in our "stack" apClasses.SetAt(nClasses, pobjClass); nClasses++; // Get the class's parent class pobjClass = pobjClass->GetParent(); } // Exit when reach the system root // NOTE: This assumes that class root is always located in the system root while (pobjClass->GetObjectID() != rootSystem); // Walk through class chain from top to bottom, adding propObjectProperties to our array. // If user just wants inherited props, don't include the object's classdef props. int nFirst = bInheritedOnly ? 1 : 0; for (int i = nClasses - 1; i >= nFirst; i--) { pobjClass = DYNAMIC_DOWNCAST(BObject, apClasses.GetAt(i)); ASSERT_VALID(pobjClass); CObArray* pa = pobjClass->GetPropertyLinks(propObjectProperties); if (pa) aPropertyDefs.Append(*pa); //x /* BDataLink* pdatLink = DYNAMIC_DOWNCAST(BDataLink, pobjClass->GetPropertyData(propObjectProperties)); // CObArray* pa = pobjClass->GetPropertyLinks(propObjectProperties); if (pdatLink) { ASSERT_VALID(pdatLink); // Append the array of pobj's to the list of property defs. // Might need to exclude some properties, eg exclude flagSystemProperty if not in admin mode, // but i think it's better to just do that in the property view. CObArray* pa = pdatLink->GetLinkArray(); if (pa) { CObArray& ra = *pa; aPropertyDefs.Append(ra); } delete pdatLink; } */ } // Add any custom properties not in the preceding collections to the end. // Need to walk through current property collection, and if a prop is not in the current array, add it. //, ie // m_paProperties.Remove(aProperties); // remove the intersection of the arrays // aProperties.Append(m_paProperties); // now append them // Would do this now but would add another layer of inheritance and not sure how that would // affect performance at this point (ie derive our own array class from CObArray). // How would that affect performance? maybe it wouldn't except in constructor and destructor? // ie the vtable would point to the correct routines anyway? if (m_paProperties && !bInheritedOnly) { ASSERT_VALID(m_paProperties); int nProps = m_paProperties->GetSize(); int nPropsTotal = aPropertyDefs.GetSize(); for (int i = 0; i < nProps; i++) { // Get property value, then property def from it BObject* pobjPropValue = DYNAMIC_DOWNCAST(BObject, m_paProperties->GetAt(i)); ASSERT_VALID(pobjPropValue); OBJID lngPropertyID = pobjPropValue->GetClassID(); BObject* pobjPropDef = m_pDoc->GetObjectNull(lngPropertyID); if (!pobjPropDef) { CString str; str.Format("Found a property that has no propertydef (propid = %d) - delete it (recommended)?", lngPropertyID); if (IDYES == AfxMessageBox(str, MB_YESNO)) { m_paProperties->RemoveAt(i); i--; nProps--; } } else { ASSERT_VALID(pobjPropDef); // Walk through array and see if this property is already there. // If not, add it to the array. BOOL bNotThere = TRUE; for (int j = 0; j < nPropsTotal; j++) { if (aPropertyDefs.GetAt(j) == DYNAMIC_DOWNCAST(CObject, pobjPropDef)) { bNotThere = FALSE; break; } } if (bNotThere) aPropertyDefs.Add(pobjPropDef); } } } return aPropertyDefs.GetSize(); } /* // see getreferences // Search through document, looking for links to this object. // Returns total number of links. //. add objects that link to this object to the array //, move this to BDoc - like Search int BObject::GetLinks(BObjects &aObjects, BObject* pobjStart) { ASSERT_VALID(this); ASSERT_VALID(&aObjects); // Start at main root object if (pobjStart == NULL) pobjStart = m_pDoc->GetRoot(); ASSERT_VALID(pobjStart); // See if the start object has any references to this object pobjStart->m_lngClassID; pobjStart->m_lngIconID; pobjStart->m_pobjParent; pobjStart->m_pdat->GetLinks(this); // walk through properties, searching for references to this object if (pobjStart->m_paProperties) { int nItems = pobjStart->m_paProperties->GetSize(); for (int i = 0; i < nItems; i++) { BObject* pobjProp = (BObject*) pobjStart->m_paProperties->GetAt(i); GetLinks(aObjects, pobjProp); } } // Recurse through all objects, searching for links to this object if (pobjStart->GetChildren()) { // walk through children int nItems = pobjStart->GetChildren()->GetSize(); for (int i = 0; i < nItems; i++) { BObject* pobj = (BObject*) pobjStart->GetChildren()->GetAt(i); GetLinks(aObjects, pobj); } } return aObjects.GetSize(); } */ //, move to BProperty // Get the alignment (left, right, center) associated with this propertydef bobject. // Numbers are right aligned, strings are left aligned. // Returns LVCFMT_LEFT, LVCFMT_RIGHT, or LVCFMT_CENTER. // This is used by CViewContents. int BObject::GetPropertyDefAlignment() { ASSERT_VALID(this); OBJID idPropType = GetPropertyLink(propPropertyType); ASSERT(idPropType); int nAlignment = LVCFMT_LEFT; // default is left-aligned switch (idPropType) { case proptypeNumber: case proptypeCurrency: case proptypeTimeInterval: case proptypeCalculated: case proptypeLong: nAlignment = LVCFMT_RIGHT; break; } return nAlignment; } // Return True if the parent of this object is set for autosort BOOL BObject::IsParentSorted() { ASSERT_VALID(this); BObject* pobjParent = GetParent(); if (pobjParent) { ASSERT_VALID(pobjParent); return (!(pobjParent->GetFlag(flagNoAutosort))); } return FALSE; } // Return True if the object is set to have its children autosorted BOOL BObject::IsSorted() { ASSERT_VALID(this); return (!(this->GetFlag(flagNoAutosort))); } // Move this object up relative to its siblings. // Sets document modified flag and updates views. //, using our own cobarray class we could have an Exchange method BOOL BObject::MoveUp() { ASSERT_VALID(this); if (m_pobjParent) { BObjects* pa = m_pobjParent->GetChildren(); ASSERT_VALID(pa); // Switch the positions of the two pointers int nIndex = pa->FindObject(this); if (nIndex != -1) { if (nIndex > 0) { int nIndexOther = nIndex - 1; BObject* pobjOther = DYNAMIC_DOWNCAST(BObject, pa->GetAt(nIndexOther)); ASSERT_VALID(pobjOther); pa->SetAt(nIndexOther, this); pa->SetAt(nIndex, pobjOther); // Set document modified flag m_pDoc->SetModifiedFlag(); // Now tell views // basically a move to the same parent, with a different index? // in future, might have drag drop to new location // we have the two objects that are exchanging positions // tree needs pobj, pobjdest, bAfter // in this case we're moving it before the given item CHint h; h.pobjObject = this; h.pobjTarget = pobjOther; h.bAfter = FALSE; m_pDoc->UpdateAllViewsEx(NULL, hintReposition, &h); return TRUE; } } } return FALSE; } // Move this object down relative to its siblings. // Sets document modified flag and updates views. BOOL BObject::MoveDown() { ASSERT_VALID(this); if (m_pobjParent) { BObjects* pa = m_pobjParent->GetChildren(); ASSERT_VALID(pa); // Switch the positions of the two pointers int nIndex = pa->FindObject(this); int nItems = pa->GetSize(); if (nIndex != -1) { if (nIndex < nItems - 1) { int nIndexOther = nIndex + 1; BObject* pobjOther = DYNAMIC_DOWNCAST(BObject, pa->GetAt(nIndexOther)); ASSERT_VALID(pobjOther); pa->SetAt(nIndexOther, this); pa->SetAt(nIndex, pobjOther); // Set document modified flag m_pDoc->SetModifiedFlag(); // Now tell views CHint h; h.pobjObject = this; h.pobjTarget = pobjOther; h.bAfter = TRUE; m_pDoc->UpdateAllViewsEx(NULL, hintReposition, &h); return TRUE; } } } return FALSE; } // Edit the value associated with the given property in a dialog. // Returns True if user hit OK. // Note: This will set document modified flag and tell all views about any property change also. //xBOOL BObject::UIEditValue(OBJID lngPropertyID) BOOL BObject::UIEditValue(OBJID lngPropertyID, CUI& ui) { ASSERT_VALID(this); ASSERT(lngPropertyID); CWaitCursor cw; // Get propertydef object for the property BObject* pobjPropertyDef = m_pDoc->GetObject(lngPropertyID); // Check if property is read-only if (pobjPropertyDef->GetFlag(flagPropValueReadOnly)) { AfxMessageBox("This property value is read-only and cannot be changed.", MB_ICONINFORMATION); return FALSE; } // Get a copy of BData associated with object's property. // If user says OK, then we write the edited bdata object back to the object, which will // always write it to the bobject, not up the class chain. BOOL ret = FALSE; BData* pdat = GetPropertyData(lngPropertyID, TRUE); if (pdat) { ASSERT_VALID(pdat); // UIEditValue will bring up a dialog box that lets user modify the value stored in the BData object. // Need to pass object and property so it knows the context. // It will return True if user said OK in dialog. //x ret = pdat->UIEditValue(this, pobjPropertyDef); //x ret = pdat->UIEditValue(this, pobjPropertyDef, ui); ret = pdat->UIEditValue(ui, this, pobjPropertyDef); if (ret) { // User said OK, so let's set the BData copy with the new value to the object. // This also sets the document modified flag and updates views. SetPropertyData(lngPropertyID, pdat); } delete pdat; } return ret; } // Get the default column width for this propertydef, in pixels. // This is used by CViewContents when you insert a new column. int BObject::GetPropertyDefWidth() { //, hardcode for now, later could make a property to store this info in each propertydef int nWidth = 120; // default in pixels switch (m_lngObjectID) { case propDescription: nWidth = 200; break; } return nWidth; } // Get the default name for a new object of this class, eg "New Paper". //, might make a property eventually (ie you could use something different for some classes). BOOL BObject::GetClassDefNewName(CString& strName) { strName = CString(_T("New ")) + GetPropertyString(propName); return TRUE; } // Check if the object can be moved up or down relative to its siblings. // This can only be true for objects which parents have autosort turned off (they have flagNoAutosort). // For the most part, if flagNoAutosort is set for an object, we want to be able to move // its children up and down, EXCEPT for the Home, Reference and System objects. // Could handle with another flag, but for now hardcode this. BOOL BObject::IsMoveUpDownValid(BOOL bMoveUp) { ASSERT_VALID(this); // If parent has autosort off, then bEnable will be True BOOL bEnable = !IsParentSorted(); if (m_pobjParent) { // Exception for children of the main root object (eg Home, Reference). // (they have NoAutosort but you don't want user to move them around). ASSERT_VALID(m_pobjParent); if (m_pobjParent->GetObjectID() == rootMain) { // let admin move items up and down (note: no handling for first or last item) if (app.m_bAdmin) bEnable = TRUE; else bEnable = FALSE; } else if (bEnable) { // Check if first or last among siblings BObjects* paSiblings = m_pobjParent->GetChildren(); ASSERT_VALID(paSiblings); int nIndex = paSiblings->FindObject(this); int nItems = paSiblings->GetSize(); // Bug: Had these if statements without the brackets, which screwed up the logic! be careful about that. if (bMoveUp) { // If first item in list, disable moveup if (nIndex == 0) bEnable = FALSE; } else { // If last item in list, disable movedown if (nIndex == nItems - 1) bEnable = FALSE; } } } // If object has no parent then it must be the main root object, so disable else bEnable = FALSE; return bEnable; } // Change this object's class, handling name data type change, also updating views. // This should always be used rather than setting m_lngClassID directly. BOOL BObject::SetClassID(OBJID lngNewClassID) { ASSERT_VALID(this); ASSERT_VALID(m_pdat); ASSERT_VALID(m_pDoc); ASSERT(lngNewClassID); // See if we need to handle name data type change - // compare existing bdata type and new bdata type. CRuntimeClass* prcOld = m_pdat->GetRuntimeClass(); // Get the new name bdata as required by the new class. // This will be BDataString or BDataPersonName (for now) BData* pdatNew = m_pDoc->CreateBData(lngNewClassID); CRuntimeClass* prcNew = pdatNew->GetRuntimeClass(); // If the name bdata objects are the same type, we can leave it as it is, so delete the new one. if (prcOld == prcNew) { delete pdatNew; pdatNew = 0; } else { // The name bdata types are different, so we need to convert between them and store the // new one with this bobject. CString strName = m_pdat->GetBDataText(m_pDoc, propName); pdatNew->SetBDataText(strName); // Delete the old bdata object delete m_pdat; // Store the new bdata object m_pdat = pdatNew; } // Set class and document modified flag m_lngClassID = lngNewClassID; // Set modified flag m_pDoc->SetModifiedFlag(TRUE); // Inform views of change CHint h; h.pobjObject = this; h.idProperty = propClassID; m_pDoc->UpdateAllViewsEx(NULL, hintPropertyChange, &h); // Also broadcast hints for all dependent properties //, need generic way of handling this h.idProperty = propClassName; m_pDoc->UpdateAllViewsEx(NULL, hintPropertyChange, &h); h.idProperty = propIconID; m_pDoc->UpdateAllViewsEx(NULL, hintPropertyChange, &h); return TRUE; } // Fill an array with this object's parents, stopping at the specified object. // Can specify to include this object and the stopping object. // Returns number of items in array. int BObject::GetParents(BObjects &aParents, BObject *pobjStopAt, BOOL bIncludeThisObject /* = TRUE */, BOOL bIncludeStopObject /* = FALSE */) { ASSERT_VALID(this); ASSERT_VALID(&aParents); ASSERT(bIncludeStopObject == FALSE); //, for now // Clear array aParents.RemoveAll(); // Get starting object BObject* pobj = 0; if (bIncludeThisObject) pobj = this; else pobj = m_pobjParent; do { if (pobj == 0) break; ASSERT_VALID(pobj); aParents.Add(pobj); pobj = pobj->m_pobjParent; } while (pobj != pobjStopAt); return aParents.GetSize(); } // Set or clear a flag for this object, recursing through children if specified. // Possible flags are flagExpanded, flagNoDelete, flagTemp, flagFilter, flagDisabled, etc. // This will set document modified flag if it's an important flag. void BObject::SetFlag(ULONG lngFlag, BOOL bValue /*=TRUE*/, BOOL bRecurse /* = FALSE */) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); if (bValue) m_lngFlags |= lngFlag; else m_lngFlags &= ~lngFlag; if (bRecurse) { // Walk through children and call this routine recursively int nChildren = GetChildCount(FALSE); for (int i = 0; i < nChildren; i++) { BObject* pobj = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(i)); ASSERT_VALID(pobj); pobj->SetFlag(lngFlag, bValue, bRecurse); } } // Changing the flags listed here will not set the document modified flag const ULONG lngImportantFlags = ~(flagExpanded | flagTemp | flagFilter | flagDisabled); // Set document modified if it's an important flag // if (lngFlag != flagExpanded && lngFlag != flagTemp && lngFlag != flagFilter) if (lngFlag & lngImportantFlags) m_pDoc->SetModifiedFlag(); } void BObject::ClearFlag(ULONG lngFlag) { SetFlag(lngFlag, FALSE); } // Get the value of the specified flag for this object. (flagNoDelete, flagHighPriority, etc). inline BOOL BObject::GetFlag(ULONG lngFlag) { return (m_lngFlags & lngFlag); } // Call this method to send a message to this bobject and optionally all of its children recursively. // For now just implements msgResetData, which will cause any bdata text cache's to be reset. // (just does it for name property for now) int BObject::SendMessage(ULONG lngMsg, BOOL bRecurse) { ASSERT_VALID(this); switch (lngMsg) { case msgResetData: { // Walk through all property bdatas and reset them. // Also reset m_pdat. //, for now, this is enough since we just use it to reset names. if (m_pdat) { ASSERT_VALID(m_pdat); m_pdat->ResetData(); } break; } } // Now walk through children and call this method recursively if (m_paChildren) { ASSERT_VALID(m_paChildren); int nChildren = m_paChildren->GetSize(); for (int i = 0; i < nChildren; i++) { BObject* pobj = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(i)); ASSERT_VALID(pobj); pobj->SendMessage(lngMsg, bRecurse); } } return 0; } // Set icon and document modified flag, and update views //, validate iconid BOOL BObject::SetIconID(OBJID lngIconID) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); // If icon is default for the object, store it as zero if (lngIconID == GetDefaultIconID()) m_lngIconID = 0; else m_lngIconID = lngIconID; // Set document flag m_pDoc->SetModifiedFlag(TRUE); // Inform views of change CHint h; h.pobjObject = this; h.idProperty = propIconID; m_pDoc->UpdateAllViewsEx(NULL, hintPropertyChange, &h); // If this is a classdef object, refresh all visible icons // bug: used = instead of == and wound up converting all objects to classes if (m_lngClassID == classClass) m_pDoc->UpdateAllViewsEx(NULL, hintRefreshAllIcons); return TRUE; } //x /* //, move to bfolder BOOL BObject::SetColumns(BDataColumns& cols) { ASSERT_VALID(this); BOOL bResult = this->SetPropertyData(propColumnInfoArray, &cols); // sends hint delete &cols; return bResult; } */ // For this folder object, initialize the column array (propColumnInfoArray) // to reflect the properties used by the default class. //, move to bfolder void BObject::SetColumnsBasedOnClass(BObject *pobjDefaultClass) { BDataColumns* pdatCols = new BDataColumns; ULONG lngExcludeFlags = flagAdminOnly; // always exclude admin only props (eg ObjectID) BObjects aProps; int nProps = pobjDefaultClass->GetPropertyDefs(aProps, FALSE, TRUE); // get props associated with class for (int i = 0; i < nProps; i++) { BObject* pobjProp = DYNAMIC_DOWNCAST(BObject, aProps.GetAt(i)); ASSERT_VALID(pobjProp); if (!(pobjProp->GetFlag(lngExcludeFlags))) { OBJID lngPropertyID = pobjProp->GetObjectID(); //. kludgy: don't add the Size property by default, though it's available to all objects. if (lngPropertyID != propSize) pdatCols->InsertColumn(lngPropertyID, m_pDoc); } } SetPropertyData(propColumnInfoArray, pdatCols, FALSE, FALSE); delete pdatCols; } // Change the property type for the specified property to the new property type, // recursing downwards through child objects. // See also ChangeNamePropertyType //, pobjPropertyDef is required for some SetDataText's, unfortunately! void BObject::ChangePropertyType(BObject* pobjPropertyDef, BObject* pobjNewPropertyDef, OBJID lngNewPropertyTypeID) { ASSERT_VALID(this); ASSERT_VALID(pobjPropertyDef); ASSERT_VALID(pobjNewPropertyDef); OBJID lngPropertyID = pobjPropertyDef->GetObjectID(); // Walk through properties looking for property in question if (m_paProperties) { ASSERT_VALID(m_paProperties); int nProperties = m_paProperties->GetSize(); for (int i = 0; i < nProperties; i++) { BObject* pobj = DYNAMIC_DOWNCAST(BObject, m_paProperties->GetAt(i)); ASSERT_VALID(pobj); if (pobj->m_lngClassID == lngPropertyID) { BData* pdatOld = pobj->GetData(); // Create the new bdata type object BData* pdatNew = m_pDoc->CreateBDataFromPropertyType(lngNewPropertyTypeID); // Convert between the types using a string as the go-between. // Don't display any error messages. CString strText = pdatOld->GetBDataText(m_pDoc, lngPropertyID); // pdatNew->SetBDataText(strText, pobjPropertyDef); // pdatNew->SetBDataText(strText, pobjNewPropertyDef); pdatNew->SetBDataText(strText, pobjNewPropertyDef, FALSE); // Delete the old bdata object delete pdatOld; // Store the new bdata object pobj->m_pdat = pdatNew; } } } // Now walk through children and call this method recursively if (m_paChildren) { ASSERT_VALID(m_paChildren); int nChildren = m_paChildren->GetSize(); for (int i = 0; i < nChildren; i++) { BObject* pobj = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(i)); ASSERT_VALID(pobj); // pobj->ChangePropertyType(pobjPropertyDef, lngPropertyID, lngNewPropertyTypeID); pobj->ChangePropertyType(pobjPropertyDef, pobjNewPropertyDef, lngNewPropertyTypeID); } } } // Recurse downwards through objects and change the name bdata property type for // objects of the specified class. // See also ChangePropertyType void BObject::ChangeNamePropertyType(OBJID lngClassID, OBJID lngNewPropertyTypeID) { ASSERT_VALID(this); // If this object is of the specified class, change its name bdata object if (m_lngClassID == lngClassID) { BData* pdatOld = m_pdat; // Create the new bdata type object BData* pdatNew = m_pDoc->CreateBDataFromPropertyType(lngNewPropertyTypeID); // Convert between the types using a string as the go-between. // Don't display any error messages. //. For now this just occurs between BDataString and BDataPersonName, so we don't // have to worry about propertydefs, but in future version might need to handle them! CString strName = pdatOld->GetBDataText(m_pDoc, 0); pdatNew->SetBDataText(strName, 0, FALSE); // Delete the old bdata object delete pdatOld; // Store the new bdata object m_pdat = pdatNew; } // Now walk through children and call this method recursively if (m_paChildren) { ASSERT_VALID(m_paChildren); int nChildren = m_paChildren->GetSize(); for (int i = 0; i < nChildren; i++) { BObject* pobj = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(i)); ASSERT_VALID(pobj); pobj->ChangeNamePropertyType(lngClassID, lngNewPropertyTypeID); } } } // Find references in this object and its properties to the Find object. // If recurse is specified, will search recursively through any child objects also. //. eventually add an object that includes the pobj referencing it and the propid. int BObject::GetReferences(BObject *pobjFind, CObArray &aRefs, BOOL bRecurse) { ASSERT_VALID(this); ASSERT_VALID(pobjFind); ASSERT_VALID(&aRefs); BOOL bReferenced = FALSE; OBJID lngFindID = pobjFind->GetObjectID(); // Exit if objectid is zero (can happen if it's a temporary object, not in the db) if (lngFindID == 0) return aRefs.GetSize(); // Search in attributes if (m_lngClassID == lngFindID) bReferenced = TRUE; if (m_lngIconID == lngFindID) bReferenced = TRUE; // Search in this object's bdata if (m_pdat) { ASSERT_VALID(m_pdat); if (m_pdat->FindReferences(pobjFind)) bReferenced = TRUE; } // If we haven't found a reference yet, search through this object's properties' bdata objects // until you find a reference. // Also check each propertyid. if (!bReferenced && m_paProperties) { ASSERT_VALID(m_paProperties); int nProps = m_paProperties->GetSize(); for (int i = 0; i < nProps; i++) { BObject* pobjProp = DYNAMIC_DOWNCAST(BObject, m_paProperties->GetAt(i)); ASSERT_VALID(pobjProp); // Check if this property value is using the find object as its propertydef if (pobjProp->GetClassID() == lngFindID) { bReferenced = TRUE; break; } // Check if the property value data references the find object ASSERT_VALID(pobjProp->GetData()); if (pobjProp->GetData()->FindReferences(pobjFind)) { bReferenced = TRUE; break; } } } // If there was a reference to the Find object in this object, // add this object to the list of references if (bReferenced) aRefs.Add(this); // Search through children (if recurse specified) if (bRecurse && m_paChildren) { ASSERT_VALID(m_paChildren); int nChildren = m_paChildren->GetSize(); for (int i = 0; i < nChildren; i++) { BObject* pobjChild = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(i)); ASSERT_VALID(pobjChild); pobjChild->GetReferences(pobjFind, aRefs, bRecurse); } } return aRefs.GetSize(); } // Remove references to an object, or replace references with a new object if specified, // optionally recursing downwards. void BObject::ReplaceReferences(BObject* pobjFind, BObject* pobjNew /* = 0 */, BOOL bRecurse /* = TRUE */) { //trace("BObject::ReplaceReferences\n"); ASSERT_VALID(this); ASSERT_VALID(pobjFind); CHint h; h.pobjObject = this; OBJID lngFindID = pobjFind->GetObjectID(); OBJID lngNewID = 0; if (pobjNew) { ASSERT_VALID(pobjNew); lngNewID = pobjNew->GetObjectID(); } // Check class if (m_lngClassID == lngFindID) { // If new id is 0, we'll want to delete this object entirely, as it's a property value? // Actually, this should never happen, as we check if it's a classdef and pass classPaper. ASSERT(lngNewID); // if (lngNewID == 0) // { // } // else // { SetClassID(lngNewID); // Tell views // h.idProperty = propClass; // m_pDoc->UpdateAllViewsEx(0, hintPropertyChange, &h); h.idProperty = propClassName; m_pDoc->UpdateAllViewsEx(0, hintPropertyChange, &h); // } } // Check icon if (m_lngIconID == lngFindID) { m_lngIconID = lngNewID; // Tell views // h.idProperty = propIconID; // m_pDoc->UpdateAllViewsEx(0, hintPropertyChange, &h); } // Check this object's bdata if (m_pdat) { ASSERT_VALID(m_pdat); if (m_pdat->ReplaceReferences(pobjFind, pobjNew)) { // Tell views h.idProperty = m_lngClassID; m_pDoc->UpdateAllViewsEx(0, hintPropertyChange, &h); } } // Check property values, if any. if (m_paProperties) { ASSERT_VALID(m_paProperties); int nProps = m_paProperties->GetSize(); for (int i = 0; i < nProps; i++) { BObject* pobjPropertyValue = DYNAMIC_DOWNCAST(BObject, m_paProperties->GetAt(i)); ASSERT_VALID(pobjPropertyValue); // If the property def of this property value is the object we're looking for, delete the property value. //, note this doesn't handle replace for property values yet - might need to adjust bdata objects also if (pobjPropertyValue->GetClassID() == lngFindID) { // Bug: Called DeleteProperty on the property value instead of on this bobject // pobjPropertyValue->DeleteProperty(lngFindID); DeleteProperty(lngFindID); // adjust indexes so can continue through array i--; nProps--; } else { // Remove/replace any references contained in the property value's bdata. ASSERT_VALID(pobjPropertyValue->GetData()); if (pobjPropertyValue->GetData()->ReplaceReferences(pobjFind, pobjNew)) { // Tell views h.idProperty = pobjPropertyValue->GetClassID(); m_pDoc->UpdateAllViewsEx(0, hintPropertyChange, &h); } } } } // Search through children (if recurse was specified) if (bRecurse && m_paChildren) { ASSERT_VALID(m_paChildren); int nChildren = m_paChildren->GetSize(); for (int i = 0; i < nChildren; i++) { BObject* pobjChild = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(i)); ASSERT_VALID(pobjChild); pobjChild->ReplaceReferences(pobjFind, pobjNew, bRecurse); } } } // Sort the children of this object (physically) in alphabetical order. BOOL BObject::SortChildren() { if (m_paChildren) { ASSERT_VALID(m_paChildren); m_paChildren->Sort(propName); } return TRUE; } // Delete this object and any children recursively. // Will ask to remove references if any exist, and if user says No, will return False. // If object (and descendents) is deleted successfully, will return True. // This will tell all views about deletion, remove object from doc's index, // remove object from parent's child list, and set document modified flag. // You can tell it to not set document modified flag, and to not update views. BOOL BObject::DeleteObject(BOOL bSetModifiedFlag /* = TRUE */, BOOL bUpdateViews /* = TRUE */) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); // Check children recursively also // Note: We do this first so that children are deleted before their parents (important!) if (m_paChildren) { ASSERT_VALID(m_paChildren); while (m_paChildren->GetSize() > 0) { BObject* pobjChild = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(0)); ASSERT_VALID(pobjChild); // Attempt to delete child - if failed, return False if (!pobjChild->DeleteObject()) return FALSE; } } // Check for links to <this> bobject recursively through entire document BObjects aReferences; int nLinks = m_pDoc->GetReferences(this, aReferences); if (nLinks) { // Get object's class name (lowercase) CString strClassName = GetPropertyString(propClassName); strClassName.MakeLower(); // Ask the user if they want to remove all references to the object and delete it CString strMsg; strMsg.Format(_T("The %s \"%s\" is referenced by the following object(s): %s. " "Do you want to remove all references to the object and then delete it?"), (LPCTSTR) strClassName, (LPCTSTR) GetPropertyString(propName), (LPCTSTR) aReferences.GetText() ); if (IDYES == AfxMessageBox(strMsg, MB_ICONQUESTION | MB_YESNO)) { // If we're deleting a class, we'll want to replace all references with classPaper. BObject* pobjNew = 0; // default is to just remove all references if (m_lngClassID == classClass) pobjNew = m_pDoc->GetObject(classPaper); // Remove/replace all references recursively and return true. m_pDoc->GetRoot()->ReplaceReferences(this, pobjNew); } else // Did not delete object - return False return FALSE; } // Now we're clear to delete <this> bobject.. // Tell all views about deletion. // Note: Need to do this BEFORE actually deleting the objects so view code can utilize object props, etc. // Note: If we deleted the current object, this is where treeview will remove item and select the next item. // if (bUpdateViews) { // CHint objHint; // BObjects aObjects; // aObjects.Add(this); // objHint.m_paObjects = &aObjects; // m_pDoc->UpdateAllViewsEx(NULL, hintDelete, &objHint); // } // Remove the object from the Index m_pDoc->RemoveObjectFromIndex(m_lngObjectID); // Remove the object from its parent's children collection and set parent to NULL. // Note: We only need to do this for the top level objects we are deleting - // we don't care about any children or grandchildren lists of those objects. // Also, it screws things up because you wind up removing items from the array // that you are currently walking through. ASSERT_VALID(m_pobjParent); m_pobjParent->RemoveChild(this); // Set document flag if (bSetModifiedFlag) m_pDoc->SetModifiedFlag(); // Tell all views about deletion. if (bUpdateViews) { CHint objHint; BObjects aObjects; aObjects.Add(this); objHint.paObjects = &aObjects; m_pDoc->UpdateAllViewsEx(NULL, hintDelete, &objHint); } // Now delete the actual BObject // Note: Destructor recursively deletes children and properties and bdata. // Note: We only need to do this for the top level objects since this is recursive. delete this; return TRUE; } // Get pointer to the specified child, or 0 if invalid index. BObject* BObject::GetChild(int nChild) { ASSERT_VALID(this); ASSERT(nChild >= 0); if (m_paChildren) { ASSERT_VALID(m_paChildren); int nChildren = m_paChildren->GetSize(); if (nChild < nChildren) { BObject* pobjChild = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(nChild)); ASSERT_VALID(pobjChild); return pobjChild; } } return 0; } // Returns a pointer to the class object for this object BObject* BObject::GetClassObject() { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); BObject* pobjClass = m_pDoc->GetObject(m_lngClassID); ASSERT_VALID(pobjClass); return pobjClass; } //x /* BDataColumns& BObject::GetColumns() { ASSERT_VALID(this); BDataColumns* pdatColumns = DYNAMIC_DOWNCAST(BDataColumns, this->GetPropertyData(propColumnInfoArray)); ASSERT_VALID(pdatColumns); return *pdatColumns; } */ // Move this BObject to a new parent if possible. // This will handle removing from old parent list, adding to new parent list. // This will set document modified flag and update all views if specified. // See also SetParent (which should just be for initialization?) BOOL BObject::MoveTo(BObject *pobjNewParent, BOOL bSetModifiedFlag /* = TRUE */, BOOL bUpdateViews /* = TRUE */, BOOL bDisplayMessages /* = TRUE */) { ASSERT_VALID(this); ASSERT_VALID(pobjNewParent); ASSERT_VALID(m_pDoc); // Exit if moving onto current parent (ie no change) if (pobjNewParent == m_pobjParent) return FALSE; //. or true? // Check if move is valid // Displays message if not allowed to drop any of the objects on the target. // if (!IsMoveValid(pobjNewParent, TRUE)) if (!IsMoveValid(pobjNewParent, bDisplayMessages)) return FALSE; // Remove the object from its current parent's child collection and set parent to NULL. ASSERT_VALID(m_pobjParent); m_pobjParent->RemoveChild(this); // Add the object to the new parent's child collection. // Note: This will set the object's parent pointer also. pobjNewParent->AddChild(this, TRUE); // Make sure relationship is set correctly (parent is a two-way relationship) ASSERT(this->m_pobjParent == pobjNewParent); ASSERT(this->IsChildOf(pobjNewParent, FALSE)); // Set document modified if (bSetModifiedFlag) m_pDoc->SetModifiedFlag(); // Now tell all views about the move if (bUpdateViews) { // CHint h; // h.m_paObjects = &aObjects; // h.m_pobjObject = this; // h.m_pobjParent = pobjNewParent; // m_pDoc->UpdateAllViewsEx(NULL, hintMove, &h); m_pDoc->UpdateAllViewsEx(NULL, hintMoveObject, this); } return TRUE; } // Check if this object can be moved onto the specified target. // Displays a message and returns false if move is invalid. BOOL BObject::IsMoveValid(BObject *pobjTarget, BOOL bDisplayMessages) { ASSERT_VALID(this); ASSERT_VALID(pobjTarget); int nError = 0; // Make sure an item is not being dropped onto itself if (this == pobjTarget) nError = IDS_ERROR_MOVE_SELF; // Make sure an item is not being dropped onto its parent if (m_pobjParent == pobjTarget) nError = IDS_ERROR_MOVE_PARENT; // Make sure an item is not being dropped onto a descendent if (pobjTarget->IsChild(this)) nError = IDS_ERROR_MOVE_CHILD; // Display message if rule broken and return False if (nError) { if (bDisplayMessages) AfxMessageBox(nError, MB_OK | MB_ICONEXCLAMATION); return FALSE; } // Move is valid return TRUE; } // Add the specified property to this classdef's list of associated properties, checking // first if the property is already included in the class chain. // Returns True if successful. //, This function is not finished - doesn't look up the class chain etc. BOOL BObject::ClassDefAddProperty(OBJID lngPropertyID) { ASSERT_VALID(this); //, First see if the property is associated with any parent classes - if so we don't need to add it to // the object's classdef. // CObArray aProps; // int nProps = GetPropertyDefs(aProps, TRUE, TRUE); //,, temporary - just hardcode the inherited props for now - simpler and faster at the moment. switch (lngPropertyID) { case propName: case propClassName: case propDescription: return TRUE; } // Note: Add will not add duplicate objects SetPropertyLinksAdd(propObjectProperties, lngPropertyID); //x /* // duplicate code in 3 places // Note: pdat might be zero if class has no properties assigned to it // Note: AddLinkID will not add duplicate objects (just returns -1 if already there) BDataLink* pdatLinks = DYNAMIC_DOWNCAST(BDataLink, GetPropertyData(propObjectProperties)); if (pdatLinks) { ASSERT_VALID(pdatLinks); pdatLinks->AddLinkID(lngPropertyID, m_pDoc); } else { // No bdata yet - create a new one and store it with the class def pdatLinks = new BDataLink; pdatLinks->SetMultiple(); pdatLinks->AddLinkID(lngPropertyID, m_pDoc); } SetPropertyData(propObjectProperties, pdatLinks); delete pdatLinks; */ return TRUE; } // Get the name for this object, optionally including its class name // eg: book "The Lord of the Rings" //, trim to reasonable # chars, add ... if necess //, why does this use m_strTextCache? slows it down. eg can't use it to replace GetPropertyString(propName) LPCTSTR BObject::GetName(BOOL bIncludeClassName) { ASSERT_VALID(this); // ASSERT(bIncludeClassName); //, for now if (bIncludeClassName) { CString strClassName = GetPropertyString(propClassName); strClassName.MakeLower(); m_strTextCache.Format("%s \"%s\"", // (LPCTSTR) GetPropertyString(propClassName), (LPCTSTR) strClassName, (LPCTSTR) GetPropertyString(propName) ); } else { m_strTextCache.Format("%s", (LPCTSTR) GetPropertyString(propName) ); } return m_strTextCache; } // Add rich text to the specified property. // Used in drag/drop of text to different items and Move Text To... command. // This will set the document modified flag. // Note: This uses the app's hidden rtf control, because the target rtf is not necessarily // visible in the main rtf control. //, could pass a param for position to insert at (beginning, end, stored insertion point) BOOL BObject::AddRtf(OBJID lngPropertyID, CString& strRtf) { ASSERT_VALID(this); // Get text (rtf) of target object. CString strOldText = GetPropertyString(lngPropertyID); // Add existing text (rtf) to the dummy rtf control. app.m_rtf.SetRtf(strOldText); //traceString("%s\n", pszOldText); //traceToFile("_1.rtf", pszOldText); // Select the last character. long nChars = app.m_rtf.GetTextLength(); app.m_rtf.SetSel(nChars, nChars + 1); // bug: if nchars was 0 was leaving default system font at very end. fixed by using nchars+1 for end of range. // Replace the selection with the new selection. app.m_rtf.SetRtf((LPCTSTR) strRtf, TRUE); // Get the new text (rtf) //, GetRtfConst()? CString strNewText = app.m_rtf.GetRtf(FALSE); //traceString("%s\n", (LPCTSTR) strNewText); //traceToFile("_2.rtf", (LPCTSTR) strNewText); // Assign new text (rtf) back to object. // Set doc modified flag and tell all views. SetPropertyString(lngPropertyID, (LPCTSTR) strNewText, TRUE, TRUE); // Clear rtf contents to save memory. app.m_rtf.SetWindowText(""); return TRUE; } // Convert all subproperties to soft links (ie ObjectIDs) void BObject::ConvertToSoftLinks(BOOL bRecurse) { ASSERT_VALID(this); // Walk through all properties and convert to soft links if (m_paProperties) { ASSERT_VALID(m_paProperties); int nProps = m_paProperties->GetSize(); for (int i = 0; i < nProps; i++) { BObject* pobjProp = DYNAMIC_DOWNCAST(BObject, m_paProperties->GetAt(i)); ASSERT_VALID(pobjProp); BData* pdat = pobjProp->GetData(); if (pdat) { OBJID lngPropertyID = pobjProp->GetClassID(); TRACE("converting %s.[%d] to soft links\n", (LPCTSTR) this->GetName(TRUE), lngPropertyID); pdat->ConvertToSoftLinks(); } } } // Recurse through all child objects also, if specified if (bRecurse) { if (m_paChildren) { int nItems = m_paChildren->GetSize(); for (int i = 0; i < nItems; i++) { BObject* pobj = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(i)); ASSERT_VALID(pobj); pobj->ConvertToSoftLinks(bRecurse); } } } } // Convert all subproperties from soft to hard links void BObject::ConvertToHardLinks(BOOL bRecurse) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); BDoc* pDoc = this->GetDoc(); // Walk through all properties and convert to hard links. // Note: Some properties may already be hard links. if (m_paProperties) { ASSERT_VALID(m_paProperties); int nProps = m_paProperties->GetSize(); for (int i = 0; i < nProps; i++) { BObject* pobjProp = DYNAMIC_DOWNCAST(BObject, m_paProperties->GetAt(i)); ASSERT_VALID(pobjProp); BData* pdat = pobjProp->GetData(); if (pdat) { OBJID lngPropertyID = pobjProp->GetClassID(); //trace("converting %s.[%d] to hard links\n", (LPCTSTR) this->GetName(TRUE), lngPropertyID); pdat->ConvertToHardLinks(pDoc); } } } // Recurse through all child objects also, if specified if (bRecurse) { if (m_paChildren) { int nItems = m_paChildren->GetSize(); for (int i = 0; i < nItems; i++) { BObject* pobj = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(i)); ASSERT_VALID(pobj); pobj->ConvertToHardLinks(bRecurse); } } } } // Copy the bdata object associated with the specified BObject and property value, if there. // Also returns a pointer to the new bdata object, or 0 if none. void BObject::CopyPropertyDataFrom(BObject *pobjSource, OBJID lngPropertyID) { ASSERT_VALID(this); BData* pdat = pobjSource->GetPropertyData(lngPropertyID); if (pdat) { this->SetPropertyData(lngPropertyID, pdat, FALSE, FALSE); delete pdat; } // else // If bdata can't be found, make sure it doesn't exist in this bobject as well! // bug: forgot to include this step! this->DeleteProperty(lngPropertyID, FALSE, FALSE); } // Copy a BObject's contents onto this one. void BObject::CopyFrom(BObject* pobjSource) { ASSERT_VALID(this); ASSERT_VALID(m_pDoc); ASSERT_VALID(pobjSource); AfxMessageBox("copyfrom!"); //x // Copy properties this->m_lngFlags = pobjSource->GetFlags(); this->m_lngIconID = pobjSource->m_lngIconID; // leave as direct ref this->m_bytViewHeight = pobjSource->m_bytViewHeight; this->m_lngClassID = pobjSource->GetClassID(); this->SetObjectID(pobjSource->GetObjectID()); // Leave this->pDoc as is // Find the parent of the source object and get its ID. // Parent is essentially a link property - so can treat as a soft link also. // This will make sure if we're copying from one document to another that // the parent will be set properly. //. Note: Assumes that the parent already exists, ie that synchronization is // done in top down recursive order BObject* pobjSourceParent = pobjSource->GetParent(); ASSERT_VALID(pobjSourceParent); OBJID nSourceParentID = pobjSourceParent->GetObjectID(); // Lookup the parent object in THIS document, and make this bobject a child. // This will handle moving the object if its parent has changed for some reason // (ie remove from old parent list, add to new parent list). // Use setparent instead of moveto because moveto assumes that the object already has a valid parent. BObject* pobjThisParent = m_pDoc->GetObjectNull(nSourceParentID); // this->MoveTo(pobjThisParent, TRUE, TRUE, FALSE); this->SetParent(pobjThisParent); // Copy BData (usually contains name of this BObject) if (pobjSource->GetData()) { this->SetData(pobjSource->GetData()->CreateCopy()); } // Delete all existing property subobjects in case this object has some that the new object doesn't. // Release property objects recursively (descructor recursively deletes property objects) if (this->m_paProperties) { delete this->m_paProperties; this->m_paProperties = 0; // Bug: Didn't have this here and some code used this to see if had props } // Copy all property bdata objects BObjects* pobjSourceProps = pobjSource->m_paProperties; if (pobjSourceProps) { ASSERT_VALID(pobjSourceProps); int nProps = pobjSourceProps->GetSize(); for (int i = 0; i < nProps; i++) { BObject* pobjSourceProp = DYNAMIC_DOWNCAST(BObject, pobjSourceProps->GetAt(i)); ASSERT_VALID(pobjSourceProp); OBJID lngPropertyID = pobjSourceProp->GetClassID(); BData* pdatSource = pobjSourceProp->GetData(); if (pdatSource) { ASSERT_VALID(pdatSource); BData* pdatCopy = pdatSource->CreateCopy(); this->SetPropertyData(lngPropertyID, pdatCopy, FALSE, FALSE); delete pdatCopy; } } } } // Set the parent for this object. // See also MoveTo, AddChild void BObject::SetParent(BObject *pobjNewParent) { ASSERT_VALID(this); ASSERT_VALID(pobjNewParent); ASSERT_VALID(m_pDoc); //, Exit if move is not valid // skip for now - bombs if setting to existing parent // if (!IsMoveValid(pobjNewParent, FALSE)) // { // ASSERT(0); // return; // } // Exit if moving onto current parent (ie no change) // if (pobjNewParent == m_pobjParent) // return FALSE; //. or true? // Remove the object from its current parent's child collection and set its parent to NULL. if (m_pobjParent) { ASSERT_VALID(m_pobjParent); m_pobjParent->RemoveChild(this); } // Add the object to the new parent's child collection // Note: This will set this object's parent pointer also // ie this->m_pobjParent = pobjNewParent; pobjNewParent->AddChild(this, TRUE); // Make sure relationship is set correctly (parent is a two-way relationship) ASSERT(this->m_pobjParent == pobjNewParent); ASSERT(this->IsChildOf(pobjNewParent, FALSE)); } void BObject::Export(CFileText &file, BOOL bRecurse, BDataLink& datProps) { ASSERT_VALID(this); ASSERT_VALID(&datProps); static int nIndent = 0; CString strIndent; strIndent.Format("%*s", nIndent * 2, ""); switch (file.m_nFormat) { case ffCsv: case ffTab: { // Walk through properties int nProps = datProps.GetLinkCount(); LPCTSTR psz = NULL; for (int i = 0; i < nProps; i++) { BObject* pobjProp = datProps.GetLinkAt(i); ASSERT_VALID(pobjProp); OBJID lngPropertyID = pobjProp->GetObjectID(); // CString str = this->GetPropertyString(lngPropertyID); // file.WriteValue(str); // will add quotes, etc BData* pdat = this->GetPropertyData(lngPropertyID); if (pdat) psz = pdat->GetBDataText(m_pDoc, lngPropertyID); else psz = ""; file.WriteValue(psz); // will add quotes, etc // output machine values of certain property types also if (pobjProp->PropertyDefHasMachineVersion()) { if (pdat) psz = pdat->GetBDataText(m_pDoc, lngPropertyID, TRUE); else psz = ""; file.WriteDelim(); file.WriteValue(psz); } // add delimiter if (i < nProps-1) { file.WriteDelim(); } delete pdat; } file.WriteNewline(); } break; case ffRtf: { CString str; // format // \s1\ql \outlinelevel0 str.Format("\\s%d\\ql \\outlinelevel%d ", nIndent+1, nIndent ); file.WriteString(str); // name str.Format("%s\r\n\\par \r\n\r\n", (LPCTSTR) this->GetName() ); file.WriteString(str); // contents CStringEx strText = this->GetPropertyString(propPlainText); strText.Trim(); if (!strText.IsEmpty()) { strText.Replace("\r\n","\r\n\\par "); str.Format("\\pard\\plain \\ql\r\n" "%s\r\n" "\\par\r\n\r\n", (LPCTSTR) strText ); file.WriteString(str); } } break; case ffText: { // no indentation CString str; str.Format("%s%s\r\n", // (LPCTSTR) strIndent, "", (LPCTSTR) this->GetName() ); file.WriteString(str); str.Format("%s%s\r\n", // (LPCTSTR) strIndent "", "-------------------------------------------------------" ); file.WriteString(str); str.Format("%s%s\r\n\r\n", // (LPCTSTR) strIndent, "", (LPCTSTR) this->GetPropertyString(propPlainText) ); file.WriteString(str); } break; case ffOpml: // eg <outline text="Heart of Glass.mp3" type="song" f="Blondie - Heart of Glass.mp3"> // <outline text=(rtf contents) /> { // yes these format statements must be separate because they use m_strTextCache! CString str; str.Format("%s<outline text=\"%s\" type=\"%s\">\r\n", (LPCTSTR) strIndent, (LPCTSTR) this->GetName(), (LPCTSTR) this->GetPropertyString(propClassName) ); file.WriteString(str); // get plain text, and convert all linefeeds to &#10; CStringEx strText = this->GetPropertyString(propPlainText); strText.Trim(); if (!strText.IsEmpty()) strText.Replace("\r\n","&#10;"); str.Format("%s <outline text=\"%s\"/>\r\n", (LPCTSTR) strIndent, (LPCTSTR) strText ); file.WriteString(str); } break; case ffXml: // eg <object id=15> // <type type_id=23>fish</type> // <name>plecy</name> { // yes these format statements must be separate because they use m_strTextCache! CString str; // no indent for xml - exporting flat list of objects // str.Format("%s<object id=\"%d\">\r\n", // (LPCTSTR) strIndent, // (LPCTSTR) this->GetObjectID() // ); str.Format(" <object id=\"%d\">\r\n", (LPCTSTR) this->GetObjectID() ); file.WriteString(str); /* // get plain text CStringEx strText = this->GetPropertyString(propPlainText); str.Format(" <text><![CDATA[%s]]></text>\r\n", (LPCTSTR) strText ); file.WriteString(str); */ // Walk through properties int nProps = datProps.GetLinkCount(); LPCTSTR pszValue = NULL; CStringEx strPropName; for (int i = 0; i < nProps; i++) { BObject* pobjProp = datProps.GetLinkAt(i); ASSERT_VALID(pobjProp); strPropName = pobjProp->GetName(); OBJID lngPropertyID = pobjProp->GetObjectID(); BData* pdat = this->GetPropertyData(lngPropertyID); if (pdat) { // proptype. // convert to valid element name. ie limit to a-z and underscore. strPropName.RemoveBadChars(); pszValue = pdat->GetBDataText(m_pDoc, lngPropertyID); str.Format(" <%s><![CDATA[%s]]></%s>\r\n", (LPCTSTR) strPropName, pszValue, (LPCTSTR) strPropName ); file.WriteString(str); // output machine values of certain property types also if (pobjProp->PropertyDefHasMachineVersion()) { strPropName = pobjProp->GetPropertyDefMachineVersionName(); strPropName.RemoveBadChars(); pszValue = pdat->GetBDataText(m_pDoc, lngPropertyID, TRUE); // get machine version str.Format(" <%s><![CDATA[%s]]></%s>\r\n", (LPCTSTR) strPropName, pszValue, (LPCTSTR) strPropName ); } delete pdat; } } str.Format(" </object>\r\n" ); file.WriteString(str); } break; } // Update progress bar app.GetProgressBar().StepIt(); nIndent++; // Now walk through children and call this routine recursively if (bRecurse && m_paChildren) { ASSERT_VALID(m_paChildren); int nChildren = m_paChildren->GetSize(); for (int i = 0; i < nChildren; i++) { BObject* pobjChild = DYNAMIC_DOWNCAST(BObject, m_paChildren->GetAt(i)); ASSERT_VALID(pobjChild); // pobjChild->Export(file, bRecurse, pobjProps); pobjChild->Export(file, bRecurse, datProps); } } nIndent--; // write object footer, if any switch (file.m_nFormat) { case ffOpml: { CString str; str.Format("%s</outline>\r\n", (LPCTSTR) strIndent ); file.WriteString(str); } break; /* case ffXml: { CString str; str.Format(" </object>\r\n" ); file.WriteString(str); } break;*/ } } // return true if this property def stores both human and machine-readable info. // used by export, so can know to export the machine-readable version as well. BOOL BObject::PropertyDefHasMachineVersion() { ASSERT_VALID(this); ASSERT(m_lngClassID == classProperty); OBJID idPropType = GetPropertyLink(propPropertyType); switch (idPropType) { case proptypeLink: case proptypeDate: case proptypeCurrency: return TRUE; break; } return FALSE; } CString BObject::GetPropertyDefMachineVersionName() { // get property def name, add "ID" or "_value" // eg "ClassID", "ParentID" switch (this->GetObjectID()) { case propClassID: return _T("ClassID"); case propParentName: return _T("ParentID"); } // else CString s = this->GetName(); s += _T("_value"); return s; }
28.042278
149
0.706141
[ "object" ]
4e4bcc9ae0b7bb81302ba7fe68f37ce635cdbc41
196
cpp
C++
Leetcode/1000-2000/1217. Play with Chips/1217.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/1000-2000/1217. Play with Chips/1217.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/1000-2000/1217. Play with Chips/1217.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
class Solution { public: int minCostToMoveChips(vector<int>& chips) { vector<int> count(2); for (int chip : chips) ++count[chip % 2]; return min(count[0], count[1]); } };
16.333333
46
0.586735
[ "vector" ]
4e4d9ff3347ae01b0fadaffc4b575560548c550e
28,575
cpp
C++
tvm/src/detection/detector.cpp
yongtaoge/RetinaFace.PyTorch
343866ea6b5641b307a4eec804bddc99c2f68847
[ "MIT" ]
83
2019-07-21T16:45:23.000Z
2020-09-11T07:29:17.000Z
tvm/src/detection/detector.cpp
YongtaoGe/RetinaFace.PyTorch
343866ea6b5641b307a4eec804bddc99c2f68847
[ "MIT" ]
4
2019-07-23T06:35:44.000Z
2019-08-24T07:05:59.000Z
tvm/src/detection/detector.cpp
YongtaoGe/RetinaFace.PyTorch
343866ea6b5641b307a4eec804bddc99c2f68847
[ "MIT" ]
18
2019-07-22T13:57:03.000Z
2020-06-19T06:13:16.000Z
// // Created by geyongtao on 2019-07-07. // #include "../../include/detection/detector.hpp" #include "../../include/detection/anchor_generator.hpp" //#include "net.h" //#include "benchmark.h" //#include "quantize.h" //#include "sn_depthwise_ssd_quantized_no_relu.id.h" #ifdef ANDROID #include<android/log.h> #define TAG "face" // 这个是自定义的LOG的标识 #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__) // 定义LOGD类型 #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__) // 定义LOGI类型 #define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__) // 定义LOGW类型 #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__) // 定义LOGE类型 #define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__) // 定义LOGF类型 #endif SSDDetector::SSDDetector(const int gpuid, const int src_width, const int src_height) : src_height_(src_height), src_width_(src_width) { img_num_ = 1; // resize_scale_width_ = 0.333333;//0.6;// 0.45; //resize the orignal pic to feed cnn // resize_scale_height_ = 0.333333; classes_.push_back("__background__"); classes_.push_back("face"); conf_thresh_ = 0.8; nms_thresh_ = 0.25; max_roi_before_nms_ = 400; channel_ = 3; // height_ = round(src_height_ * resize_scale_height_); // width_ = round(src_width_ * resize_scale_width_); class_num_ = classes_.size(); result_boxes_.resize(img_num_); result_landmarks_.resize(img_num_); keep_inds_.resize(img_num_); } void SSDDetector::set_resize_scale(const float resize_scale_width, const float resize_scale_height) { resize_scale_width_ = resize_scale_width; resize_scale_height_ = resize_scale_height; height_ = round(src_height_ * resize_scale_height_); width_ = round(src_width_ * resize_scale_width_); } void SSDDetector::set_resize(const float resized_width, const float resized_height) { resize_scale_width_ = resized_width/src_width_; resize_scale_height_ = resized_height/src_height_; height_ = round(src_height_ * resize_scale_height_); width_ = round(src_width_ * resize_scale_width_); } // subtract mean and to chw void SSDDetector::prepare_input_blob(const vector<cv::Mat> &imgs) { // Reshape 图片 blob vector<int> data_shape(4); data_shape[0] = img_num_; data_shape[1] = channel_; data_shape[2] = height_; data_shape[3] = width_; data_blob_ = std::make_shared<snr::Tensor>(data_shape); unsigned long time_0, time_1; float *dest = data_blob_->mutable_cpu_data(); for (int i = 0; i < imgs.size(); i++) { //Using OpenCV pre-precess API cv::Mat src = imgs[i]; cv::Mat img_float; double start = get_current_time(); //cv::Scalar pixel_mean(102.9801, 115.9465, 122.7717); // cv::Scalar pixel_mean(128.0f, 128.0f, 128.0f); cv::Scalar pixel_mean(104.0f, 117.0f, 123.0f); if (src.channels() == 3) src.convertTo(img_float, CV_32FC3); else src.convertTo(img_float, CV_32FC1); double end = get_current_time(); std::cout << "ConvertTo32F cost: " << (end - start) << " ms" << std::endl; start = get_current_time(); cv::Mat mean_mask = cv::Mat(img_float.rows, img_float.cols, CV_32FC3, pixel_mean); cv::Mat img_normalized; cv::subtract(img_float, mean_mask, img_normalized); end = get_current_time(); std::cout << "Normaliz cost: " << (end - start) << " ms" << std::endl; start = get_current_time(); std::cout<<"prepare data blob"<<std::endl; std::cout<<"resize_scale_width_: "<<resize_scale_width_<<std::endl; std::cout<<"resize_scale_height_: "<<resize_scale_height_<<std::endl; if(width_!=img_normalized.cols||height_!=img_normalized.rows) cv::resize(img_normalized, img_normalized, cv::Size(width_, height_), cv::INTER_LINEAR); // cv::resize(img_normalized, img_normalized, cv::Size(), resize_scale_width_, resize_scale_height_, cv::INTER_LINEAR); end = get_current_time(); // cout << "img_normalized: "<< img_normalized << endl; // cout << "img_normalized (python) = " << endl << format(img_normalized, Formatter::FMT_PYTHON) << endl << endl; // cout << "img_normalized row: 0~2 = "<< endl << " " << img_normalized.rowRange(0, 2) << endl << endl; std::cout << "Resize cost: " << (end - start) << " ms" << std::endl; std::cout << img_normalized.size() << std::endl; cout<<"height_: "<<height_<<endl; cout<<"width_: "<<width_<<endl; start = get_current_time(); for (int h = 0; h < height_; ++h) { const float *ptr = img_normalized.ptr<float>(h); int img_index = 0; for (int w = 0; w < width_; ++w) { for (int c = 0; c < channel_; ++c) { dest[(c * height_ + h) * width_ + w] = static_cast<float>(ptr[img_index++]); } } } dest += (data_blob_->Shape()[1] * data_blob_->Shape()[2] * data_blob_->Shape()[3]); end = get_current_time(); std::cout << "Data copy cost: " << (end - start) << " ms" << std::endl; } } void SSDDetector::generate_anchors(){ rois_blob_shape_.resize(2); rois_blob_shape_[0] = 4; // 根据要检测的 blob 名称获取 blob, 计算最终生成的 anchor blob 的大小 feat_blob_num_ = feat_blob_names_.size(); vector<SSDAnchorGenerator> ssd_anchor_generators(feat_blob_num_); rois_blob_shape_[1] = 0; for (int i = 0; i < feat_blob_num_; i++) { // 根据要检测的 blob 名称获取 blob // std::shared_ptr<Tensor> feat_tensor = outputs[i]; ssd_anchor_generators[i].set(height_, width_, ratio_fix_heights_[i], feat_strides_[i], base_sizes_[i], base_scales_[i]); vector<float> &scales = scales_[i]; for (int j = 0; j < scales.size(); j++) { ssd_anchor_generators[i].add_scale(scales[j]); } vector<float> &ratios = ratios_[i]; for (int j = 0; j < ratios.size(); j++) { ssd_anchor_generators[i].add_ratio(ratios[j]); } // 生成 anchor cout << "generating anchor for " << feat_blob_names_[i] << endl; ssd_anchor_generators[i].generate_anchor();//产生的结果在 result_blob_ cout << "generating anchor for " << feat_blob_names_[i] << " sussessfully!" << endl; // 累加计算最终的 anchor blob 的大小 rois_blob_shape_[1] += ssd_anchor_generators[i].get_result_blob()->Shape()[1]; } // 分配 rois_blob_ 的空间 rois_blob_ = std::make_shared<Tensor>(rois_blob_shape_); // 初始化最终的 anchor blob float *anchor_blob_data = rois_blob_->mutable_cpu_data(); for (int i = 0; i < feat_blob_num_; i++) { std::shared_ptr<Tensor> sdk_anchor_tensor = ssd_anchor_generators[i].get_result_blob(); const float *ssd_anchor_data = sdk_anchor_tensor->cpu_data(); const int count = sdk_anchor_tensor->Shape()[1];//每个点anchor数量*featmap_size // 按照 channel 复制数据 for (int j = 0; j < rois_blob_shape_[0]; j++) { memcpy(anchor_blob_data + j * rois_blob_shape_[1], ssd_anchor_data + j * count, count * sizeof(float)); } // if (i==0) // { // for (int i=0;i<12;i++){ // cout<<"ssd_anchor_data: "<<ssd_anchor_data[i]<<endl; // cout<<"anchor_blob_data: "<<anchor_blob_data[i]<<endl; // cout<<"roi blob: "<<rois_blob_->mutable_cpu_data()[i]<<endl; // } // // } anchor_blob_data += count; } std::cout<<"rois_blob_shape_[0]: "<<rois_blob_shape_[0]<<std::endl; std::cout<<"rois_blob_shape_[1]: "<<rois_blob_shape_[1]<<std::endl; } void SSDDetector::add_detect_blob( const string &feat_blob_name_, const bool ratio_fix_height, const int feat_stride, const float base_size, const float base_scale, const vector<float> &scales, const vector<float> &ratios) { feat_blob_names_.push_back(feat_blob_name_); ratio_fix_heights_.push_back(ratio_fix_height); feat_strides_.push_back(feat_stride); base_sizes_.push_back(base_size); base_scales_.push_back(base_scale); scales_.push_back(scales); ratios_.push_back(ratios); } void Mat_to_CHW(float *data, cv::Mat &frame) { assert(data && !frame.empty()); unsigned int volChl = 128 * 128; for(int c = 0; c < 3; ++c) { for (unsigned j = 0; j < volChl; ++j) data[c*volChl + j] = static_cast<float>(float(frame.data[j * 3 + c]) / 255.0); } } void SSDDetector::im_detect(const std::string &lib_path, const std::string &graph_path, const std::string &param_path, const std::string &image_path, vector<vector<Rect> > &boxes, vector<vector<float> > &scores, vector<vector<Point2f> > &ldmks) { // tvm module for compiled functions tvm::runtime::Module mod_syslib = tvm::runtime::Module::LoadFromFile(lib_path); // json graph std::ifstream json_in(graph_path, std::ios::in); std::string json_data((std::istreambuf_iterator<char>(json_in)), std::istreambuf_iterator<char>()); json_in.close(); // parameters in binary std::ifstream params_in(param_path, std::ios::binary); std::string params_data((std::istreambuf_iterator<char>(params_in)), std::istreambuf_iterator<char>()); params_in.close(); // parameters need to be TVMByteArray type to indicate the binary data TVMByteArray params_arr; params_arr.data = params_data.c_str(); params_arr.size = params_data.length(); int dtype_code = kDLFloat; int dtype_bits = 32; int dtype_lanes = 1; int device_type = kDLCPU; int device_id = 0; // get global function module for graph runtime tvm::runtime::Module mod = (*tvm::runtime::Registry::Get("tvm.graph_runtime.create"))(json_data, mod_syslib, device_type, device_id); const int N = 1; const int C = 3; const int H = height_; const int W = width_; DLTensor* x; int in_ndim = 4; //int64_t in_shape[4] = {1, 3, 224, 224}; int64_t in_shape[4] = {N, C, H, W}; TVMArrayAlloc(in_shape, in_ndim, dtype_code, dtype_bits, dtype_lanes, device_type, device_id, &x); // load image data saved in binary // std::ifstream data_fin(image_path, std::ios::binary); // data_fin.read(static_cast<char*>(x->data), C * H * W * sizeof(float)); // cv::Mat image, frame, input; // image = cv::imread(image_path); // cv::cvtColor(image, frame, cv::COLOR_BGR2RGB); // cv::resize(frame, input, cv::Size(640,640)); // float data[640 * 640 * 3]; // // 在这个函数中 将OpenCV中的图像数据转化为CHW的形式 // Mat_to_CHW(data, input); //有问题 prepare_data // // x为之前的张量类型 data为之前开辟的浮点型空间 // memcpy(x->data, &data, 3 * 640 * 640 * sizeof(float)); cv::Mat image; std::vector<cv::Mat> img_vector; image = cv::imread(image_path); img_vector.push_back(image); src_height_ = image.rows; src_width_ = image.cols; // resize_scale_width_=640; // resize_scale_height_=640; prepare_input_blob(img_vector); memcpy(x->data, data_blob_->mutable_cpu_data(), 3 * height_ * width_ * sizeof(float)); // get the function from the module(set input data) tvm::runtime::PackedFunc set_input = mod.GetFunction("set_input"); set_input("0", x); // get the function from the module(load patameters) tvm::runtime::PackedFunc load_params = mod.GetFunction("load_params"); load_params(params_arr); // get the function from the module(run it) tvm::runtime::PackedFunc run = mod.GetFunction("run"); run(); DLTensor* loc_out; int loc_out_ndim = 2; int64_t loc_out_shape[2] = {4, rois_blob_shape_[1]}; TVMArrayAlloc(loc_out_shape, loc_out_ndim, dtype_code, dtype_bits, dtype_lanes, device_type, device_id, &loc_out); DLTensor* cls_out; int cls_out_ndim = 2; int64_t cls_out_shape[2] = {2, rois_blob_shape_[1]}; TVMArrayAlloc(cls_out_shape, cls_out_ndim, dtype_code, dtype_bits, dtype_lanes, device_type, device_id, &cls_out); DLTensor* ldmk_out; int ldmk_out_ndim = 2; int64_t ldmk_out_shape[2] = {10, rois_blob_shape_[1]}; TVMArrayAlloc(ldmk_out_shape, ldmk_out_ndim, dtype_code, dtype_bits, dtype_lanes, device_type, device_id, &ldmk_out); // get the function from the module(get output data) tvm::runtime::PackedFunc get_output = mod.GetFunction("get_output"); double start = get_current_time(); get_output(0, loc_out); get_output(1, cls_out); get_output(2, ldmk_out); double end = get_current_time(); std::cout << "Inference cost: " << (end - start) << " ms" << std::endl; // get the maximum position in output vector // auto y_iter = static_cast<float*>(loc_out->data); // auto max_iter = std::max_element(y_iter, y_iter + 1000); // auto max_index = std::distance(y_iter, max_iter); // std::cout << "The maximum position in output vector is: " << max_index << std::endl; // std::cout << loc_out; // 将输出的信息打印出来 // auto input_tvm = static_cast<float*>(x->data); // for (int i = 0; i < 24; i++) // std::cout<<input_tvm[i]<<std::endl; // auto result = static_cast<float*>(ldmk_out->data); vector<int> cls_out_dim(2); cls_out_dim[0] = 2; cls_out_dim[1] = rois_blob_shape_[1]; cls_prob_blob_ = std::make_shared<snr::Tensor>(cls_out_dim); vector<int> bbox_out_dim(2); bbox_out_dim[0] = 4; bbox_out_dim[1] = rois_blob_shape_[1]; bbox_pred_blob_= std::make_shared<snr::Tensor>(bbox_out_dim); vector<int> ldmk_out_dim(2); ldmk_out_dim[0] = 10; ldmk_out_dim[1] = rois_blob_shape_[1]; ldmk_pred_blob_= std::make_shared<snr::Tensor>(ldmk_out_dim); memcpy(cls_prob_blob_->mutable_cpu_data(), cls_out->data, rois_blob_shape_[1] * 2 * sizeof(float)); memcpy(bbox_pred_blob_->mutable_cpu_data(), loc_out->data, rois_blob_shape_[1] * 4 * sizeof(float)); memcpy(ldmk_pred_blob_->mutable_cpu_data(), ldmk_out->data, rois_blob_shape_[1] * 10 * sizeof(float)); // cls_prob_blob_ = outputs[2]; // bbox_pred_blob_ = outputs[3]; // // // // Reshape 图片 blob // vector<int> data_shape(4); // data_shape[0] = img_num_; // data_shape[1] = channel_; // data_shape[2] = height_; // data_shape[3] = width_; // data_blob_ = std::make_shared<snr::Tensor>(data_shape); // float *dest = data_blob_->mutable_cpu_data(); // std::cout<<(result[0]+result[25575])<<std::endl; // std::cout<<(result[1]+result[25576])<<std::endl; // std::cout<<(cls_prob_blob_->mutable_cpu_data()[0]+cls_prob_blob_->mutable_cpu_data()[25575])<<std::endl; // // std::cout<<"result[0]: "<<result[0]<<std::endl; // std::cout<<"result[25575]: "<<result[25575]<<std::endl; // std::cout<<"cls_prob_blob_: "<<cls_prob_blob_->mutable_cpu_data()[0]<<std::endl; // std::cout<<"cls_prob_blob_: "<<cls_prob_blob_->mutable_cpu_data()[25575]<<std::endl<<std::endl; // // std::cout<<"bbox_pred_blob_: "<<bbox_pred_blob_->mutable_cpu_data()[0]<<std::endl; // std::cout<<"bbox_pred_blob_: "<<bbox_pred_blob_->mutable_cpu_data()[25575]<<std::endl; // std::cout<<"bbox_pred_blob_: "<<bbox_pred_blob_->mutable_cpu_data()[51150]<<std::endl; // std::cout<<"bbox_pred_blob_: "<<bbox_pred_blob_->mutable_cpu_data()[76725]<<std::endl<<std::endl; // // std::cout<<"cls_prob_blob_: "<<cls_prob_blob_->mutable_cpu_data()[1]<<std::endl; // std::cout<<"cls_prob_blob_: "<<cls_prob_blob_->mutable_cpu_data()[25576]<<std::endl<<std::endl; // // std::cout<<"bbox_pred_blob_: "<<bbox_pred_blob_->mutable_cpu_data()[1]<<std::endl; // std::cout<<"bbox_pred_blob_: "<<bbox_pred_blob_->mutable_cpu_data()[25576]<<std::endl; // std::cout<<"bbox_pred_blob_: "<<bbox_pred_blob_->mutable_cpu_data()[51151]<<std::endl; // std::cout<<"bbox_pred_blob_: "<<bbox_pred_blob_->mutable_cpu_data()[76726]<<std::endl<<std::endl; // // std::cout<<"cls_prob_blob_: "<<cls_prob_blob_->mutable_cpu_data()[2]<<std::endl; // std::cout<<"cls_prob_blob_: "<<cls_prob_blob_->mutable_cpu_data()[25577]<<std::endl<<std::endl; // // std::cout<<"bbox_pred_blob_: "<<bbox_pred_blob_->mutable_cpu_data()[0]<<std::endl; // std::cout<<"bbox_pred_blob_: "<<bbox_pred_blob_->mutable_cpu_data()[25577]<<std::endl; // std::cout<<"bbox_pred_blob_: "<<bbox_pred_blob_->mutable_cpu_data()[51152]<<std::endl; // std::cout<<"bbox_pred_blob_: "<<bbox_pred_blob_->mutable_cpu_data()[76727]<<std::endl<<std::endl; // std::cout<<(result[4]+result[5])<<std::endl; // std::cout<<(result[6]+result[7])<<std::endl; TVMArrayFree(x); TVMArrayFree(loc_out); TVMArrayFree(cls_out); TVMArrayFree(ldmk_out); start = get_current_time(); parse_detect_result(); // 进行 NMS perform_nms(); // // 返回结果 boxes.resize(img_num_); scores.resize(img_num_); ldmks.resize(img_num_); for (int img_idx = 0; img_idx < img_num_; img_idx++) { // 获取结果框 vector<Box> &img_boxes = result_boxes_[img_idx]; vector<int> img_keep_inds = keep_inds_[img_idx]; // 获取关键点 vector<Landmark> &img_ldmks = result_landmarks_[img_idx]; // for (int i=0; i<img_keep_inds.size();i++){ // cout<<img_keep_inds.size()<<endl; // cout << "img_keep_inds: "<<img_keep_inds[i]<<endl; // // } const int img_box_num = img_keep_inds.size(); if (img_box_num == 0) continue; // 为返回结果分配空间 vector<Rect> &img_rects = boxes[img_idx]; vector<float> &img_scores = scores[img_idx]; vector<Point2f> &img_points = ldmks[img_idx]; img_rects.resize(img_box_num); img_scores.resize(img_box_num); img_points.resize(img_box_num * 5); // 获取每一个结果框 for (int i = 0; i < img_box_num; i++) { Box &box = img_boxes[img_keep_inds[i]]; Rect &rect = img_rects[i]; Landmark &ldmk_5point = img_ldmks[img_keep_inds[i]]; // 转化成 (xmin, ymin, w, h) 的形式 rect.x = box.region[0]; rect.y = box.region[1]; rect.width = box.region[2] - box.region[0] + 1; rect.height = box.region[3] - box.region[1] + 1; img_points[i*5].x = ldmk_5point.region[0]; img_points[i*5].y = ldmk_5point.region[1]; img_points[i*5+1].x = ldmk_5point.region[2]; img_points[i*5+1].y = ldmk_5point.region[3]; img_points[i*5+2].x = ldmk_5point.region[4]; img_points[i*5+2].y = ldmk_5point.region[5]; img_points[i*5+3].x = ldmk_5point.region[6]; img_points[i*5+3].y = ldmk_5point.region[7]; img_points[i*5+4].x = ldmk_5point.region[8]; img_points[i*5+4].y = ldmk_5point.region[9]; img_scores[i] = box.score; } } end = get_current_time(); std::cout << "Result cost: " << (end - start) << " ms" << std::endl; } void SSDDetector::parse_detect_result() { Box box; Landmark ldmk; float variances[2] = {0.1, 0.2}; const int roi_num = rois_blob_->Shape()[1]; //25575 // 初始化每个 channel 指针 vector<const float *> roi_datas(4), bbox_datas(4), cls_datas(class_num_), ldmk_datas(10); const float *cls_prob_data = cls_prob_blob_->cpu_data(); const float *bbox_pred_data = bbox_pred_blob_->cpu_data(); const float *ldmk_pred_data = ldmk_pred_blob_->cpu_data(); const float *rois_data = rois_blob_->cpu_data(); // 对于每一张图片 for (int img_idx = 0; img_idx < img_num_; img_idx++) { vector<Box> &img_boxes = result_boxes_[img_idx]; vector<Landmark> &img_landmarks = result_landmarks_[img_idx]; img_boxes.clear(); img_landmarks.clear(); // 所有图片共用同一个 roi blob roi_datas[0] = rois_data; //anchor 首地址 bbox_datas[0] = bbox_pred_data; // 4 的含义是 anchor 和 box 需要4维矩阵表示 for (int i = 1; i < 4; i++) { roi_datas[i] = roi_datas[i - 1] + roi_num; //anchor 首地址的 roi_num (25575) 个偏移 bbox_datas[i] = bbox_datas[i - 1] + roi_num; } // for (int i=0; i<100; i++){ // cout<<roi_datas[0][i]<<", "<<roi_datas[1][i]<<", "<<roi_datas[2][i]<<", "<<roi_datas[3][i]<<", "<<endl; // } // 获取分类得分指针 cls_datas[0] = cls_prob_data; for (int i = 1; i < class_num_; i++) { cls_datas[i] = cls_datas[i - 1] + roi_num; } // 获取关键点回归指针 ldmk_datas[0] = ldmk_pred_data; for (int i = 1; i < 10; i++) { ldmk_datas[i] = ldmk_datas[i - 1] + roi_num; } // 对于每一个 roi for (int roi_idx = 0; roi_idx < roi_num; roi_idx++) { // 获取 roi 并 归一化resize_scale_height_ = 0.333333; // const float xmin = std::min(std::max( // float(*(roi_datas[0]) / resize_scale_width_), float(0)), float(src_width_)); // const float ymin = std::min(std::max( // float(*(roi_datas[1]) / resize_scale_height_), float(0)), float(src_height_)); // const float xmax = std::min(std::max( // float(*(roi_datas[2]) / resize_scale_width_), float(0)), float(src_width_)); // const float ymax = std::min(std::max( // float(*(roi_datas[3]) / resize_scale_height_), float(0)), float(src_height_)); const float xmin = std::min(std::max( float(*(roi_datas[0]) / width_), float(0)), float(src_width_)); const float ymin = std::min(std::max( float(*(roi_datas[1]) / height_), float(0)), float(src_height_)); const float xmax = std::min(std::max( float(*(roi_datas[2]) / width_), float(0)), float(src_width_)); const float ymax = std::min(std::max( float(*(roi_datas[3]) / height_), float(0)), float(src_height_)); // 转化成 (x, y, w, h) 的形式 // // float width = xmax - xmin + 1; // float height = ymax - ymin + 1; // anchor [ctr_x, ctr_y, width, height] float width = xmax - xmin; float height = ymax - ymin; float ctr_x = xmin + 0.5 * width; float ctr_y = ymin + 0.5 * height; // 对于除了背景之外的每一个类别,获取对应的得分和回归后的框 for (int class_idx = 1; class_idx < class_num_; class_idx++) { // 获取得分 box.score = *(cls_datas[class_idx]); // 如果得分小于要求的置信度,则忽略这个 roi if (box.score < conf_thresh_) continue; // cout << box.score << endl; // cout << xmin << ", " << ymin << ", " << xmax << ", " << ymax << endl; // 获取类别标签 box.label = class_idx; // 对 roi 做回归 // cout << "anchor center: (" << ctr_x <<", "<< ctr_y <<") " << endl; // cout << "bbox_datas: " << bbox_datas[0][0] << endl; const float cls_ctr_x = ctr_x + *(bbox_datas[0]) * width * variances[0]; const float cls_ctr_y = ctr_y + *(bbox_datas[1]) * height* variances[0]; const float cls_width = width * exp(*(bbox_datas[2]) * variances[1]); const float cls_height = height * exp(*(bbox_datas[3]) * variances[1]); // 转化成 (xmin, ymin, xmax, ymax) 的形式 box.region[0] = std::max(cls_ctr_x - 0.5 * cls_width, 0.0); box.region[1] = std::max(cls_ctr_y - 0.5 * cls_height, 0.0); box.region[2] = std::min(static_cast<float>(cls_ctr_x + 0.5 * cls_width), src_width_); box.region[3] = std::min(static_cast<float>(cls_ctr_y + 0.5 * cls_height), src_height_); box.region[0] = box.region[0] * width_; box.region[1] = box.region[1] * height_; box.region[2] = box.region[2] * width_; box.region[3] = box.region[3] * height_; // 对关键点做回归 const float x1 = ctr_x + *(ldmk_datas[0]) * width * variances[0]; const float x2 = ctr_x + *(ldmk_datas[2]) * width * variances[0]; const float x3 = ctr_x + *(ldmk_datas[4]) * width * variances[0]; const float x4 = ctr_x + *(ldmk_datas[6]) * width * variances[0]; const float x5 = ctr_x + *(ldmk_datas[8]) * width * variances[0]; const float y1 = ctr_y + *(ldmk_datas[1]) * height * variances[0]; const float y2 = ctr_y + *(ldmk_datas[3]) * height * variances[0]; const float y3 = ctr_y + *(ldmk_datas[5]) * height * variances[0]; const float y4 = ctr_y + *(ldmk_datas[7]) * height * variances[0]; const float y5 = ctr_y + *(ldmk_datas[9]) * height * variances[0]; ldmk.region[0] = x1 * width_; ldmk.region[2] = x2 * width_; ldmk.region[4] = x3 * width_; ldmk.region[6] = x4 * width_; ldmk.region[8] = x5 * width_; ldmk.region[1] = y1 * height_; ldmk.region[3] = y2 * height_; ldmk.region[5] = y3 * height_; ldmk.region[7] = y4 * height_; ldmk.region[9] = y5 * height_; // cout<<"box region: "<<box.region[0] << ", " << box.region[1] << ", " << box.region[2] << ", " << box.region[3] << endl; // 如果是一个合法的框,那么就添加到临时结果数组里面 if (box.region[2] > box.region[0] && box.region[3] > box.region[1]) { img_boxes.push_back(box); img_landmarks.push_back(ldmk); } } // 将指针偏移到下一个 roi for (int i = 0; i < 4; i++) { roi_datas[i]++; bbox_datas[i]++; } for (int i = 1; i < class_num_; i++) { cls_datas[i]++; } for (int i = 0; i < 10; i++) { ldmk_datas[i]++; } } } } void SSDDetector::perform_nms() { // 对每一张图片做 NMS for (int img_idx = 0; img_idx < img_num_; img_idx++) { vector<int> &keep_inds = keep_inds_[img_idx]; keep_inds.clear(); vector<Box> &img_boxes = result_boxes_[img_idx]; int box_num = img_boxes.size(); if (box_num == 0) continue; // 用来排序的下标和 NMS 数组 vector<int> box_inds(box_num); for (int i = 0; i < box_num; i++) { box_inds[i] = i; } // 排序 sort(box_inds.begin(), box_inds.end(), by_box_score(img_boxes)); // 只保留指定的最大数量的框 if (box_num > max_roi_before_nms_) { box_num = max_roi_before_nms_; } // 计算每个 roi 的面积 vector<float> areas(box_num); for (int i = 0; i < box_num; i++) { areas[i] = img_boxes[i].get_area(); } // 做 NMS vector<bool> suppressed(box_num, false); for (int i = 0; i < box_num; i++) { const int src_box_idx = box_inds[i]; if (suppressed[i]) continue; keep_inds.push_back(src_box_idx); Box &src_box = img_boxes[src_box_idx]; for (int j = i + 1; j < box_num; j++) { const int dst_box_idx = box_inds[j]; if (suppressed[j]) continue; Box &dst_box = img_boxes[dst_box_idx]; // 如果不同 label 则不需要抑制 if (src_box.label != dst_box.label) continue; // 计算交集面积 const float x1 = std::max(src_box.region[0], dst_box.region[0]); const float y1 = std::max(src_box.region[1], dst_box.region[1]); const float x2 = std::min(src_box.region[2], dst_box.region[2]); const float y2 = std::min(src_box.region[3], dst_box.region[3]); // 如果 iou > nms_thresh_,则进行抑制 if (x2 > x1 && y2 > y1) { const float inter_area = (x2 - x1 + 1) * (y2 - y1 + 1); if (inter_area / (areas[src_box_idx] + areas[dst_box_idx] - inter_area) > nms_thresh_) { suppressed[j] = true; } } } } } }
38.355705
137
0.583272
[ "shape", "vector" ]
4e553e8c8c1f1ac512522378f1b94467c31e77bc
74,970
cpp
C++
automated-tests/src/dali-toolkit/utc-Dali-WebView.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
7
2016-11-18T10:26:51.000Z
2021-01-28T13:51:59.000Z
automated-tests/src/dali-toolkit/utc-Dali-WebView.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
13
2020-07-15T11:33:03.000Z
2021-04-09T21:29:23.000Z
automated-tests/src/dali-toolkit/utc-Dali-WebView.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
10
2019-05-17T07:15:09.000Z
2021-05-24T07:28:08.000Z
/* * Copyright (c) 2021 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 <iostream> #include <stdlib.h> #include <dali-toolkit-test-suite-utils.h> #include "dali-toolkit-test-utils/toolkit-timer.h" #include <dali.h> #include <dali/devel-api/adaptor-framework/web-engine-certificate.h> #include <dali/devel-api/adaptor-framework/web-engine-console-message.h> #include <dali/devel-api/adaptor-framework/web-engine-context-menu.h> #include <dali/devel-api/adaptor-framework/web-engine-context-menu-item.h> #include <dali/devel-api/adaptor-framework/web-engine-form-repost-decision.h> #include <dali/devel-api/adaptor-framework/web-engine-frame.h> #include <dali/devel-api/adaptor-framework/web-engine-hit-test.h> #include <dali/devel-api/adaptor-framework/web-engine-http-auth-handler.h> #include <dali/devel-api/adaptor-framework/web-engine-load-error.h> #include <dali/devel-api/adaptor-framework/web-engine-policy-decision.h> #include <dali/devel-api/adaptor-framework/web-engine-request-interceptor.h> #include <dali/devel-api/adaptor-framework/web-engine-context.h> #include <dali/devel-api/adaptor-framework/web-engine-security-origin.h> #include <dali/integration-api/events/hover-event-integ.h> #include <dali/integration-api/events/key-event-integ.h> #include <dali/integration-api/events/touch-event-integ.h> #include <dali/integration-api/events/wheel-event-integ.h> #include <dali/public-api/images/pixel-data.h> #include <dali-toolkit/public-api/controls/image-view/image-view.h> #include <dali-toolkit/public-api/focus-manager/keyboard-focus-manager.h> #include <dali-toolkit/devel-api/controls/web-view/web-back-forward-list.h> #include <dali-toolkit/devel-api/controls/web-view/web-context.h> #include <dali-toolkit/devel-api/controls/web-view/web-cookie-manager.h> #include <dali-toolkit/devel-api/controls/web-view/web-settings.h> #include <dali-toolkit/devel-api/controls/web-view/web-view.h> using namespace Dali; using namespace Toolkit; namespace { const char* const TEST_URL1( "http://www.somewhere.valid1.com" ); const char* const TEST_URL2( "http://www.somewhere.valid2.com" ); static int gPageLoadStartedCallbackCalled = 0; static int gPageLoadInProgressCallbackCalled = 0; static int gPageLoadFinishedCallbackCalled = 0; static int gPageLoadErrorCallbackCalled = 0; static std::unique_ptr<Dali::WebEngineLoadError> gPageLoadErrorInstance = nullptr; static int gScrollEdgeReachedCallbackCalled = 0; static int gUrlChangedCallbackCalled = 0; static int gEvaluateJavaScriptCallbackCalled = 0; static int gJavaScriptAlertCallbackCalled = 0; static int gJavaScriptConfirmCallbackCalled = 0; static int gJavaScriptPromptCallbackCalled = 0; static int gScreenshotCapturedCallbackCalled = 0; static int gVideoPlayingCallbackCalled = 0; static int gGeolocationPermissionCallbackCalled = 0; static bool gTouched = false; static bool gHovered = false; static bool gWheelEventHandled = false; static int gFormRepostDecidedCallbackCalled = 0; static std::unique_ptr<Dali::WebEngineFormRepostDecision> gFormRepostDecidedInstance = nullptr; static int gFrameRenderedCallbackCalled = 0; static int gConsoleMessageCallbackCalled = 0; static std::unique_ptr<Dali::WebEngineConsoleMessage> gConsoleMessageInstance = nullptr; static int gResponsePolicyDecidedCallbackCalled = 0; static std::unique_ptr<Dali::WebEnginePolicyDecision> gResponsePolicyDecisionInstance = nullptr; static int gCertificateConfirmCallbackCalled = 0; static std::unique_ptr<Dali::WebEngineCertificate> gCertificateConfirmInstance = nullptr; static int gSslCertificateChangedCallbackCalled = 0; static std::unique_ptr<Dali::WebEngineCertificate> gSslCertificateInstance = nullptr; static int gHttpAuthHandlerCallbackCalled = 0; static std::unique_ptr<Dali::WebEngineHttpAuthHandler> gHttpAuthInstance = nullptr; static int gSecurityOriginsAcquiredCallbackCalled = 0; static int gStorageUsageAcquiredCallbackCalled = 0; static int gFormPasswordsAcquiredCallbackCalled = 0; static int gDownloadStartedCallbackCalled = 0; static int gMimeOverriddenCallbackCalled = 0; static int gRequestInterceptedCallbackCalled = 0; static Dali::WebEngineRequestInterceptorPtr gRequestInterceptorInstance = nullptr; static std::vector<std::unique_ptr<Dali::WebEngineSecurityOrigin>> gSecurityOriginList; static std::vector<std::unique_ptr<Dali::WebEngineContext::PasswordData>> gPasswordDataList; static int gContextMenuShownCallbackCalled = 0; static std::unique_ptr<Dali::WebEngineContextMenu> gContextMenuShownInstance = nullptr; static int gContextMenuHiddenCallbackCalled = 0; static std::unique_ptr<Dali::WebEngineContextMenu> gContextMenuHiddenInstance = nullptr; static int gHitTestCreatedCallbackCalled = 0; static int gCookieManagerChangsWatchCallbackCalled = 0; static int gPlainTextReceivedCallbackCalled = 0; struct CallbackFunctor { CallbackFunctor(bool* callbackFlag) : mCallbackFlag( callbackFlag ) { } void operator()() { *mCallbackFlag = true; } bool* mCallbackFlag; }; static void OnPageLoadStarted(const std::string& url) { gPageLoadStartedCallbackCalled++; } static void OnPageLoadInProgress(const std::string& url) { gPageLoadInProgressCallbackCalled++; } static void OnPageLoadFinished(const std::string& url) { gPageLoadFinishedCallbackCalled++; } static void OnScrollEdgeReached(Dali::WebEnginePlugin::ScrollEdge edge) { gScrollEdgeReachedCallbackCalled++; } static void OnResponsePolicyDecided(std::unique_ptr<Dali::WebEnginePolicyDecision> decision) { gResponsePolicyDecidedCallbackCalled++; gResponsePolicyDecisionInstance = std::move(decision); } static void OnUrlChanged(const std::string& url) { gUrlChangedCallbackCalled++; } static bool OnHitTestCreated(std::unique_ptr<Dali::WebEngineHitTest> test) { gHitTestCreatedCallbackCalled++; return true; } static bool OnPlainTextReceived(const std::string& plainText) { gPlainTextReceivedCallbackCalled++; return true; } static void OnPageLoadError(std::unique_ptr<Dali::WebEngineLoadError> error) { gPageLoadErrorCallbackCalled++; gPageLoadErrorInstance = std::move(error); } static void OnEvaluateJavaScript(const std::string& result) { gEvaluateJavaScriptCallbackCalled++; } static bool OnJavaScriptAlert(const std::string& result) { gJavaScriptAlertCallbackCalled++; return true; } static bool OnJavaScriptConfirm(const std::string& result) { gJavaScriptConfirmCallbackCalled++; return true; } static bool OnJavaScriptPrompt(const std::string& meesage1, const std::string& message2) { gJavaScriptPromptCallbackCalled++; return true; } static void OnScreenshotCaptured(Dali::Toolkit::ImageView) { gScreenshotCapturedCallbackCalled++; } static void OnVideoPlaying(bool isPlaying) { gVideoPlayingCallbackCalled++; } static bool OnGeolocationPermission(const std::string&, const std::string&) { gGeolocationPermissionCallbackCalled++; return true; } static bool OnTouched( Actor actor, const Dali::TouchEvent& touch ) { gTouched = true; return true; } static void OnChangesWatch() { gCookieManagerChangsWatchCallbackCalled++; } static bool OnHovered(Actor actor, const Dali::HoverEvent& hover) { gHovered = true; return true; } static bool OnWheelEvent(Actor actor, const Dali::WheelEvent& wheel) { gWheelEventHandled = true; return true; } static void OnFormRepostDecided(std::unique_ptr<Dali::WebEngineFormRepostDecision> decision) { gFormRepostDecidedCallbackCalled++; gFormRepostDecidedInstance = std::move(decision); } static void OnFrameRendered() { gFrameRenderedCallbackCalled++; } static void OnConsoleMessage(std::unique_ptr<Dali::WebEngineConsoleMessage> message) { gConsoleMessageCallbackCalled++; gConsoleMessageInstance = std::move(message); } static void OnCertificateConfirm(std::unique_ptr<Dali::WebEngineCertificate> certificate) { gCertificateConfirmCallbackCalled++; gCertificateConfirmInstance = std::move(certificate); } static void OnSslCertificateChanged(std::unique_ptr<Dali::WebEngineCertificate> certificate) { gSslCertificateChangedCallbackCalled++; gSslCertificateInstance = std::move(certificate); } static void OnHttpAuthHandler(std::unique_ptr<Dali::WebEngineHttpAuthHandler> hander) { gHttpAuthHandlerCallbackCalled++; gHttpAuthInstance = std::move(hander); } static void OnSecurityOriginsAcquired(std::vector<std::unique_ptr<Dali::WebEngineSecurityOrigin>>& origins) { gSecurityOriginsAcquiredCallbackCalled++; gSecurityOriginList.clear(); gSecurityOriginList.swap(origins); } static void OnStorageUsageAcquired(uint64_t usage) { gStorageUsageAcquiredCallbackCalled++; } static void OnFormPasswordsAcquired(std::vector<std::unique_ptr<Dali::WebEngineContext::PasswordData>>& passwords) { gFormPasswordsAcquiredCallbackCalled++; gPasswordDataList.clear(); gPasswordDataList.swap(passwords); } static void OnDownloadStarted(const std::string& url) { gDownloadStartedCallbackCalled++; } static bool OnMimeOverridden(const std::string&, const std::string&, std::string&) { gMimeOverriddenCallbackCalled++; return false; } static bool OnRequestIntercepted(Dali::WebEngineRequestInterceptorPtr interceptor) { gRequestInterceptedCallbackCalled++; gRequestInterceptorInstance = interceptor; return false; } static void OnContextMenuShown(std::unique_ptr<Dali::WebEngineContextMenu> menu) { gContextMenuShownCallbackCalled++; gContextMenuShownInstance = std::move(menu); } static void OnContextMenuHidden(std::unique_ptr<Dali::WebEngineContextMenu> menu) { gContextMenuHiddenCallbackCalled++; gContextMenuHiddenInstance = std::move(menu); } } // namespace void web_view_startup(void) { test_return_value = TET_UNDEF; } void web_view_cleanup(void) { test_return_value = TET_PASS; } int UtcDaliWebViewBasics(void) { ToolkitTestApplication application; // Copy and Assignment Test tet_infoline( "UtcDaliWebViewBasic Copy and Assignment Test" ); WebView view = WebView::New(); DALI_TEST_CHECK( view ); WebView copy( view ); DALI_TEST_CHECK( view == copy ); WebView assign; DALI_TEST_CHECK( !assign ); assign = copy; DALI_TEST_CHECK( assign == view ); // DownCast Test tet_infoline( "UtcDaliWebViewBasic DownCast Test" ); BaseHandle handle(view); WebView view2 = WebView::DownCast( handle ); DALI_TEST_CHECK( view ); DALI_TEST_CHECK( view2 ); DALI_TEST_CHECK( view == view2 ); // TypeRegistry Test tet_infoline( "UtcDaliWebViewBasic TypeRegistry Test" ); TypeRegistry typeRegistry = TypeRegistry::Get(); DALI_TEST_CHECK( typeRegistry ); TypeInfo typeInfo = typeRegistry.GetTypeInfo( "WebView" ); DALI_TEST_CHECK( typeInfo ); BaseHandle handle2 = typeInfo.CreateInstance(); DALI_TEST_CHECK( handle2 ); WebView view3 = WebView::DownCast( handle2 ); DALI_TEST_CHECK( view3 ); END_TEST; } int UtcDaliWebViewPageNavigation(void) { ToolkitTestApplication application; WebView view = WebView::New(); view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); application.GetScene().Add( view ); application.SendNotification(); application.Render(); DALI_TEST_CHECK( view ); view.RegisterPageLoadStartedCallback( &OnPageLoadStarted ); view.RegisterPageLoadInProgressCallback( &OnPageLoadInProgress ); view.RegisterPageLoadFinishedCallback( &OnPageLoadFinished ); view.RegisterUrlChangedCallback( &OnUrlChanged ); DALI_TEST_EQUALS( gPageLoadStartedCallbackCalled, 0, TEST_LOCATION ); DALI_TEST_EQUALS( gPageLoadInProgressCallbackCalled, 0, TEST_LOCATION ); DALI_TEST_EQUALS( gPageLoadFinishedCallbackCalled, 0, TEST_LOCATION ); DALI_TEST_EQUALS( gUrlChangedCallbackCalled, 0, TEST_LOCATION ); view.LoadUrl( TEST_URL1 ); view.GetNaturalSize(); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( view.CanGoBack(), false, TEST_LOCATION ); DALI_TEST_EQUALS( gPageLoadStartedCallbackCalled, 1, TEST_LOCATION ); DALI_TEST_EQUALS( gPageLoadInProgressCallbackCalled, 1, TEST_LOCATION ); DALI_TEST_EQUALS( gPageLoadFinishedCallbackCalled, 1, TEST_LOCATION ); DALI_TEST_EQUALS( gUrlChangedCallbackCalled, 1, TEST_LOCATION ); view.LoadUrl( TEST_URL2 ); view.Suspend(); view.SetProperty( Actor::Property::SIZE, Vector2( 400, 300 ) ); application.SendNotification(); application.Render(); Test::EmitGlobalTimerSignal(); view.Resume(); DALI_TEST_EQUALS( view.CanGoBack(), true, TEST_LOCATION ); DALI_TEST_EQUALS( view.CanGoForward(), false, TEST_LOCATION ); DALI_TEST_EQUALS( gPageLoadStartedCallbackCalled, 2, TEST_LOCATION ); DALI_TEST_EQUALS( gPageLoadInProgressCallbackCalled, 2, TEST_LOCATION ); DALI_TEST_EQUALS( gPageLoadFinishedCallbackCalled, 2, TEST_LOCATION ); DALI_TEST_EQUALS( gUrlChangedCallbackCalled, 2, TEST_LOCATION ); view.GoBack(); Test::EmitGlobalTimerSignal(); DALI_TEST_CHECK( !view.CanGoBack() ); DALI_TEST_CHECK( view.CanGoForward() ); view.GoForward(); Test::EmitGlobalTimerSignal(); DALI_TEST_CHECK( view.CanGoBack() ); DALI_TEST_CHECK( !view.CanGoForward() ); view.Reload(); view.StopLoading(); view.ClearHistory(); Test::EmitGlobalTimerSignal(); DALI_TEST_CHECK( !view.CanGoBack() ); DALI_TEST_CHECK( !view.CanGoForward() ); END_TEST; } int UtcDaliWebViewPageLoadErrorConsoleMessage(void) { ToolkitTestApplication application; WebView view = WebView::New(); view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); application.GetScene().Add( view ); application.SendNotification(); application.Render(); DALI_TEST_CHECK( view ); view.RegisterPageLoadErrorCallback( &OnPageLoadError ); view.RegisterConsoleMessageReceivedCallback( &OnConsoleMessage ); DALI_TEST_EQUALS( gPageLoadErrorCallbackCalled, 0, TEST_LOCATION ); DALI_TEST_EQUALS( gConsoleMessageCallbackCalled, 0, TEST_LOCATION ); view.LoadUrl( TEST_URL1 ); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gPageLoadErrorCallbackCalled, 1, TEST_LOCATION ); DALI_TEST_EQUALS( gConsoleMessageCallbackCalled, 1, TEST_LOCATION ); // error code. DALI_TEST_CHECK(gPageLoadErrorInstance); DALI_TEST_EQUALS(gPageLoadErrorInstance->GetUrl(), TEST_URL1, TEST_LOCATION); DALI_TEST_EQUALS(gPageLoadErrorInstance->GetCode(), Dali::WebEngineLoadError::ErrorCode::UNKNOWN, TEST_LOCATION); std::string testErrorDescription("This is an error."); DALI_TEST_EQUALS(gPageLoadErrorInstance->GetDescription(), testErrorDescription, TEST_LOCATION); DALI_TEST_EQUALS(gPageLoadErrorInstance->GetType(), Dali::WebEngineLoadError::ErrorType::NONE, TEST_LOCATION); // console message. DALI_TEST_CHECK(gConsoleMessageInstance); std::string testConsoleSource("source"); DALI_TEST_EQUALS(gConsoleMessageInstance->GetSource(), testConsoleSource, TEST_LOCATION); DALI_TEST_EQUALS(gConsoleMessageInstance->GetLine(), 10, TEST_LOCATION); DALI_TEST_EQUALS(gConsoleMessageInstance->GetSeverityLevel(), Dali::WebEngineConsoleMessage::SeverityLevel::EMPTY, TEST_LOCATION); std::string testConsoleText("This is a text."); DALI_TEST_EQUALS(gConsoleMessageInstance->GetText(), testConsoleText, TEST_LOCATION); // reset gPageLoadErrorInstance = nullptr; gConsoleMessageInstance = nullptr; END_TEST; } int UtcDaliWebViewTouchAndKeys(void) { ToolkitTestApplication application; WebView view = WebView::New(); view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); application.GetScene().Add( view ); application.SendNotification(); application.Render(); view.GetNaturalSize(); view.TouchedSignal().Connect( &OnTouched ); // Touch event Dali::Integration::TouchEvent event; Dali::Integration::Point pointDown, pointUp; event = Dali::Integration::TouchEvent(); pointDown.SetState( PointState::DOWN ); pointDown.SetScreenPosition( Vector2( 10, 10 ) ); event.AddPoint( pointDown ); application.ProcessEvent( event ); event = Dali::Integration::TouchEvent(); pointUp.SetState( PointState::UP ); pointUp.SetScreenPosition( Vector2( 10, 10 ) ); event.AddPoint( pointUp ); application.ProcessEvent( event ); // Key event Toolkit::KeyboardFocusManager::Get().SetCurrentFocusActor( view ); application.ProcessEvent( Integration::KeyEvent( "", "", "", DALI_KEY_ESCAPE, 0, 0, Integration::KeyEvent::DOWN, "", "", Device::Class::NONE, Device::Subclass::NONE ) ); application.SendNotification(); DALI_TEST_CHECK( gTouched ); DALI_TEST_CHECK( view ); END_TEST; } int UtcDaliWebViewFocusGainedAndLost(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); application.GetScene().Add( view ); application.SendNotification(); application.Render(); view.SetKeyInputFocus(); DALI_TEST_CHECK( view.HasKeyInputFocus() ); // reset view.ClearKeyInputFocus(); DALI_TEST_CHECK( !view.HasKeyInputFocus() ); END_TEST; } int UtcDaliWebViewPropertyPageZoomFactor(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); application.GetScene().Add( view ); application.SendNotification(); application.Render(); view.SetProperty( WebView::Property::PAGE_ZOOM_FACTOR, 1.5f); float zoomFactor = view.GetProperty<float>( WebView::Property::PAGE_ZOOM_FACTOR ); DALI_TEST_EQUALS( zoomFactor, 1.5f, TEST_LOCATION ); view.SetProperty( WebView::Property::PAGE_ZOOM_FACTOR, 1.0f); zoomFactor = view.GetProperty<float>( WebView::Property::PAGE_ZOOM_FACTOR ); DALI_TEST_EQUALS( zoomFactor, 1.0f, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewPropertyTextZoomFactor(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); application.GetScene().Add( view ); application.SendNotification(); application.Render(); view.SetProperty( WebView::Property::TEXT_ZOOM_FACTOR, 1.5f); float zoomFactor = view.GetProperty<float>( WebView::Property::TEXT_ZOOM_FACTOR ); DALI_TEST_EQUALS( zoomFactor, 1.5f, TEST_LOCATION ); view.SetProperty( WebView::Property::TEXT_ZOOM_FACTOR, 1.0f); zoomFactor = view.GetProperty<float>( WebView::Property::TEXT_ZOOM_FACTOR ); DALI_TEST_EQUALS( zoomFactor, 1.0f, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewPropertyLoadProgressPercentage(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); application.GetScene().Add( view ); application.SendNotification(); application.Render(); float percentage = view.GetProperty<float>( WebView::Property::LOAD_PROGRESS_PERCENTAGE ); DALI_TEST_EQUALS( percentage, 0.5f, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewMove(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); application.GetScene().Add( view ); application.SendNotification(); application.Render(); view.SetProperty( Actor::Property::POSITION, Vector2( 100, 100 )); Vector3 viewPos = view.GetProperty<Vector3>( Actor::Property::POSITION ); DALI_TEST_EQUALS( viewPos, Vector3( 100, 100, 0 ), TEST_LOCATION ); END_TEST; } int UtcDaliWebViewPropertyVideoHoleEnabled(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); const bool kDefaultValue = false; const bool kTestValue = true; // Check default value bool output; Property::Value value = view.GetProperty( WebView::Property::VIDEO_HOLE_ENABLED ); DALI_TEST_CHECK( value.Get( output ) ); DALI_TEST_EQUALS( output, kDefaultValue, TEST_LOCATION ); // Check Set/GetProperty view.SetProperty( WebView::Property::VIDEO_HOLE_ENABLED, kTestValue ); value = view.GetProperty( WebView::Property::VIDEO_HOLE_ENABLED ); DALI_TEST_CHECK( value.Get( output ) ); DALI_TEST_EQUALS( output, kTestValue, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewPropertyMouseEventsEnabled(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); const bool kDefaultValue = true; const bool kTestValue = false; // Check default value bool output; Property::Value value = view.GetProperty( WebView::Property::MOUSE_EVENTS_ENABLED ); DALI_TEST_CHECK( value.Get( output ) ); DALI_TEST_EQUALS( output, kDefaultValue, TEST_LOCATION ); // Check Set/GetProperty view.SetProperty( WebView::Property::MOUSE_EVENTS_ENABLED, kTestValue ); value = view.GetProperty( WebView::Property::MOUSE_EVENTS_ENABLED ); DALI_TEST_CHECK( value.Get( output ) ); DALI_TEST_EQUALS( output, kTestValue, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewPropertyKeyEventsEnabled(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); const bool kDefaultValue = true; const bool kTestValue = false; // Check default value bool output; Property::Value value = view.GetProperty( WebView::Property::KEY_EVENTS_ENABLED ); DALI_TEST_CHECK( value.Get( output ) ); DALI_TEST_EQUALS( output, kDefaultValue, TEST_LOCATION ); // Check Set/GetProperty view.SetProperty( WebView::Property::KEY_EVENTS_ENABLED, kTestValue ); value = view.GetProperty( WebView::Property::KEY_EVENTS_ENABLED ); DALI_TEST_CHECK( value.Get( output ) ); DALI_TEST_EQUALS( output, kTestValue, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewHoverAndWheel(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); application.GetScene().Add( view ); application.SendNotification(); application.Render(); view.GetNaturalSize(); view.HoveredSignal().Connect( &OnHovered ); view.WheelEventSignal().Connect( &OnWheelEvent ); // Hover event Dali::Integration::HoverEvent event = Dali::Integration::HoverEvent(); Dali::Integration::Point pointDown; pointDown.SetState( PointState::DOWN ); pointDown.SetScreenPosition( Vector2( 10, 10 ) ); event.AddPoint( pointDown ); application.ProcessEvent( event ); event = Dali::Integration::HoverEvent(); Dali::Integration::Point pointUp; pointUp.SetState( PointState::UP ); pointUp.SetScreenPosition( Vector2( 10, 10 ) ); event.AddPoint( pointUp ); application.ProcessEvent( event ); event = Dali::Integration::HoverEvent(); Dali::Integration::Point pointMotion; pointUp.SetState( PointState::MOTION ); pointUp.SetScreenPosition( Vector2( 10, 10 ) ); event.AddPoint( pointMotion ); application.ProcessEvent( event ); // Wheel event Dali::Integration::WheelEvent wheelEvent; wheelEvent.type = Dali::Integration::WheelEvent::Type::MOUSE_WHEEL; wheelEvent.direction = 0; wheelEvent.point = Vector2( 20, 20 ); wheelEvent.delta = 10; application.ProcessEvent( wheelEvent ); application.SendNotification(); DALI_TEST_CHECK( gHovered ); DALI_TEST_CHECK( gWheelEventHandled ); END_TEST; } int UtcDaliWebViewFormRepostDecidedFrameRendering(void) { ToolkitTestApplication application; WebView view = WebView::New(); view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); application.GetScene().Add( view ); application.SendNotification(); application.Render(); DALI_TEST_CHECK( view ); view.RegisterFormRepostDecidedCallback(&OnFormRepostDecided); view.RegisterFrameRenderedCallback(&OnFrameRendered); DALI_TEST_EQUALS( gFormRepostDecidedCallbackCalled, 0, TEST_LOCATION ); DALI_TEST_EQUALS( gFrameRenderedCallbackCalled, 0, TEST_LOCATION ); view.LoadUrl( TEST_URL1 ); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gFormRepostDecidedCallbackCalled, 1, TEST_LOCATION ); DALI_TEST_EQUALS( gFrameRenderedCallbackCalled, 1, TEST_LOCATION ); // form repost decision. DALI_TEST_CHECK(gFormRepostDecidedInstance); gFormRepostDecidedInstance->Reply(true); // reset gFormRepostDecidedInstance = nullptr; END_TEST; } int UtcDaliWebViewSslCertificateHttpAuthentication(void) { ToolkitTestApplication application; WebView view = WebView::New(); view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); application.GetScene().Add( view ); application.SendNotification(); application.Render(); DALI_TEST_CHECK( view ); view.RegisterCertificateConfirmedCallback(&OnCertificateConfirm); view.RegisterSslCertificateChangedCallback(&OnSslCertificateChanged); view.RegisterHttpAuthHandlerCallback(&OnHttpAuthHandler); DALI_TEST_EQUALS( gCertificateConfirmCallbackCalled, 0, TEST_LOCATION ); DALI_TEST_EQUALS( gSslCertificateChangedCallbackCalled, 0, TEST_LOCATION ); DALI_TEST_EQUALS( gHttpAuthHandlerCallbackCalled, 0, TEST_LOCATION ); view.LoadUrl( TEST_URL1 ); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gCertificateConfirmCallbackCalled, 1, TEST_LOCATION ); DALI_TEST_EQUALS( gSslCertificateChangedCallbackCalled, 1, TEST_LOCATION ); DALI_TEST_EQUALS( gHttpAuthHandlerCallbackCalled, 1, TEST_LOCATION ); // certificate. DALI_TEST_CHECK(gCertificateConfirmInstance); gCertificateConfirmInstance->Allow(true); DALI_TEST_CHECK(gCertificateConfirmInstance->IsFromMainFrame()); DALI_TEST_CHECK(gSslCertificateInstance); DALI_TEST_EQUALS(gSslCertificateInstance->GetPem(), "abc", TEST_LOCATION); DALI_TEST_CHECK(gSslCertificateInstance->IsContextSecure()); // http authentication. DALI_TEST_CHECK(gHttpAuthInstance); gHttpAuthInstance->Suspend(); gHttpAuthInstance->UseCredential("", ""); gHttpAuthInstance->CancelCredential(); DALI_TEST_EQUALS(gHttpAuthInstance->GetRealm(), "test", TEST_LOCATION); // reset gCertificateConfirmInstance = nullptr; gSslCertificateInstance = nullptr; gHttpAuthInstance = nullptr; END_TEST; } int UtcDaliWebViewGetWebBackForwardList(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebBackForwardList* bfList = view.GetBackForwardList(); DALI_TEST_CHECK( bfList != 0 ); END_TEST; } int UtcDaliWebViewGetWebContext(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebContext* context = view.GetContext(); DALI_TEST_CHECK( context != 0 ); END_TEST; } int UtcDaliWebViewGetWebCookieManager(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebCookieManager* cookieManager = view.GetCookieManager(); DALI_TEST_CHECK( cookieManager != 0 ); END_TEST; } int UtcDaliWebViewGetWebSettings(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ); END_TEST; } int UtcDaliWebViewProperty1(void) { // URL ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); std::string local; view.SetProperty( WebView::Property::URL, TEST_URL1 ); Property::Value val = view.GetProperty( WebView::Property::URL ); DALI_TEST_CHECK( val.Get( local ) ); DALI_TEST_EQUALS( local, TEST_URL1, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewProperty4(void) { // USER_AGENT ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); const std::string kDefaultValue; const std::string kTestValue = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"; // Check default value std::string output; Property::Value value = view.GetProperty( WebView::Property::USER_AGENT ); DALI_TEST_CHECK( value.Get( output ) ); DALI_TEST_EQUALS( output, kDefaultValue, TEST_LOCATION ); // Check Set/GetProperty view.SetProperty( WebView::Property::USER_AGENT, kTestValue ); value = view.GetProperty( WebView::Property::USER_AGENT ); DALI_TEST_CHECK( value.Get( output ) ); DALI_TEST_EQUALS( output, kTestValue, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewProperty9(void) { // SCROLL_POSITION ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); // Check default value Dali::Vector2 output = Dali::Vector2::ONE; view.GetProperty( WebView::Property::SCROLL_POSITION ).Get( output ); DALI_TEST_CHECK( output.x == 0 && output.y == 0 ); // Check Set/GetProperty Dali::Vector2 testValue = Dali::Vector2( 100, 100 ); view.SetProperty( WebView::Property::SCROLL_POSITION, testValue ); view.GetProperty( WebView::Property::SCROLL_POSITION ).Get( output ); DALI_TEST_EQUALS( output, testValue, TEST_LOCATION ); // Check default value of scroll size output = Dali::Vector2::ONE; view.GetProperty( WebView::Property::SCROLL_SIZE ).Get( output ); DALI_TEST_CHECK( output.x == 500 && output.y == 500 ); // Check default value of content size output = Dali::Vector2::ONE; view.GetProperty( WebView::Property::CONTENT_SIZE ).Get( output ); DALI_TEST_CHECK( output.x == 500 && output.y == 500 ); END_TEST; } int UtcDaliWebViewPropertyBackgroundColorSelectedTextEtc(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Vector4 testValue = Dali::Vector4(0.0f, 0.0f, 0.0f, 0.0f); view.SetProperty(WebView::Property::DOCUMENT_BACKGROUND_COLOR, testValue); view.SetProperty(WebView::Property::TILES_CLEARED_WHEN_HIDDEN, true); view.SetProperty(WebView::Property::TILE_COVER_AREA_MULTIPLIER, 1.0f); view.SetProperty(WebView::Property::CURSOR_ENABLED_BY_CLIENT, true); // Check default value std::string testText("test"); std::string output; view.GetProperty(WebView::Property::SELECTED_TEXT).Get(output); DALI_TEST_EQUALS(output, testText, TEST_LOCATION); END_TEST; } int UtcDaliWebViewPropertyTitleFavicon(void) { ToolkitTestApplication application; char argv[] = "--test"; WebView view = WebView::New( 1, (char**)&argv ); DALI_TEST_CHECK( view ); // reset something view.ClearAllTilesResources(); // Check default value of title std::string testValue("title"); std::string output; view.GetProperty( WebView::Property::TITLE ).Get( output ); DALI_TEST_EQUALS( output, testValue, TEST_LOCATION ); // Check the case that favicon is not null. Dali::Toolkit::ImageView favicon = view.GetFavicon(); DALI_TEST_CHECK( favicon ); Dali::Vector3 iconsize = favicon.GetProperty< Vector3 >( Dali::Actor::Property::SIZE ); DALI_TEST_CHECK( ( int )iconsize.width == 2 && ( int )iconsize.height == 2 ); // Check the case that favicon is null. favicon = view.GetFavicon(); DALI_TEST_CHECK( !favicon ); END_TEST; } int UtcDaliWebViewContextMenuShownAndHidden(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); // load url. view.RegisterContextMenuShownCallback( &OnContextMenuShown ); view.RegisterContextMenuHiddenCallback( &OnContextMenuHidden ); DALI_TEST_EQUALS( gContextMenuShownCallbackCalled, 0, TEST_LOCATION ); DALI_TEST_EQUALS( gContextMenuHiddenCallbackCalled, 0, TEST_LOCATION ); DALI_TEST_CHECK(gContextMenuShownInstance == 0); DALI_TEST_CHECK(gContextMenuHiddenInstance == 0); view.LoadUrl( TEST_URL1 ); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gContextMenuShownCallbackCalled, 1, TEST_LOCATION ); DALI_TEST_EQUALS( gContextMenuHiddenCallbackCalled, 1, TEST_LOCATION ); // check context meun & its items. DALI_TEST_CHECK(gContextMenuShownInstance != 0); std::unique_ptr<Dali::WebEngineContextMenuItem> item = gContextMenuShownInstance->GetItemAt(0); DALI_TEST_CHECK(item.get() != 0); std::vector<std::unique_ptr<Dali::WebEngineContextMenuItem>> itemList = gContextMenuShownInstance->GetItemList(); DALI_TEST_CHECK(itemList.size() == 1); DALI_TEST_CHECK(gContextMenuShownInstance->RemoveItem(*(item.get()))); DALI_TEST_CHECK(gContextMenuShownInstance->AppendItemAsAction(WebEngineContextMenuItem::ItemTag::NO_ACTION, "", false)); DALI_TEST_CHECK(gContextMenuShownInstance->AppendItem(WebEngineContextMenuItem::ItemTag::NO_ACTION, "", "", false)); DALI_TEST_CHECK(gContextMenuShownInstance->SelectItem(*(item.get()))); DALI_TEST_CHECK(gContextMenuShownInstance->Hide()); Dali::WebEngineContextMenuItem::ItemTag testItemTag = Dali::WebEngineContextMenuItem::ItemTag::NO_ACTION; DALI_TEST_EQUALS(item->GetTag(), testItemTag, TEST_LOCATION); Dali::WebEngineContextMenuItem::ItemType testItemType = Dali::WebEngineContextMenuItem::ItemType::ACTION; DALI_TEST_EQUALS(item->GetType(), testItemType, TEST_LOCATION); DALI_TEST_CHECK(item->IsEnabled()); std::string testLinkUrl("http://test.html"); DALI_TEST_EQUALS(item->GetLinkUrl(), testLinkUrl, TEST_LOCATION); std::string testImageUrl("http://test.jpg"); DALI_TEST_EQUALS(item->GetImageUrl(), testImageUrl, TEST_LOCATION); std::string testTitle("title"); DALI_TEST_EQUALS(item->GetTitle(), testTitle, TEST_LOCATION); DALI_TEST_CHECK(item->GetParentMenu().get() == 0); DALI_TEST_CHECK(gContextMenuHiddenInstance != 0); gContextMenuShownInstance = nullptr; gContextMenuHiddenInstance = nullptr; END_TEST; } int UtcDaliWebViewScrollBy(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); // load url. view.RegisterScrollEdgeReachedCallback( &OnScrollEdgeReached ); DALI_TEST_EQUALS( gScrollEdgeReachedCallbackCalled, 0, TEST_LOCATION ); view.LoadUrl( TEST_URL1 ); Test::EmitGlobalTimerSignal(); // set scroll position. Dali::Vector2 output = Dali::Vector2::ONE; Dali::Vector2 testValue = Dali::Vector2( 100, 100 ); view.SetProperty( WebView::Property::SCROLL_POSITION, testValue ); view.GetProperty( WebView::Property::SCROLL_POSITION ).Get( output ); DALI_TEST_EQUALS( output, testValue, TEST_LOCATION ); // scroll by and trigger scrollEdgeReached event. view.ScrollBy( 50, 50 ); Test::EmitGlobalTimerSignal(); view.GetProperty( WebView::Property::SCROLL_POSITION ).Get( output ); DALI_TEST_CHECK( output.x == 150 && output.y == 150 ); DALI_TEST_EQUALS( gScrollEdgeReachedCallbackCalled, 1, TEST_LOCATION ); // scroll by and trigger scrollEdgeReached event. bool result = view.ScrollEdgeBy( 50, 50 ); DALI_TEST_CHECK( result ); Test::EmitGlobalTimerSignal(); view.GetProperty( WebView::Property::SCROLL_POSITION ).Get( output ); DALI_TEST_CHECK( output.x == 200 && output.y == 200 ); DALI_TEST_EQUALS( gScrollEdgeReachedCallbackCalled, 2, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewSetGetScaleFactorActivateAccessibility(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); application.GetScene().Add( view ); application.SendNotification(); application.Render(); view.ActivateAccessibility(true); view.AddDynamicCertificatePath("host", "test/to/path"); bool found = view.HighlightText("test", Dali::WebEnginePlugin::FindOption::CASE_INSENSITIVE, 2); DALI_TEST_CHECK( found ); view.SetScaleFactor(1.5f, Dali::Vector2(0.0f, 0.0f)); float result = view.GetScaleFactor(); DALI_TEST_EQUALS( result, 1.5f, TEST_LOCATION ); view.SetScaleFactor(1.0f, Dali::Vector2(0.0f, 0.0f)); result = view.GetScaleFactor(); DALI_TEST_EQUALS( result, 1.0f, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewGetScreenshotSyncAndAsync(void) { // SCROLL_POSITION ToolkitTestApplication application; char argv[] = "--test"; WebView view = WebView::New( 1, (char**)&argv ); DALI_TEST_CHECK( view ); // Check GetScreenshot Dali::Rect<int> viewArea; viewArea.x = 100; viewArea.y = 100; viewArea.width = 10; viewArea.height = 10; Dali::Toolkit::ImageView screenshot = view.GetScreenshot(viewArea, 1.0f); DALI_TEST_CHECK( screenshot ); Dali::Vector3 shotsize = screenshot.GetProperty< Vector3 >( Dali::Actor::Property::SIZE ); DALI_TEST_CHECK( ( int )shotsize.width == viewArea.width && ( int )shotsize.height == viewArea.height ); // Check GetScreenshotAsynchronously viewArea.x = 100; viewArea.y = 100; viewArea.width = 100; viewArea.height = 100; bool result = view.GetScreenshotAsynchronously(viewArea, 1.0f, &OnScreenshotCaptured); DALI_TEST_CHECK( result ); Test::EmitGlobalTimerSignal(); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gScreenshotCapturedCallbackCalled, 1, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewVideoPlayingGeolocationPermission(void) { // SCROLL_POSITION ToolkitTestApplication application; char argv[] = "--test"; WebView view = WebView::New( 1, (char**)&argv ); DALI_TEST_CHECK( view ); // Check CheckVideoPlayingAsynchronously bool result = view.CheckVideoPlayingAsynchronously(&OnVideoPlaying); DALI_TEST_CHECK( result ); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gVideoPlayingCallbackCalled, 1, TEST_LOCATION ); // Check RegisterGeolocationPermissionCallback view.RegisterGeolocationPermissionCallback(&OnGeolocationPermission); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gGeolocationPermissionCallbackCalled, 1, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewResponsePolicyDecisionRequest(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); // load url. view.RegisterResponsePolicyDecidedCallback( &OnResponsePolicyDecided ); DALI_TEST_EQUALS( gResponsePolicyDecidedCallbackCalled, 0, TEST_LOCATION ); DALI_TEST_CHECK(gResponsePolicyDecisionInstance == 0); view.LoadUrl( TEST_URL1 ); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gResponsePolicyDecidedCallbackCalled, 1, TEST_LOCATION ); // check response policy decision & its frame. DALI_TEST_CHECK(gResponsePolicyDecisionInstance != 0); std::string testUrl("http://test.html"); DALI_TEST_EQUALS(gResponsePolicyDecisionInstance->GetUrl(), testUrl, TEST_LOCATION); std::string testCookie("test:abc"); DALI_TEST_EQUALS(gResponsePolicyDecisionInstance->GetCookie(), testCookie, TEST_LOCATION); Dali::WebEnginePolicyDecision::DecisionType testDecisionType = Dali::WebEnginePolicyDecision::DecisionType::USE; DALI_TEST_EQUALS(gResponsePolicyDecisionInstance->GetDecisionType(), testDecisionType, TEST_LOCATION); std::string testResponseMime("txt/xml"); DALI_TEST_EQUALS(gResponsePolicyDecisionInstance->GetResponseMime(), testResponseMime, TEST_LOCATION); int32_t ResponseStatusCode = 500; DALI_TEST_EQUALS(gResponsePolicyDecisionInstance->GetResponseStatusCode(), ResponseStatusCode, TEST_LOCATION); Dali::WebEnginePolicyDecision::NavigationType testNavigationType = Dali::WebEnginePolicyDecision::NavigationType::LINK_CLICKED; DALI_TEST_EQUALS(gResponsePolicyDecisionInstance->GetNavigationType(), testNavigationType, TEST_LOCATION); std::string testScheme("test"); DALI_TEST_EQUALS(gResponsePolicyDecisionInstance->GetScheme(), testScheme, TEST_LOCATION); DALI_TEST_CHECK(gResponsePolicyDecisionInstance->Use()); DALI_TEST_CHECK(gResponsePolicyDecisionInstance->Ignore()); DALI_TEST_CHECK(gResponsePolicyDecisionInstance->Suspend()); Dali::WebEngineFrame* webFrame = &(gResponsePolicyDecisionInstance->GetFrame()); DALI_TEST_CHECK(webFrame); DALI_TEST_CHECK(webFrame->IsMainFrame()); gResponsePolicyDecisionInstance = nullptr; END_TEST; } int UtcDaliWebViewHitTest(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); // load url. view.LoadUrl( TEST_URL1 ); // sync hit test. std::unique_ptr<Dali::WebEngineHitTest> hitTest = view.CreateHitTest(100, 100, Dali::WebEngineHitTest::HitTestMode::DEFAULT); DALI_TEST_CHECK(hitTest != 0); DALI_TEST_EQUALS(hitTest->GetResultContext(), Dali::WebEngineHitTest::ResultContext::DOCUMENT, TEST_LOCATION); std::string testLinkUri("http://test.html"); DALI_TEST_EQUALS(hitTest->GetLinkUri(), testLinkUri, TEST_LOCATION); std::string testLinkTitle("test"); DALI_TEST_EQUALS(hitTest->GetLinkTitle(), testLinkTitle, TEST_LOCATION); std::string testLinkLabel("label"); DALI_TEST_EQUALS(hitTest->GetLinkLabel(), testLinkLabel, TEST_LOCATION); std::string testImageUri("http://test.jpg"); DALI_TEST_EQUALS(hitTest->GetImageUri(), testImageUri, TEST_LOCATION); std::string testMediaUri("http://test.mp4"); DALI_TEST_EQUALS(hitTest->GetMediaUri(), testMediaUri, TEST_LOCATION); std::string testTagName("img"); DALI_TEST_EQUALS(hitTest->GetTagName(), testTagName, TEST_LOCATION); std::string testNodeValue("test"); DALI_TEST_EQUALS(hitTest->GetNodeValue(), testNodeValue, TEST_LOCATION); Dali::Property::Map testMap = hitTest->GetAttributes(); DALI_TEST_EQUALS(testMap.Count(), 0, TEST_LOCATION); std::string testImageFileNameExtension("jpg"); DALI_TEST_EQUALS(hitTest->GetImageFileNameExtension(), testImageFileNameExtension, TEST_LOCATION); Dali::PixelData testImageBuffer = hitTest->GetImageBuffer(); DALI_TEST_CHECK((int)testImageBuffer.GetWidth() == 2 && (int)testImageBuffer.GetHeight() == 2); // async... bool result = view.CreateHitTestAsynchronously(100, 100, Dali::WebEngineHitTest::HitTestMode::DEFAULT, &OnHitTestCreated); DALI_TEST_CHECK(result); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gHitTestCreatedCallbackCalled, 1, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewEvaluteJavaScript(void) { ToolkitTestApplication application; WebView view = WebView::New( "ko-KR", "Asia/Seoul" ); view.LoadHtmlString( "<body>Hello World!</body>" ); view.EvaluateJavaScript( "jsObject.postMessage('Hello')" ); view.EvaluateJavaScript( "jsObject.postMessage('World')", OnEvaluateJavaScript ); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gEvaluateJavaScriptCallbackCalled, 1, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewJavaScriptAlertConfirmPrompt(void) { ToolkitTestApplication application; WebView view = WebView::New( "ko-KR", "Asia/Seoul" ); view.RegisterJavaScriptAlertCallback( &OnJavaScriptAlert ); view.LoadHtmlString( "<head><script type='text/javascript'>alert('this is an alert popup.');</script></head><body>Hello World!</body>" ); view.JavaScriptAlertReply(); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gJavaScriptAlertCallbackCalled, 1, TEST_LOCATION ); view.RegisterJavaScriptConfirmCallback( &OnJavaScriptConfirm ); view.LoadHtmlString( "<head><script type='text/javascript'>confirm('this is a confirm popup.');</script></head><body>Hello World!</body>" ); view.JavaScriptConfirmReply( true ); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gJavaScriptConfirmCallbackCalled, 1, TEST_LOCATION ); view.RegisterJavaScriptPromptCallback( &OnJavaScriptPrompt ); view.LoadHtmlString( "<head><script type='text/javascript'>prompt('this is a prompt popup.');</script></head><body>Hello World!</body>" ); view.JavaScriptPromptReply( "it is a prompt." ); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gJavaScriptPromptCallbackCalled, 1, TEST_LOCATION ); END_TEST; } int UtcDaliWebViewLoadHtmlStringOverrideCurrentEntryAndContents(void) { ToolkitTestApplication application; WebView view = WebView::New( "ko-KR", "Asia/Seoul" ); DALI_TEST_CHECK( view ); std::string html("<body>Hello World!</body>"); std::string basicUri("http://basicurl"); std::string unreachableUrl("http://unreachableurl"); bool result = view.LoadHtmlStringOverrideCurrentEntry( html, basicUri, unreachableUrl ); DALI_TEST_CHECK( result ); application.SendNotification(); application.Render(); Test::EmitGlobalTimerSignal(); result = view.LoadContents( html, html.length(), "html/text", "utf-8", basicUri ); DALI_TEST_CHECK( result ); END_TEST; } int UtcDaliWebViewReloadSuspendResumeNetworkLoadingCustomHeader(void) { ToolkitTestApplication application; WebView view = WebView::New(); view.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); view.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); view.SetProperty( Actor::Property::POSITION, Vector2( 0, 0 )); view.SetProperty( Actor::Property::SIZE, Vector2( 800, 600 ) ); application.GetScene().Add( view ); application.SendNotification(); application.Render(); DALI_TEST_CHECK( view ); view.LoadUrl( "http://test.html" ); bool result = view.AddCustomHeader("key", "value"); DALI_TEST_CHECK( result ); result = view.ReloadWithoutCache(); DALI_TEST_CHECK( result ); uint32_t portNumber = view.StartInspectorServer(5000); DALI_TEST_EQUALS( portNumber, 5000, TEST_LOCATION ); application.SendNotification(); application.Render(); Test::EmitGlobalTimerSignal(); result = view.StopInspectorServer(); DALI_TEST_CHECK( result ); view.SuspendNetworkLoading(); result = view.RemoveCustomHeader("key"); DALI_TEST_CHECK( result ); view.ResumeNetworkLoading(); END_TEST; } int UtcDaliWebViewMethodsForCoverage(void) { ToolkitTestApplication application; WebView view = WebView::New( "ko-KR", "Asia/Seoul" ); view.LoadHtmlString( "<body>Hello World!</body>" ); view.AddJavaScriptMessageHandler( "jsObject", []( const std::string& arg ) { } ); view.SetTtsFocus(true); DALI_TEST_CHECK( view ); END_TEST; } // test cases for web backforward list. int UtcDaliWebBackForwardListCheckItem(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebBackForwardList* bfList = view.GetBackForwardList(); DALI_TEST_CHECK( bfList != 0 ) unsigned int itemCount = bfList->GetItemCount(); DALI_TEST_CHECK( itemCount == 1 ) std::unique_ptr<Dali::WebEngineBackForwardListItem> citem = bfList->GetCurrentItem(); DALI_TEST_CHECK( citem != 0 ); std::unique_ptr<Dali::WebEngineBackForwardListItem> citemP = bfList->GetPreviousItem(); DALI_TEST_CHECK( citemP != 0 ); std::unique_ptr<Dali::WebEngineBackForwardListItem> citemN = bfList->GetNextItem(); DALI_TEST_CHECK( citemN != 0 ); const std::string kDefaultUrl( "http://url" ); std::string testValue = citem->GetUrl(); DALI_TEST_EQUALS( testValue, kDefaultUrl, TEST_LOCATION ); const std::string kDefaultTitle( "title" ); testValue = citem->GetTitle(); DALI_TEST_EQUALS( testValue, kDefaultTitle, TEST_LOCATION ); const std::string kDefaultOriginalUrl( "http://originalurl" ); testValue = citem->GetOriginalUrl(); DALI_TEST_EQUALS( testValue, kDefaultOriginalUrl, TEST_LOCATION ); std::unique_ptr<Dali::WebEngineBackForwardListItem> item = bfList->GetItemAtIndex( 0 ); DALI_TEST_CHECK( item != 0 ); std::vector<std::unique_ptr<Dali::WebEngineBackForwardListItem>> vecBack = bfList->GetBackwardItems(-1); DALI_TEST_CHECK( vecBack.size() == 1 ); std::vector<std::unique_ptr<Dali::WebEngineBackForwardListItem>> vecForward = bfList->GetForwardItems(-1); DALI_TEST_CHECK( vecForward.size() == 1 ); END_TEST; } // test cases for web context. int UtcDaliWebContextGetSetCacheModel(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebContext* context = view.GetContext(); DALI_TEST_CHECK( context != 0 ) std::string kDefaultValue; // Reset something context->SetAppId( "id" ); context->SetApplicationType( Dali::WebEngineContext::ApplicationType::OTHER ); context->SetTimeOffset( 0 ); context->SetTimeZoneOffset( 0, 0 ); context->SetDefaultProxyAuth( kDefaultValue, kDefaultValue ); context->DeleteAllWebDatabase(); context->DeleteAllWebStorage(); context->DeleteLocalFileSystem(); context->ClearCache(); context->DeleteAllFormPasswordData(); context->DeleteAllFormCandidateData(); // Check default value Dali::WebEngineContext::CacheModel value = context->GetCacheModel(); DALI_TEST_CHECK( value == Dali::WebEngineContext::CacheModel::DOCUMENT_VIEWER ); // Check Set/GetProperty context->SetCacheModel( Dali::WebEngineContext::CacheModel::DOCUMENT_BROWSER ); value = context->GetCacheModel(); DALI_TEST_CHECK( value == Dali::WebEngineContext::CacheModel::DOCUMENT_BROWSER ); // Get cache enabled context->EnableCache( true ); DALI_TEST_CHECK( context->IsCacheEnabled() ); // Get certificate context->SetCertificateFilePath( "test" ); std::string str = context->GetCertificateFilePath(); DALI_TEST_EQUALS( str, "test", TEST_LOCATION ); // Set version DALI_TEST_CHECK( context->SetAppVersion( "test" ) ); // Register std::vector<std::string> temp; context->RegisterUrlSchemesAsCorsEnabled( temp ); context->RegisterJsPluginMimeTypes( temp ); context->DeleteFormPasswordDataList( temp ); // Get zoom factor context->SetDefaultZoomFactor( 1.0f ); DALI_TEST_EQUALS( context->GetDefaultZoomFactor(), float( 1.0f ), TEST_LOCATION ); // Delete cache and database DALI_TEST_CHECK( context->DeleteAllApplicationCache() ); DALI_TEST_CHECK( context->DeleteAllWebIndexedDatabase() ); // Get contextProxy context->SetProxyUri( "test" ); DALI_TEST_EQUALS( context->GetProxyUri(), "test", TEST_LOCATION ); context->SetProxyBypassRule("", "test"); DALI_TEST_EQUALS( context->GetProxyBypassRule(), "test", TEST_LOCATION ); //Notify low memory DALI_TEST_CHECK( context->FreeUnusedMemory() ); END_TEST; } int UtcDaliWebContextGetWebDatabaseStorageOrigins(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebContext* context = view.GetContext(); DALI_TEST_CHECK( context != 0 ) std::string kDefaultValue; // get origins of web database bool result = context->GetWebDatabaseOrigins(&OnSecurityOriginsAcquired); DALI_TEST_CHECK( result ); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gSecurityOriginsAcquiredCallbackCalled, 1, TEST_LOCATION ); DALI_TEST_CHECK(gSecurityOriginList.size() == 1); Dali::WebEngineSecurityOrigin* origin = gSecurityOriginList[0].get(); DALI_TEST_CHECK( origin ); result = context->DeleteWebDatabase(*origin); DALI_TEST_CHECK( result ); // get origins of web storage result = context->GetWebStorageOrigins(&OnSecurityOriginsAcquired); DALI_TEST_CHECK( result ); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gSecurityOriginsAcquiredCallbackCalled, 2, TEST_LOCATION ); DALI_TEST_CHECK(gSecurityOriginList.size() == 1); origin = gSecurityOriginList[0].get(); DALI_TEST_CHECK( origin ); result = context->GetWebStorageUsageForOrigin(*origin, &OnStorageUsageAcquired); DALI_TEST_CHECK( result ); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gStorageUsageAcquiredCallbackCalled, 1, TEST_LOCATION ); result = context->DeleteWebStorage(*origin); DALI_TEST_CHECK( result ); result = context->DeleteApplicationCache(*origin); DALI_TEST_CHECK( result ); // form passwords, download state, mime type. context->GetFormPasswordList(&OnFormPasswordsAcquired); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS(gFormPasswordsAcquiredCallbackCalled, 1, TEST_LOCATION); DALI_TEST_CHECK(gPasswordDataList.size() == 1); DALI_TEST_EQUALS(gPasswordDataList[0]->url, "http://test.html", TEST_LOCATION); DALI_TEST_CHECK(gPasswordDataList[0]->useFingerprint == false); context->RegisterDownloadStartedCallback(&OnDownloadStarted); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS(gDownloadStartedCallbackCalled, 1, TEST_LOCATION); context->RegisterMimeOverriddenCallback(&OnMimeOverridden); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS(gMimeOverriddenCallbackCalled, 1, TEST_LOCATION); gSecurityOriginList.clear(); gPasswordDataList.clear(); END_TEST; } int UtcDaliWebContextHttpRequestInterceptor(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebContext* context = view.GetContext(); DALI_TEST_CHECK( context != 0 ) // load url. context->RegisterRequestInterceptedCallback(&OnRequestIntercepted); DALI_TEST_EQUALS(gRequestInterceptedCallbackCalled, 0, TEST_LOCATION); DALI_TEST_CHECK(gRequestInterceptorInstance == 0); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gRequestInterceptedCallbackCalled, 1, TEST_LOCATION ); // check request interceptor. DALI_TEST_CHECK(gRequestInterceptorInstance != 0); DALI_TEST_CHECK(gRequestInterceptorInstance->Ignore()); DALI_TEST_CHECK(gRequestInterceptorInstance->SetResponseStatus(400, "error")); DALI_TEST_CHECK(gRequestInterceptorInstance->AddResponseHeader("key1", "value1")); Dali::Property::Map testHeaders; testHeaders.Insert("key2", "value2"); DALI_TEST_CHECK(gRequestInterceptorInstance->AddResponseHeaders(testHeaders)); DALI_TEST_CHECK(gRequestInterceptorInstance->AddResponseBody("test", 4)); DALI_TEST_CHECK(gRequestInterceptorInstance->AddResponse("key:value", "test", 4)); DALI_TEST_CHECK(gRequestInterceptorInstance->WriteResponseChunk("test", 4)); std::string testUrl("http://test.html"); DALI_TEST_EQUALS(gRequestInterceptorInstance->GetUrl(), testUrl, TEST_LOCATION); std::string testMethod("GET"); DALI_TEST_EQUALS(gRequestInterceptorInstance->GetMethod(), testMethod, TEST_LOCATION); Dali::Property::Map resultHeaders = gRequestInterceptorInstance->GetHeaders(); DALI_TEST_EQUALS(resultHeaders.Count(), 2, TEST_LOCATION); gRequestInterceptorInstance = nullptr; END_TEST; } // test cases for web cookie manager. int UtcDaliWebCookieManagerGetSetCookieAcceptPolicy(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebCookieManager* cookieManager = view.GetCookieManager(); DALI_TEST_CHECK( cookieManager != 0 ) const std::string kDefaultValue; // Reset something cookieManager->SetPersistentStorage( kDefaultValue, Dali::WebEngineCookieManager::CookiePersistentStorage::SQLITE ); cookieManager->ClearCookies(); // Check default value Dali::WebEngineCookieManager::CookieAcceptPolicy value = cookieManager->GetCookieAcceptPolicy(); DALI_TEST_CHECK( value == Dali::WebEngineCookieManager::CookieAcceptPolicy::NO_THIRD_PARTY ); // Check Set/GetProperty cookieManager->SetCookieAcceptPolicy( Dali::WebEngineCookieManager::CookieAcceptPolicy::ALWAYS ); value = cookieManager->GetCookieAcceptPolicy(); DALI_TEST_CHECK( value == Dali::WebEngineCookieManager::CookieAcceptPolicy::ALWAYS ); END_TEST; } int UtcDaliWebCookieManagerChangesWatch(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebCookieManager* cookieManager = view.GetCookieManager(); DALI_TEST_CHECK( cookieManager != 0 ) cookieManager->ChangesWatch(&OnChangesWatch); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS( gCookieManagerChangsWatchCallbackCalled, 1, TEST_LOCATION ); END_TEST; } // test cases for web settings. int UtcDaliWebSettingsGetSetDefaultFontSize(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value int value = settings->GetDefaultFontSize(); DALI_TEST_CHECK( value == 16 ); // Check Set/GetProperty settings->SetDefaultFontSize( 20 ); value = settings->GetDefaultFontSize(); DALI_TEST_CHECK( value == 20 ); END_TEST; } int UtcDaliWebSettingsCheckEnableJavaScript(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->IsJavaScriptEnabled(); DALI_TEST_CHECK( value ); // Check Set/GetProperty settings->EnableJavaScript( false ); value = settings->IsJavaScriptEnabled(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsCheckEnableAutoFitting(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->IsAutoFittingEnabled(); DALI_TEST_CHECK( value ); // Check Set/GetProperty settings->EnableAutoFitting( false ); value = settings->IsAutoFittingEnabled(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsCheckEnablePlugins(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->ArePluginsEnabled(); DALI_TEST_CHECK( value ); // Check Set/GetProperty settings->EnablePlugins( false ); value = settings->ArePluginsEnabled(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsCheckEnablePrivateBrowsing(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->IsPrivateBrowsingEnabled(); DALI_TEST_CHECK( value ); // Check Set/GetProperty settings->EnablePrivateBrowsing( false ); value = settings->IsPrivateBrowsingEnabled(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsCheckEnableLinkMagnifier(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->IsLinkMagnifierEnabled(); DALI_TEST_CHECK( value ); // Check Set/GetProperty settings->EnableLinkMagnifier( false ); value = settings->IsLinkMagnifierEnabled(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsCheckUseKeypadWithoutUserAction(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->IsKeypadWithoutUserActionUsed(); DALI_TEST_CHECK( value ); // Check Set/GetProperty settings->UseKeypadWithoutUserAction( false ); value = settings->IsKeypadWithoutUserActionUsed(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsCheckEnableAutofillPasswordForm(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->IsAutofillPasswordFormEnabled(); DALI_TEST_CHECK( value ); settings->EnableAutofillPasswordForm( false ); value = settings->IsAutofillPasswordFormEnabled(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsCheckEnableFormCandidateData(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ); // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->IsFormCandidateDataEnabled(); DALI_TEST_CHECK( value ); // Check Set/GetProperty settings->EnableFormCandidateData( false ); value = settings->IsFormCandidateDataEnabled(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsCheckEnableTextSelection(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ); // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->IsTextSelectionEnabled(); DALI_TEST_CHECK( value ); //Check Set/GetProperty settings->EnableTextSelection(false); value = settings->IsTextSelectionEnabled(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsCheckEnableTextAutosizing(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ); // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->IsTextAutosizingEnabled(); DALI_TEST_CHECK( value ); // Check Set/GetProperty settings->EnableTextAutosizing(false); value = settings->IsTextAutosizingEnabled(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsCheckEnableArrowScroll(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ); // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->IsArrowScrollEnabled(); DALI_TEST_CHECK( value ); // Check Set/GetProperty settings->EnableArrowScroll(false); value = settings->IsArrowScrollEnabled(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsCheckEnableClipboard(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ); // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->IsClipboardEnabled(); DALI_TEST_CHECK( value ); settings->EnableClipboard(false); value = settings->IsClipboardEnabled(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsCheckEnableImePanel(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ); // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->IsImePanelEnabled(); DALI_TEST_CHECK( value ); // Check Set/GetProperty settings->EnableImePanel(false); value = settings->IsImePanelEnabled(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsCheckAllowImagesLoadAutomatically(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value is true or not bool value = settings->AreImagesLoadedAutomatically(); DALI_TEST_CHECK( value ); // Check Set/GetProperty settings->AllowImagesLoadAutomatically( false ); value = settings->AreImagesLoadedAutomatically(); DALI_TEST_CHECK( !value ); END_TEST; } int UtcDaliWebSettingsGetSetDefaultTextEncodingName(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) const std::string kDefaultValue; const std::string kTestValue = "UTF-8"; // Reset something settings->AllowMixedContents( false ); settings->EnableSpatialNavigation( false ); settings->EnableWebSecurity( false ); settings->EnableCacheBuilder( false ); settings->EnableDoNotTrack( false ); settings->UseScrollbarThumbFocusNotifications( false ); settings->AllowFileAccessFromExternalUrl( false ); settings->AllowScriptsOpenWindows( false ); // Check default value std::string value = settings->GetDefaultTextEncodingName(); DALI_TEST_EQUALS( value, kDefaultValue, TEST_LOCATION ); // Check Set/GetProperty settings->SetDefaultTextEncodingName( kTestValue ); value = settings->GetDefaultTextEncodingName(); DALI_TEST_EQUALS( value, kTestValue, TEST_LOCATION ); END_TEST; } int UtcDaliWebSettingsSetViewportMetaTag(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) // Check the value is true or not bool value = settings->SetViewportMetaTag(true); DALI_TEST_CHECK( value ); END_TEST; } int UtcDaliWebSettingsSetForceZoom(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) // Check the value is true or not bool value = settings->SetForceZoom(true); DALI_TEST_CHECK( value ); value = settings->IsZoomForced(); DALI_TEST_CHECK( value ); END_TEST; } int UtcDaliWebSettingsSetTextZoomEnabled(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) // Check the value is true or not bool value = settings->SetTextZoomEnabled(true); DALI_TEST_CHECK( value ); value = settings->IsTextZoomEnabled(); DALI_TEST_CHECK( value ); END_TEST; } int UtcDaliWebSettingsSetExtraFeature(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK( view ); Dali::Toolkit::WebSettings* settings = view.GetSettings(); DALI_TEST_CHECK( settings != 0 ) // Check the value is true or not settings->SetExtraFeature("test", true); bool value = settings->IsExtraFeatureEnabled("test"); DALI_TEST_CHECK( value ); END_TEST; } int UtcDaliWebViewGetPlainText(void) { ToolkitTestApplication application; WebView view = WebView::New(); DALI_TEST_CHECK(view); view.LoadUrl(TEST_URL1); view.GetPlainTextAsynchronously(&OnPlainTextReceived); Test::EmitGlobalTimerSignal(); DALI_TEST_EQUALS(gPlainTextReceivedCallbackCalled, 1, TEST_LOCATION); END_TEST; }
32.14837
171
0.762198
[ "render", "vector" ]
4e66897561db7387576831f927d9d837428afceb
23,138
cc
C++
src/kk-ws.cc
hailongz/kk-surface
d87cd8f26682f7c96dc4becc6e6f705d60e8941a
[ "MIT" ]
null
null
null
src/kk-ws.cc
hailongz/kk-surface
d87cd8f26682f7c96dc4becc6e6f705d60e8941a
[ "MIT" ]
null
null
null
src/kk-ws.cc
hailongz/kk-surface
d87cd8f26682f7c96dc4becc6e6f705d60e8941a
[ "MIT" ]
null
null
null
// // kk-ws.cc // app // // Created by hailong11 on 2018/6/8. // Copyright © 2018年 kkmofang.cn. All rights reserved. // #include "kk-config.h" #include "kk-ws.h" #include "kk-ev.h" #ifndef ntohll #define ntohll(x) \ ((__uint64_t)((((__uint64_t)(x) & 0xff00000000000000ULL) >> 56) | \ (((__uint64_t)(x) & 0x00ff000000000000ULL) >> 40) | \ (((__uint64_t)(x) & 0x0000ff0000000000ULL) >> 24) | \ (((__uint64_t)(x) & 0x000000ff00000000ULL) >> 8) | \ (((__uint64_t)(x) & 0x00000000ff000000ULL) << 8) | \ (((__uint64_t)(x) & 0x0000000000ff0000ULL) << 24) | \ (((__uint64_t)(x) & 0x000000000000ff00ULL) << 40) | \ (((__uint64_t)(x) & 0x00000000000000ffULL) << 56))) #define htonll(x) ntohll(x) #endif #define Sec_WebSocket_Key "RCfYMqhgCo4N4E+cIZ0iPg==" #define MAX_BUF_SIZE 2147483647 #define KKFinMask 0x80 #define KKOpCodeMask 0x0F #define KKRSVMask 0x70 #define KKMaskMask 0x80 #define KKPayloadLenMask 0x7F #define KKMaxFrameSize 32 namespace kk { enum WebSocketOpCode { WebSocketOpCodeContinueFrame = 0x0, WebSocketOpCodeTextFrame = 0x1, WebSocketOpCodeBinaryFrame = 0x2, WebSocketOpCodeConnectionClose = 0x8, WebSocketOpCodePing = 0x9, WebSocketOpCodePong = 0xA, }; static duk_ret_t WebSocketAlloc(duk_context * ctx) { int top = duk_get_top(ctx); kk::CString url = nullptr; kk::CString protocol = nullptr; if(top >0 && duk_is_string(ctx, -top)) { url = duk_to_string(ctx, -top); } if(top >1 && duk_is_string(ctx, -top + 1)) { protocol = duk_to_string(ctx, -top + 1); } if(url) { kk::Strong v = (kk::Object *) (new WebSocket()); WebSocket * vv = v.as<WebSocket>(); vv->open(ev_base(ctx),ev_dns(ctx),url,protocol); kk::script::PushObject(ctx, (kk::Object *) vv); return 1; } return 0; } IMP_SCRIPT_CLASS_BEGIN(nullptr, WebSocket, WebSocket) static kk::script::Method methods[] = { {"on",(kk::script::Function) &WebSocket::duk_on}, {"close",(kk::script::Function) &WebSocket::duk_close}, {"send",(kk::script::Function) &WebSocket::duk_send}, }; kk::script::SetMethod(ctx, -1, methods, sizeof(methods) / sizeof(kk::script::Method)); duk_push_string(ctx, "alloc"); duk_push_c_function(ctx, WebSocketAlloc, 2); duk_put_prop(ctx, -3); IMP_SCRIPT_CLASS_END WebSocket::WebSocket() :_bev(nullptr),_bodyType(WebSocketTypeNone) ,_state(WebSocketStateNone),_bodyLength(0) { _body = evbuffer_new(); } WebSocket::~WebSocket() { if(_bev != nullptr) { bufferevent_free(_bev); _bev = nullptr; } evbuffer_free(_body); } void WebSocket::close() { if(_bev != nullptr) { bufferevent_free(_bev); _bev = nullptr; } } void WebSocket_data_rd(struct bufferevent *bev, void *ctx) { WebSocket * v = (WebSocket *) ctx; v->onReading(); } void WebSocket_data_wd(struct bufferevent *bev, void *ctx) { WebSocket * v = (WebSocket *) ctx; v->onWritting(); } void WebSocket_event_cb(struct bufferevent *bev, short what, void *ctx) { WebSocket * v = (WebSocket *) ctx; if(what & BEV_EVENT_CONNECTED) { v->onConnected(); } else if(what & (BEV_EVENT_ERROR | BEV_EVENT_TIMEOUT)){ v->onClose(nullptr); } } void WebSocket_evdns_cb (int result, char type, int count, int ttl, void *addresses, void *arg) { WebSocket * v = (WebSocket *) arg; struct in_addr * addr = (struct in_addr *) addresses; if(result == DNS_ERR_NONE && count > 0) { v->onResolve(addr); } else { v->onClose("域名解析错误"); } } void WebSocket::onResolve(struct in_addr * addr){ if(_state == WebSocketStateNone) { _state = WebSocketStateResolve; _addr.sin_addr = * addr; bufferevent_socket_connect(_bev, (struct sockaddr *) &_addr, sizeof(struct sockaddr_in)); } } void WebSocket::onConnected() { if(_state == WebSocketStateResolve) { _state = WebSocketStateConnected; bufferevent_enable(_bev, EV_WRITE); } } void WebSocket::onWritting() { if(_state == WebSocketStateConnected) { bufferevent_enable(_bev, EV_READ); } } void WebSocket::onData(WebSocketType type,void * data,size_t length) { if(type == WebSocketTypePing) { } else { { std::map<duk_context *,void *>::iterator i = _heapptrs.begin(); while(i != _heapptrs.end()) { duk_context * ctx = i->first; duk_push_heapptr(ctx, i->second); duk_push_sprintf(ctx, "_ondata"); duk_get_prop(ctx, -2); if(duk_is_function(ctx, -1)) { if(type == WebSocketTypeText) { duk_push_lstring(ctx, (const char *) data,length); if(duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) { kk::script::Error(ctx, -1); } } else { void * d = duk_push_fixed_buffer(ctx, length); memcpy(d, data, length); duk_push_buffer_object(ctx, -1, 0, length, DUK_BUFOBJ_UINT8ARRAY); duk_remove(ctx, -2); if(DUK_EXEC_SUCCESS != duk_pcall(ctx, 1)) { kk::script::Error(ctx, -1); } } } duk_pop_n(ctx, 2); i ++; } } } } void WebSocket::onReading() { if(_state == WebSocketStateConnected) { evbuffer * data = bufferevent_get_input(_bev); char * s = (char *) EVBUFFER_DATA(data); char * e = s + EVBUFFER_LENGTH(data); char * p = s; int n = 0; while(p != e) { if(*p == '\r') { } else if(*p == '\n') { n++; if(n == 2) { p ++; break; } } else { n = 0; } p ++ ; } if(n == 2) { int code = 0; char status[128]; sscanf(s, "HTTP/1.1 %d %[^\r\n]\r\n",&code,status); evbuffer_drain(data, p - s); if(code == 101) { onOpen(); return; } else { onClose(status); return ; } } bufferevent_enable(_bev, EV_READ); } else if(_state == WebSocketStateOpened) { evbuffer * data = bufferevent_get_input(_bev); uint8_t * p = EVBUFFER_DATA(data); size_t n = EVBUFFER_LENGTH(data); if(_bodyType != WebSocketTypeNone && _bodyLength > 0 && n > 0) { ssize_t v = (ssize_t) _bodyLength - (ssize_t) EVBUFFER_LENGTH(_body); if(v > 0 && n >= v) { evbuffer_add(_body, p, v); evbuffer_drain(data, v); p = EVBUFFER_DATA(data); n = EVBUFFER_LENGTH(data); } if(EVBUFFER_LENGTH(_body) == _bodyLength){ onData(_bodyType, EVBUFFER_DATA(_body), EVBUFFER_LENGTH(_body)); evbuffer_drain(_body, EVBUFFER_LENGTH(_body)); _bodyType = WebSocketTypeNone; _bodyLength = 0; } else { bufferevent_enable(_bev, EV_READ); return; } } if(n >= 2) { bool isFin = (KKFinMask & p[0]); uint8_t receivedOpcode = KKOpCodeMask & p[0]; bool isMasked = (KKMaskMask & p[1]); uint8_t payloadLen = (KKPayloadLenMask & p[1]); int offset = 2; if((isMasked || (KKRSVMask & p[0])) && receivedOpcode != WebSocketOpCodePong) { this->onClose("不支持的协议"); this->close(); return; } bool isControlFrame = (receivedOpcode == WebSocketOpCodeConnectionClose || receivedOpcode == WebSocketOpCodePing); if(!isControlFrame && (receivedOpcode != WebSocketOpCodeBinaryFrame && receivedOpcode != WebSocketOpCodeContinueFrame && receivedOpcode != WebSocketOpCodeTextFrame && receivedOpcode != WebSocketOpCodePong)) { this->onClose("不支持的协议"); this->close(); return; } if(isControlFrame && !isFin) { this->onClose("不支持的协议"); this->close(); return; } if(receivedOpcode == WebSocketOpCodeConnectionClose) { this->onClose(nullptr); this->close(); return; } if(isControlFrame && payloadLen > 125) { this->onClose("不支持的协议"); this->close(); return; } uint64_t dataLength = payloadLen; if(payloadLen == 127) { dataLength = ntohll((*(uint64_t *)(p+offset))); offset += sizeof(uint64_t); } else if(payloadLen == 126) { dataLength = ntohs(*(uint16_t *)(p+offset)); offset += sizeof(uint16_t); } if(n < offset) { // we cannot process this yet, nead more header data bufferevent_enable(_bev, EV_READ); return; } uint64_t len = dataLength; if(dataLength > (n-offset) || (n - offset) < dataLength) { len = n-offset; } if(receivedOpcode == WebSocketOpCodePong) { evbuffer_drain(data, (size_t) (offset + len)); onReading(); return; } if(receivedOpcode == WebSocketOpCodeContinueFrame) { evbuffer_add(_body, p + offset, (size_t) len); evbuffer_drain(data, (size_t) (offset + len)); } else if(receivedOpcode == WebSocketOpCodeTextFrame) { _bodyType = WebSocketTypeText; evbuffer_add(_body, p + offset, (size_t) len); evbuffer_drain(data, (size_t) (offset + len)); } else if(receivedOpcode == WebSocketOpCodeBinaryFrame) { _bodyType = WebSocketTypeBinary; evbuffer_add(_body, p + offset, (size_t) len ); evbuffer_drain(data, (size_t) (offset + len) ); } else if(receivedOpcode == WebSocketOpCodePing) { _bodyType = WebSocketTypePing; evbuffer_add(_body, p + offset, (size_t) len); evbuffer_drain(data, (size_t) (offset + len) ); } else { this->onClose("不支持的协议"); this->close(); return; } if(isFin && EVBUFFER_LENGTH(_body) == dataLength) { onData(_bodyType, EVBUFFER_DATA(_body), EVBUFFER_LENGTH(_body)); evbuffer_drain(_body, EVBUFFER_LENGTH(_body)); _bodyType = WebSocketTypeNone; _bodyLength = 0; } else { _bodyLength = dataLength; } onReading(); return; } bufferevent_enable(_bev, EV_READ); } } void WebSocket::onOpen() { if(_state == WebSocketStateConnected) { _state = WebSocketStateOpened; { std::map<duk_context *,void *>::iterator i = _heapptrs.begin(); while(i != _heapptrs.end()) { duk_context * ctx = i->first; duk_push_heapptr(ctx, i->second); duk_push_sprintf(ctx, "_onopen"); duk_get_prop(ctx, -2); if(duk_is_function(ctx, -1)) { if(duk_pcall(ctx, 0) != DUK_EXEC_SUCCESS) { kk::script::Error(ctx, -1); } } duk_pop_n(ctx, 2); i ++; } } onReading(); if(EVBUFFER_LENGTH(bufferevent_get_output(_bev)) > 0) { bufferevent_enable(_bev, EV_WRITE); } } } void WebSocket::onClose(kk::CString errmsg) { if(_state != WebSocketStateClosed) { _state = WebSocketStateClosed; retain(); { std::map<duk_context *,void *> m; std::map<duk_context *,void *>::iterator i = _heapptrs.begin(); while(i != _heapptrs.end()) { duk_context * ctx = i->first; duk_push_global_object(ctx); duk_push_sprintf(ctx, "0x%x",(long) i->second); duk_push_heapptr(ctx, i->second); duk_put_prop(ctx, -3); duk_pop(ctx); m[i->first] = i->second; i ++; } i = m.begin(); while(i != m.end()) { duk_context * ctx = i->first; duk_push_heapptr(ctx, i->second); duk_push_sprintf(ctx, "_onclose"); duk_get_prop(ctx, -2); if(duk_is_function(ctx, -1)) { duk_push_string(ctx, errmsg); if(duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) { kk::script::Error(ctx, -1); } } duk_pop_n(ctx, 2); duk_push_global_object(ctx); duk_push_sprintf(ctx, "0x%x",(long) i->second); duk_del_prop(ctx, -2); duk_pop(ctx); i ++; } } if(_bev != nullptr) { bufferevent_free(_bev); _bev = nullptr; } release(); } } void WebSocket::send(void * data,size_t n) { send(data,n,WebSocketTypeBinary); } void WebSocket::send(kk::CString text) { send((void *) text, (size_t) strlen(text),WebSocketTypeText); } void WebSocket::send(void * data,size_t n,WebSocketType type) { if(_bev == nullptr) { return; } uint8_t frame[KKMaxFrameSize]; memset(frame, 0, sizeof(frame)); switch (type) { case WebSocketTypePing: frame[0] = KKFinMask | WebSocketOpCodePing; break; case WebSocketTypeText: frame[0] = KKFinMask | WebSocketOpCodeTextFrame; break; case WebSocketTypeBinary: frame[0] = KKFinMask | WebSocketOpCodeBinaryFrame; break; default: return; } uint64_t offset = 2; if(n < 126) { frame[1] |= n; } else if(n <= UINT16_MAX) { frame[1] |= 126; *((uint16_t *)(frame + offset)) = htons((uint16_t)n); offset += sizeof(uint16_t); } else { frame[1] |= 127; *((uint64_t *)(frame + offset)) = htonll((uint64_t)n); offset += sizeof(uint64_t); } frame[1] |= KKMaskMask; uint8_t *mask_key = (frame + offset); for(int i=0;i<sizeof(uint32_t);i++) { mask_key[i] = rand(); } offset += sizeof(uint32_t); evbuffer * output = bufferevent_get_output(_bev); evbuffer_add(output, frame, (size_t) offset); uint8_t * p = (uint8_t *) data; uint8_t u; for(int i=0;i<n;i++) { u = p[i] ^ mask_key[i % sizeof(uint32_t)]; evbuffer_add(output, &u, 1); } bufferevent_enable(_bev, EV_WRITE); } kk::Boolean WebSocket::open(event_base * base,evdns_base * dns, kk::CString url,kk::CString protocol) { evhttp_uri * uri = evhttp_uri_parse(url); if(uri == nullptr) { _errmsg = "错误的URL"; return false; } kk::String host = evhttp_uri_get_host(uri); kk::String origin = evhttp_uri_get_scheme(uri); kk::String path = evhttp_uri_get_path(uri); if(path == "") { path = "/"; } kk::String query = evhttp_uri_get_query(uri); if(query != "") { path.append("?"); path.append(query); } if(origin == "ws") { origin = "http"; } if(origin == "wss") { origin = "https"; } origin.append("://"); origin.append(host); char fmt[64]; int port = evhttp_uri_get_port(uri); if(port == 0) { port = 80; } else { host.append(":"); snprintf(fmt, sizeof(fmt), "%d",port); host.append(fmt); origin.append(":"); origin.append(fmt); } memset(&_addr, 0, sizeof(_addr)); _addr.sin_family = AF_INET; _addr.sin_port = htons(port); _bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE); bufferevent_setcb(_bev, WebSocket_data_rd, WebSocket_data_wd, WebSocket_event_cb, this); bufferevent_setwatermark(_bev, EV_READ | EV_WRITE, 0, MAX_BUF_SIZE); evbuffer * data = bufferevent_get_output(_bev); evbuffer_add_printf(data, "GET %s HTTP/1.1\r\n", path.c_str()); evbuffer_add_printf(data, "Host: %s\r\n",host.c_str()); evbuffer_add_printf(data, "Upgrade: %s\r\n","websocket"); evbuffer_add_printf(data, "Connection: %s\r\n","Upgrade"); evbuffer_add_printf(data, "Origin: %s\r\n",origin.c_str()); evbuffer_add_printf(data, "Sec-WebSocket-Key: %s\r\n",Sec_WebSocket_Key); evbuffer_add_printf(data, "Sec-WebSocket-Version: %s\r\n","13"); evbuffer_add_printf(data, "\r\n"); struct in_addr addr; addr.s_addr = inet_addr(evhttp_uri_get_host(uri)); if(addr.s_addr == INADDR_NONE) { evdns_base_resolve_ipv4(dns, evhttp_uri_get_host(uri), 0, WebSocket_evdns_cb, this); } else { onResolve(&addr); } evhttp_uri_free(uri); return true; } duk_ret_t WebSocket::duk_on(duk_context * ctx) { void *heapptr = this->heapptr(ctx); if(heapptr) { int top = duk_get_top(ctx); if(top > 0 && duk_is_string(ctx, -top) ) { const char *name = duk_to_string(ctx, -top); if(top > 1 && duk_is_function(ctx, -top + 1)) { duk_push_heapptr(ctx, heapptr); duk_push_sprintf(ctx, "_on%s",name); duk_dup(ctx, - top + 1 - 2); duk_put_prop(ctx, -3); duk_pop(ctx); } else { duk_push_heapptr(ctx, heapptr); duk_push_sprintf(ctx, "_on%s",name); duk_del_prop(ctx, -2); duk_pop(ctx); } } } return 0; } duk_ret_t WebSocket::duk_close(duk_context * ctx) { close(); return 0; } duk_ret_t WebSocket::duk_send(duk_context * ctx) { int top = duk_get_top(ctx); if(top >0 ) { if(duk_is_string(ctx, - top)) { send(duk_to_string(ctx, -top)); } else if(duk_is_buffer_data(ctx, -top)) { duk_size_t n; void * bytes = duk_get_buffer_data(ctx, - top, &n); send(bytes, n); } } return 0; } }
31.739369
224
0.428732
[ "object" ]
4e6be87b274d32f163a0f143a67748568e74d065
1,563
cpp
C++
main.cpp
Ruddernation-Designs/Matrix
13542558b03f28864777f8ac795baae2740f7656
[ "MIT" ]
1
2017-12-28T00:29:23.000Z
2017-12-28T00:29:23.000Z
main.cpp
Ruddernation-Designs/Matrix
13542558b03f28864777f8ac795baae2740f7656
[ "MIT" ]
null
null
null
main.cpp
Ruddernation-Designs/Matrix
13542558b03f28864777f8ac795baae2740f7656
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include "Matrix.h" int main() { RemoveCursor(); // Set the console title and double the consoles height #if (_WIN32_WINNT == _WIN32_WINNT_WINXP) if (!SetConsoleTitle("Matrix - Win32 Console")) { std::cout << "SetConsoleTitle returned an error: " << GetLastError(); } SMALL_RECT windowSize = { 0, 0, 79, 49 }; if (!SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &windowSize)) { std::cout << "SetConsoleWindowInfo returned an error: " << GetLastError(); } #else // Windows Vista/7 have disabled FULL SCREEN ShowWindow(GetConsoleWindow(), SW_MAXIMIZE); #endif std::vector<Matrix>matrix; /* matrix.push_back(Matrix(0, 0, 5, 15)); matrix.push_back(Matrix(65, 0, 5, 15)); matrix.push_back(Matrix(0, 0, 5, 15)); matrix.push_back(Matrix(65, 0, 5, 15)); matrix.push_back(Matrix(0, 0, 5, 15)); matrix.back().setErase(true); matrix.push_back(Matrix(65, 0, 5, 15)); matrix.back().setErase(true); matrix.push_back(Matrix(0, 0, 5, 15)); matrix.back().setErase(true); matrix.push_back(Matrix(65, 0, 5, 15)); matrix.back().setErase(true); */ for (int y = 0; y < 15; y++) { matrix.push_back(Matrix()); } for (int z = 0; z < 5; z++) { matrix.push_back(Matrix()); matrix.at(z).setErase(true); } while (1) { Sleep(1); for (int x = 0; x < matrix.size(); x++) { matrix.at(x).display(); } } return 0; }
27.421053
88
0.581574
[ "vector" ]
4e722b79776c6965b58a43f1759a8cb72b78c432
603
cpp
C++
Cplus/MostBeautifulItemforEachQuery.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
1
2018-01-22T12:06:28.000Z
2018-01-22T12:06:28.000Z
Cplus/MostBeautifulItemforEachQuery.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
Cplus/MostBeautifulItemforEachQuery.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
#include <algorithm> #include <vector> using namespace std; class Solution { public: vector<int> maximumBeauty(vector<vector<int>> &items, vector<int> &queries) { int N = queries.size(); vector<int> res(N); sort(items.begin(), items.end()); vector<pair<int, int>> v; //{price,index} for (int i = 0; i < N; ++i) v.push_back({queries[i], i}); sort(v.begin(), v.end()); int beauty = 0; for (int i = 0, j = 0; i < N; ++i) { for (; j < (int)items.size() && items[j][0] <= v[i].first; ++j) beauty = max(beauty, items[j][1]); res[v[i].second] = beauty; } return res; } };
23.192308
76
0.573798
[ "vector" ]
4e7589c3a795328857202b310901b7a2f3455314
13,785
cc
C++
src/tir/transforms/hoist_if_then_else.cc
janifer112x/incubator-tvm
98c2096f4944bdbdbbb2b7b20ccd35c6c11dfbf6
[ "Apache-2.0" ]
22
2022-03-18T07:29:31.000Z
2022-03-23T14:54:32.000Z
src/tir/transforms/hoist_if_then_else.cc
janifer112x/incubator-tvm
98c2096f4944bdbdbbb2b7b20ccd35c6c11dfbf6
[ "Apache-2.0" ]
3
2020-04-20T15:37:55.000Z
2020-05-13T05:34:28.000Z
src/tir/transforms/hoist_if_then_else.cc
janifer112x/incubator-tvm
98c2096f4944bdbdbbb2b7b20ccd35c6c11dfbf6
[ "Apache-2.0" ]
2
2022-03-18T08:26:34.000Z
2022-03-20T06:02:48.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file hoist_if_then_else.cc */ #include <tvm/arith/analyzer.h> #include <tvm/runtime/registry.h> #include <tvm/tir/expr.h> #include <tvm/tir/stmt_functor.h> #include <tvm/tir/transform.h> #include <queue> #include <unordered_map> #include <unordered_set> #include "../../arith/interval_set.h" #include "../../runtime/thread_storage_scope.h" #include "ir_util.h" namespace tvm { namespace tir { struct HoistIfThenElseConfigNode : public tvm::AttrsNode<HoistIfThenElseConfigNode> { bool support_block_scope_hosting; TVM_DECLARE_ATTRS(HoistIfThenElseConfigNode, "tir.transform.HoistIfThenElseConfig") { TVM_ATTR_FIELD(support_block_scope_hosting) .describe("Hoist if cond with block scope variables") .set_default(false); } }; class HoistIfThenElseConfig : public Attrs { public: TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(HoistIfThenElseConfig, Attrs, HoistIfThenElseConfigNode); }; TVM_REGISTER_NODE_TYPE(HoistIfThenElseConfigNode); TVM_REGISTER_PASS_CONFIG_OPTION("tir.HoistIfThenElse", HoistIfThenElseConfig); using VarForMap = std::unordered_map<const VarNode*, const ForNode*>; using HoistForIfTuple = std::tuple<bool, const ForNode*, const IfThenElseNode*>; /* * This pass tries to hoist IfThenElse stmt out of For loop if condition is loop invariant. * For example, given the following block: * for (i = 0; i < 3; i++) * for (j = 0; j < 4; j++) * for (k = 0; k < 5; k++) * if (likely(i*2 < 4)) * A[3*i+2j+k] = B[7*i+3j+k] * * We first detect all IfThenElse stmt and find the corresponding loop invariant For stmt. * Then we hoist IfThenElse stmt by one For stmt each step: * * Step 1: * for (i = 0; i < 3; i++) * for (j = 0; j < 4; j++) * if (likely(i*2 < 4)) * for (k = 0; k < 5; k++) * A[3*i+2j+k] = B[7*i+3j+k] * * Step 2: * for (i = 0; i < 3; i++) * if (likely(i*2 < 4)) * for (j = 0; j < 4; j++) * for (k = 0; k < 5; k++) * A[3*i+2j+k] = B[7*i+3j+k] * * In this pass, we only continue detecting possible hoisting chance when visiting For, * IfThenElse or AttrStmt Node. For example, for the following block: * for (i = 0; i < 3; i++) * for (j = 0; j < 4; j++) * A[i + j] = A[i + j] - 1 * for (k = 0; k < 5; k++) * if (likely(i*2 < 4)) * A[3*i+2j+k] = B[7*i+3j+k] * * Only the For with k variable will be considered and the resulting stmt would be: * for (i = 0; i < 3; i++) * for (j = 0; j < 4; j++) * A[i + j] = A[i + j] - 1 * if (likely(i*2 < 4)) * for (k = 0; k < 5; k++) * A[3*i+2j+k] = B[7*i+3j+k] * * This pass doesn't do hoisting for consecutive IfThenElse stmt. The following * block won't be optimized: * for (i = 0; i < 3; i++) * for (j = 0; j < 4; j++) * for (k = 0; k < 5; k++) * if (likely(i*2 < 4)) * A[3*i+2j+k] = B[7*i+3j+k] * if (likely(j > 2)) * A[i+j+k] = B[i+j+k] * * * This pass do hoisting for Block scope variables also. * As below: * Attr(IterVar: threadIdx.x) * for (i = 0; i < 3; i++) * for (j = 0; j < 4; j++) * for (k = 0; k < 5; k++) * if (likely(threadIdx.x < 3)) * A[3*i+2j+k] = B[7*i+3j+k] * * Will be transformed to as below: * Attr(IterVar: threadIdx.x) * if (likely(threadIdx.x < 3)) * for (i = 0; i < 3; i++) * for (j = 0; j < 4; j++) * for (k = 0; k < 5; k++) * A[3*i+2j+k] = B[7*i+3j+k] * */ // Select potential candidate IRs that can be hoisted. class HoistCandidateSelector final : public StmtExprVisitor { public: explicit HoistCandidateSelector(bool support_block_scope_hosting) : support_block_scope_hosting_(support_block_scope_hosting) { InitRecorder(); } HoistCandidateSelector() { InitRecorder(); } void VisitStmt_(const ForNode* op) final { // If already recording complete, // then stop tracing if (RecordingComplete()) { return; } // Check if it is first for loop, then start the recorder StartOrAddRecord(GetRef<ObjectRef>(op)); StmtExprVisitor::VisitStmt_(op); RemoveRecord(GetRef<ObjectRef>(op)); } void VisitStmt_(const SeqStmtNode* op) final { // If SeqStmt is encountered in the middle of recording // then need to purge all, as it can not be hoisted if (IsRecordingOn()) { ResetRecorderInternal(); } StmtExprVisitor::VisitStmt_(op); } void VisitStmt_(const AttrStmtNode* op) final { // Maintain list of all vars in AttrStmt // To stop hoisting if any of the block variables are used. // // In case we want to use hoisting in between certain passes // which have interdependencies of the postioning of if nodes with scope var // it is better to disable this section if (support_block_scope_hosting_) { if (IsRecordingOn()) { StartOrAddRecord(GetRef<ObjectRef>(op)); StmtExprVisitor::VisitStmt_(op); RemoveRecord(GetRef<ObjectRef>(op)); return; } else { return StmtExprVisitor::VisitStmt_(op); } } UpdateAttrVarList(op); StmtExprVisitor::VisitStmt_(op); RemoveAttrVarList(op); } void VisitStmt_(const IfThenElseNode* op) final { if (!IsRecordingOn()) { StmtExprVisitor::VisitStmt_(op); return; } is_if_cond_ = true; StmtExprVisitor::VisitExpr(op->condition); is_if_cond_ = false; if (CheckValidIf()) { // Check corresponding for loop int match_for_loop_pos = -1; for (auto var : if_var_list_) { for (int i = 0; i < static_cast<int>(ordered_list_.size()); ++i) { if ((ordered_list_[i] == var_for_map_[var]) || (ordered_list_[i] == var)) { if (match_for_loop_pos < i) { match_for_loop_pos = i; } } } } // If none of the for loop has the matching loop variable as if condition, // then the if node need to be hoisted on top of all, provided no parent loop exists. int target_for_pos = GetNextLoopPos(match_for_loop_pos); // Check if valid position if (target_for_pos >= 0) { StopAndAddRecord(static_cast<const ForNode*>(ordered_list_[target_for_pos]), op); if_var_list_.clear(); return; } } if_var_list_.clear(); StmtExprVisitor::VisitStmt_(op); StopRecording(); } void VisitExpr_(const VarNode* op) final { if (is_if_cond_) { if_var_list_.emplace_back(op); } } HoistForIfTuple hoist_for_if_recorder; void ResetRecorder() { ResetRecorderInternal(); // Reset Block scope vars also here attr_var_list_.clear(); } bool RecordingComplete() { return std::get<0>(hoist_for_if_recorder); } const ForNode* GetTargetForNode() { return std::get<1>(hoist_for_if_recorder); } const IfThenElseNode* GetTargetIfNode() { return std::get<2>(hoist_for_if_recorder); } private: void ResetRecorderInternal() { if (is_recorder_on_) { CHECK_GT(ordered_list_.size(), 0); is_recorder_on_ = false; } ordered_list_.clear(); var_for_map_.clear(); hoist_for_if_recorder = std::make_tuple(false, nullptr, nullptr); } bool CheckValidIf() { // If no if var list is present, then all the condition vars are possibly from AttrStmt, so stop // hoisting return ((!if_var_list_.empty()) && (!CheckAttrVar())); } int GetNextLoopPos(int cur_pos) { for (size_t i = cur_pos + 1; i < ordered_list_.size(); ++i) { if (ordered_list_[i]->IsInstance<ForNode>()) { return i; } } return -1; } void InitRecorder() { hoist_for_if_recorder = std::make_tuple(false, nullptr, nullptr); } void StopRecording() { is_recorder_on_ = false; } bool IsRecordingOn() { return is_recorder_on_; } void StartOrAddRecord(const ObjectRef& op) { is_recorder_on_ = true; if (const auto* node = op.as<ForNode>()) { if (!var_for_map_.count(node->loop_var.get())) var_for_map_.insert({node->loop_var.get(), node}); ordered_list_.emplace_back(op.get()); } else if (const auto* node = op.as<AttrStmtNode>()) { if (const auto* iv = node->node.as<IterVarNode>()) { ordered_list_.emplace_back(iv->var.get()); } else if (const auto* iv = node->node.as<VarNode>()) { ordered_list_.emplace_back(iv); } } } void RemoveRecord(const ObjectRef& op) { StopRecording(); if (const auto* node = op.as<ForNode>()) var_for_map_.erase(node->loop_var.get()); if (ordered_list_.size() > 0) ordered_list_.pop_back(); } void StopAndAddRecord(const ForNode* for_node, const IfThenElseNode* if_node) { hoist_for_if_recorder = std::make_tuple(true, for_node, if_node); StopRecording(); } void UpdateAttrVarList(const AttrStmtNode* op) { if (const auto* iv = op->node.as<IterVarNode>()) { attr_var_list_.insert(iv->var.get()); } else if (const auto* iv = op->node.as<VarNode>()) { attr_var_list_.insert(iv); } } void RemoveAttrVarList(const AttrStmtNode* op) { if (const auto* iv = op->node.as<IterVarNode>()) { attr_var_list_.erase(iv->var.get()); } else if (const auto* iv = op->node.as<VarNode>()) { attr_var_list_.erase(iv); } } bool CheckAttrVar() { for (auto var : if_var_list_) { if (attr_var_list_.count(var)) { return true; } } return false; } // Ordered List maintains all ForNodes & AttrStmtNodes encountered in sequence std::vector<const Object*> ordered_list_; std::vector<const VarNode*> if_var_list_; std::unordered_set<const VarNode*> attr_var_list_; VarForMap var_for_map_; bool is_if_cond_{false}; bool is_recorder_on_{false}; bool support_block_scope_hosting_{false}; }; class IfThenElseHoister : public StmtMutator { public: IfThenElseHoister() : hoist_selector_(HoistCandidateSelector()) {} explicit IfThenElseHoister(bool support_block_scope_hosting) : hoist_selector_(HoistCandidateSelector(support_block_scope_hosting)) {} Stmt VisitAndMutate(Stmt stmt) { hoist_selector_(stmt); Stmt stmt_copy = std::move(stmt); while (hoist_selector_.RecordingComplete()) { target_for_ = hoist_selector_.GetTargetForNode(); target_if_ = hoist_selector_.GetTargetIfNode(); stmt_copy = operator()(stmt_copy); hoist_selector_.ResetRecorder(); hoist_selector_(stmt_copy); } // Support SSA Form stmt_copy = ConvertSSA(stmt_copy); return stmt_copy; } Stmt VisitStmt_(const ForNode* op) final { if ((!is_updating_) && (target_for_ == op)) { is_updating_ = true; is_then_case_ = true; Stmt then_case = StmtMutator::VisitStmt_(op); is_then_case_ = false; Stmt else_case = Stmt(); if (target_if_->else_case.defined()) { else_case = StmtMutator::VisitStmt_(op); } is_updating_ = false; return IfThenElse(target_if_->condition, then_case, else_case); } return StmtMutator::VisitStmt_(op); } Stmt VisitStmt_(const IfThenElseNode* op) final { if (is_updating_ && (target_if_ == op)) { if (is_then_case_) { return StmtMutator::VisitStmt(op->then_case); } else if (op->else_case.defined()) { return StmtMutator::VisitStmt(op->else_case); } } return StmtMutator::VisitStmt_(op); } private: bool is_updating_{false}; bool is_then_case_{false}; HoistCandidateSelector hoist_selector_; const ForNode* target_for_; const IfThenElseNode* target_if_; }; Stmt HoistIfThenElse(Stmt stmt, bool support_block_scope_hosting) { return IfThenElseHoister(support_block_scope_hosting).VisitAndMutate(stmt); } Stmt HoistIfThenElse(Stmt stmt) { return IfThenElseHoister().VisitAndMutate(stmt); } namespace transform { Pass HoistIfThenElse() { auto pass_func = [=](PrimFunc f, IRModule m, PassContext ctx) { auto* n = f.CopyOnWrite(); auto cfg = ctx->GetConfig<HoistIfThenElseConfig>("tir.HoistIfThenElse"); if (!cfg.defined()) { cfg = AttrsWithDefaultValues<HoistIfThenElseConfig>(); } n->body = HoistIfThenElse(std::move(n->body), cfg.value()->support_block_scope_hosting); return f; }; return CreatePrimFuncPass(pass_func, 0, "tir.HoistIfThenElse", {}); } Pass HoistIfThenElseBasic() { auto pass_func = [=](PrimFunc f, IRModule m, PassContext ctx) { auto* n = f.CopyOnWrite(); n->body = HoistIfThenElse(std::move(n->body)); return f; }; return CreatePrimFuncPass(pass_func, 0, "tir.HoistIfThenElseBasic", {}); } TVM_REGISTER_GLOBAL("tir.transform.HoistIfThenElse").set_body_typed(HoistIfThenElse); TVM_REGISTER_GLOBAL("tir.transform.HoistIfThenElseBasic").set_body_typed(HoistIfThenElseBasic); } // namespace transform } // namespace tir } // namespace tvm
31.400911
100
0.642075
[ "object", "vector", "transform" ]
4e7887e77e2eab4b19565a43560dd92e6c86b0d0
3,622
cpp
C++
aws-cpp-sdk-datasync/source/model/CreateLocationHdfsRequest.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-datasync/source/model/CreateLocationHdfsRequest.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-datasync/source/model/CreateLocationHdfsRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/datasync/model/CreateLocationHdfsRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/utils/HashingUtils.h> #include <utility> using namespace Aws::DataSync::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateLocationHdfsRequest::CreateLocationHdfsRequest() : m_subdirectoryHasBeenSet(false), m_nameNodesHasBeenSet(false), m_blockSize(0), m_blockSizeHasBeenSet(false), m_replicationFactor(0), m_replicationFactorHasBeenSet(false), m_kmsKeyProviderUriHasBeenSet(false), m_qopConfigurationHasBeenSet(false), m_authenticationType(HdfsAuthenticationType::NOT_SET), m_authenticationTypeHasBeenSet(false), m_simpleUserHasBeenSet(false), m_kerberosPrincipalHasBeenSet(false), m_kerberosKeytabHasBeenSet(false), m_kerberosKrb5ConfHasBeenSet(false), m_agentArnsHasBeenSet(false), m_tagsHasBeenSet(false) { } Aws::String CreateLocationHdfsRequest::SerializePayload() const { JsonValue payload; if(m_subdirectoryHasBeenSet) { payload.WithString("Subdirectory", m_subdirectory); } if(m_nameNodesHasBeenSet) { Array<JsonValue> nameNodesJsonList(m_nameNodes.size()); for(unsigned nameNodesIndex = 0; nameNodesIndex < nameNodesJsonList.GetLength(); ++nameNodesIndex) { nameNodesJsonList[nameNodesIndex].AsObject(m_nameNodes[nameNodesIndex].Jsonize()); } payload.WithArray("NameNodes", std::move(nameNodesJsonList)); } if(m_blockSizeHasBeenSet) { payload.WithInteger("BlockSize", m_blockSize); } if(m_replicationFactorHasBeenSet) { payload.WithInteger("ReplicationFactor", m_replicationFactor); } if(m_kmsKeyProviderUriHasBeenSet) { payload.WithString("KmsKeyProviderUri", m_kmsKeyProviderUri); } if(m_qopConfigurationHasBeenSet) { payload.WithObject("QopConfiguration", m_qopConfiguration.Jsonize()); } if(m_authenticationTypeHasBeenSet) { payload.WithString("AuthenticationType", HdfsAuthenticationTypeMapper::GetNameForHdfsAuthenticationType(m_authenticationType)); } if(m_simpleUserHasBeenSet) { payload.WithString("SimpleUser", m_simpleUser); } if(m_kerberosPrincipalHasBeenSet) { payload.WithString("KerberosPrincipal", m_kerberosPrincipal); } if(m_kerberosKeytabHasBeenSet) { payload.WithString("KerberosKeytab", HashingUtils::Base64Encode(m_kerberosKeytab)); } if(m_kerberosKrb5ConfHasBeenSet) { payload.WithString("KerberosKrb5Conf", HashingUtils::Base64Encode(m_kerberosKrb5Conf)); } if(m_agentArnsHasBeenSet) { Array<JsonValue> agentArnsJsonList(m_agentArns.size()); for(unsigned agentArnsIndex = 0; agentArnsIndex < agentArnsJsonList.GetLength(); ++agentArnsIndex) { agentArnsJsonList[agentArnsIndex].AsString(m_agentArns[agentArnsIndex]); } payload.WithArray("AgentArns", std::move(agentArnsJsonList)); } if(m_tagsHasBeenSet) { Array<JsonValue> tagsJsonList(m_tags.size()); for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) { tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize()); } payload.WithArray("Tags", std::move(tagsJsonList)); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection CreateLocationHdfsRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "FmrsService.CreateLocationHdfs")); return headers; }
25.152778
130
0.756212
[ "model" ]
4e7aa3b1fe1e09d0eff3c387e73e46496b891a28
2,698
cpp
C++
Robotron/Source/DirectX9Framework/Actor/TransformComponent.cpp
ThatBeanBag/Slimfish
7b0f821bccf2cae7d67f8a822f078def7a2d354d
[ "Apache-2.0" ]
null
null
null
Robotron/Source/DirectX9Framework/Actor/TransformComponent.cpp
ThatBeanBag/Slimfish
7b0f821bccf2cae7d67f8a822f078def7a2d354d
[ "Apache-2.0" ]
null
null
null
Robotron/Source/DirectX9Framework/Actor/TransformComponent.cpp
ThatBeanBag/Slimfish
7b0f821bccf2cae7d67f8a822f078def7a2d354d
[ "Apache-2.0" ]
null
null
null
// // Bachelor of Software Engineering // Media Design School // Auckland // New Zealand // // (c) 2005 - 2015 Media Design School // // File Name : TransformComponent.cpp // Description : CTransformComponent implementation file. // Author : Hayden Asplet. // Mail : hayden.asplet@mediadesignschool.com // // PCH #include "GameStd.h" // Library Includes // This Include #include "TransformComponent.h" #include "../3rdParty/tinyxml/tinyxml.h" // Local Includes #include "PhysicsComponent.h" const std::string CTransformComponent::s_kstrNAME = "TransformComponent"; CTransformComponent::CTransformComponent() { } CTransformComponent::~CTransformComponent() { } bool CTransformComponent::VInitialise(TiXmlElement* _pXmlData) { // Create the initial transform from the scale rotation and translation information. m_matTransform = CreateTransformFromXML(_pXmlData); m_matInitialTransform = m_matTransform; TiXmlElement* pElement = _pXmlData->FirstChildElement("Spawns"); if (pElement) { for (TiXmlElement* pNode = pElement->FirstChildElement(); pNode; pNode = pNode->NextSiblingElement()) { double dX = 0.0; double dY = 0.0; double dZ = 0.0; pNode->Attribute("x", &dX); pNode->Attribute("y", &dY); pNode->Attribute("z", &dZ); m_vecSpawnPositions.push_back(CVec3(static_cast<float>(dX), static_cast<float>(dY), static_cast<float>(dZ))); } if (!m_vecSpawnPositions.empty()) { // Select and random spawn from the spawn locations. int iRandomSpawn = g_pApp->GetRandomNumber(0, m_vecSpawnPositions.size()); // Set the spawn. m_matTransform.SetPosition(m_vecSpawnPositions[iRandomSpawn]); } } return true; } const CMatrix4x4 CTransformComponent::GetTransform() const { return m_matTransform; } void CTransformComponent::SetTransform(const CMatrix4x4& _krmatTransform) { m_matTransform = _krmatTransform; } void CTransformComponent::SetPosition(const CVec3& _krVec3) { m_matTransform.SetPosition(_krVec3); } const CVec3 CTransformComponent::GetPosition() const { return m_matTransform.GetPosition(); } void CTransformComponent::RespawnRandom() { if (m_vecSpawnPositions.empty()) { return; } int iRandomSpawn = g_pApp->GetRandomNumber(0, m_vecSpawnPositions.size()); Respawn(iRandomSpawn); } void CTransformComponent::Respawn(int _iSpawnPoint) { CMatrix4x4 matRespawn = m_matInitialTransform; matRespawn.SetPosition(m_vecSpawnPositions[_iSpawnPoint]); CPhysicsComponent* pPhysicsComponent = GetOwner()->GetComponent<CPhysicsComponent>(); if (pPhysicsComponent) { // If we have physics set the transform on the physics component. pPhysicsComponent->SetTransform(matRespawn); } m_matTransform = matRespawn; }
23.258621
112
0.750556
[ "transform" ]
4e7e270e20313e3b62b8154d86e5f7e51028aa9e
13,155
cpp
C++
src/core/renderer/particles.cpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
src/core/renderer/particles.cpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
src/core/renderer/particles.cpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
#define BUILD_SERIALIZER #define GLM_SWIZZLE #include "particles.hpp" #include "texture.hpp" #include "vertex_object.hpp" #include "../utils/random.hpp" #include "../utils/sf2_glm.hpp" #include <vector> namespace lux { namespace renderer { using namespace unit_literals; sf2_structDef(Float_range, min, max ) sf2_structDef(Attractor_plane, normal, force) sf2_structDef(Attractor_point, point, force) sf2_structDef(Particle_type, id, physics_simulation, mass, texture, animation_frames, fps, hue_change_in, initial_alpha, final_alpha, initial_opacity, final_opacity, initial_size, final_size, rotation, lifetime, emision_rate, max_particle_count, spawn_x, spawn_y, spawn_z, initial_pitch, initial_yaw, initial_roll, speed_pitch, speed_yaw, speed_roll, speed_pitch_global, speed_yaw_global, speed_roll_global, initial_speed, final_speed, attractor_plane, attractor_point, source_velocity_conservation ) namespace { struct Particle_draw { glm::vec3 position; glm::vec3 direction; float rotation; float frames; float current_frame; float size; float alpha; float opacity; float hue_change_out; }; Vertex_layout simple_particle_vertex_layout { Vertex_layout::Mode::points, vertex("position", &Particle_draw::position), vertex("direction", &Particle_draw::direction), vertex("rotation", &Particle_draw::rotation), vertex("frames", &Particle_draw::frames), vertex("current_frame", &Particle_draw::current_frame), vertex("size", &Particle_draw::size), vertex("alpha", &Particle_draw::alpha), vertex("opacity", &Particle_draw::opacity), vertex("hue_change_out",&Particle_draw::hue_change_out) }; struct Particle_sim { Time ttl; Time lifetime; float initial_alpha; float final_alpha; float initial_opacity; float final_opacity; float initial_size; float final_size; glm::quat source_direction; glm::quat direction; float initial_speed; float final_speed; glm::quat angular_speed_local; glm::quat angular_speed_global; glm::vec3 linear_speed; }; glm::quat calculate_w(float pitch, float yaw, float roll) { return glm::quat(0, roll, pitch, yaw); } auto rng = util::create_random_generator(); auto rand_val(Float_range r) { return util::random_real(rng, r.min, r.max); } } class Simple_particle_emitter : public Particle_emitter { public: Simple_particle_emitter(asset::Asset_manager& assets, const Particle_type& type) : Particle_emitter(type), _obj(simple_particle_vertex_layout, create_dynamic_buffer<Particle_draw>(type.max_particle_count)) { _texture = assets.load<Texture>(asset::AID{type.texture}); _particles_draw.reserve(type.max_particle_count * _scale); _particles_sim.reserve(type.max_particle_count * _scale); } auto texture()const noexcept -> const Texture* override {return &*_texture;} void update(Time dt) override { INVARIANT(_particles_draw.size()==_particles_sim.size(), "Size mismatch in particle sim/draw buffer."); if(!_last_position_set) { _last_position_set = true; _last_position = _position; } _dt_acc += dt; auto count_scale = std::max(_scale, 0.01f); auto spawn_now = util::random_int(rng,_type.emision_rate.min, _type.emision_rate.max) * count_scale; _to_spawn = static_cast<decltype(_to_spawn)>(std::round(spawn_now * _dt_acc.value())); _dt_acc-=Time(_to_spawn/spawn_now); if(!_active) { _to_spawn = 0; } _reap(dt); _spawn(); _simulation(dt); if(!_particles_draw.empty()) _obj.buffer().set(_particles_draw); _last_position = _position; } bool draw(Command& cmd)const override { if(!_particles_draw.empty()) { cmd.object(_obj).texture(Texture_unit::color, *_texture); return true; } return false; } bool dead()const noexcept override {return !_active && _particles_draw.empty();} private: Texture_ptr _texture; Object _obj; std::vector<Particle_draw> _particles_draw; std::vector<Particle_sim> _particles_sim; int_fast32_t _to_spawn; Time _dt_acc{0}; glm::vec3 _last_position; bool _last_position_set = false; void _reap(Time dt) { auto to_spawn = _to_spawn; auto new_end = int_fast32_t(_particles_sim.size()); for(auto i=0; i<new_end; i++) { auto& curr = _particles_sim[i]; curr.ttl-=dt; auto dead = curr.ttl<=0_s; if(dead) { if(to_spawn>0) { _spawn_particle_at(i); to_spawn--; } else { std::swap(_particles_sim[i], _particles_sim[new_end-1]); std::swap(_particles_draw[i], _particles_draw[new_end-1]); i--; new_end--; } } } if(static_cast<std::size_t>(new_end) < _particles_sim.size()) { _particles_sim.erase(_particles_sim.begin()+new_end, _particles_sim.end()); _particles_draw.erase(_particles_draw.begin()+new_end, _particles_draw.end()); } _to_spawn = to_spawn; } void _spawn() { using IT = decltype(_to_spawn); auto count_scale = std::max(_scale, 0.01f); auto max_spawn = static_cast<IT>(_type.max_particle_count * count_scale - _particles_sim.size()); _to_spawn = std::max(static_cast<IT>(0), std::min(_to_spawn, max_spawn)); for(auto i : util::range(_to_spawn)) { (void)i; _particles_sim.emplace_back(); _particles_draw.emplace_back(); _spawn_particle_at(_particles_sim.size()-1); } } void _spawn_particle_at(int_fast32_t idx) { Particle_sim& sim = _particles_sim[idx]; sim.ttl = sim.lifetime = rand_val(_type.lifetime) * second; sim.initial_alpha = rand_val(_type.initial_alpha); sim.final_alpha = rand_val(_type.final_alpha); sim.initial_opacity = rand_val(_type.initial_opacity); sim.final_opacity = rand_val(_type.final_opacity); sim.initial_size = rand_val(_type.initial_size); sim.final_size = rand_val(_type.final_size); sim.initial_speed = rand_val(_type.initial_speed); sim.final_speed = rand_val(_type.final_speed) ; sim.angular_speed_local = calculate_w( rand_val(_type.speed_pitch), rand_val(_type.speed_yaw), rand_val(_type.speed_roll) ); sim.angular_speed_global = calculate_w( rand_val(_type.speed_pitch_global), rand_val(_type.speed_yaw_global), rand_val(_type.speed_roll_global) ); sim.source_direction = _direction; sim.direction = glm::normalize(glm::quat(glm::vec3( rand_val(_type.initial_pitch), rand_val(_type.initial_yaw), rand_val(_type.initial_roll) ))); sim.linear_speed = (_position - _last_position) * _type.source_velocity_conservation; Particle_draw& draw = _particles_draw[idx]; draw.position = glm::mix(_last_position, _position, util::random_real(rng, 0.f, 1.f)) + glm::rotate(_direction, glm::vec3( rand_val(_type.spawn_x) * _scale, rand_val(_type.spawn_y) * _scale, rand_val(_type.spawn_z) )); draw.direction = glm::rotate(sim.direction, glm::vec3(1,0,0)); draw.rotation = rand_val(_type.rotation); draw.frames = _type.animation_frames; draw.current_frame = 0; draw.size = sim.initial_size; draw.alpha = sim.initial_alpha; draw.opacity = sim.initial_opacity; draw.hue_change_out = _hue_out / (360_deg).value(); } void _simulation(Time dt) { for(std::size_t i=0; i<_particles_sim.size(); i++) { Particle_sim& curr_sim = _particles_sim[i]; Particle_draw& curr_draw = _particles_draw[i]; auto a = 1.f - curr_sim.ttl/curr_sim.lifetime; curr_draw.alpha = glm::mix(curr_sim.initial_alpha, curr_sim.final_alpha, a); curr_draw.opacity = glm::mix(curr_sim.initial_opacity, curr_sim.final_opacity, a); curr_draw.size = glm::mix(curr_sim.initial_size, curr_sim.final_size, a); if(_type.fps<0) { curr_draw.current_frame = (curr_draw.frames-1.0)*a; } else { auto next_frame = curr_draw.current_frame + _type.fps*dt.value(); curr_draw.current_frame = std::fmod(next_frame, curr_draw.frames); } auto speed = glm::mix(curr_sim.initial_speed, curr_sim.final_speed, a); auto& q = curr_sim.direction; q = glm::normalize(q + dt.value()*0.5f * q * curr_sim.angular_speed_local); q = glm::normalize(q + dt.value()*0.5f * curr_sim.angular_speed_global * q); // TODO: attractors auto final_direction = glm::normalize(curr_sim.source_direction * q); auto dir = glm::rotate(final_direction, glm::vec3(1,0,0)); curr_draw.position += dir * speed; curr_draw.position += curr_sim.linear_speed; curr_draw.direction = dir; } } }; auto get_type(const Particle_emitter& e) -> Particle_type_id { return e.type(); } void set_position(Particle_emitter& e, glm::vec3 position) { e.position(position); } void set_direction(Particle_emitter& e, glm::vec3 euler_angles) { e.direction(euler_angles); } Particle_renderer::Particle_renderer(asset::Asset_manager& assets) { _simple_shader.attach_shader(assets.load<Shader>("vert_shader:particles"_aid)) .attach_shader(assets.load<Shader>("frag_shader:particles"_aid)) .bind_all_attribute_locations(simple_particle_vertex_layout) .build() .uniforms(make_uniform_map( "texture", int(Texture_unit::color), "shadowmaps_tex", int(Texture_unit::shadowmaps), "environment_tex", int(Texture_unit::environment), "last_frame_tex", int(Texture_unit::last_frame) )); auto type_aids = assets.list("particle"_strid); for(auto& aid : type_aids) { auto type = assets.load<Particle_type>(aid); auto id = type->id; _types.emplace(id, std::move(type)); } } auto Particle_renderer::create_emiter(Particle_type_id id) -> Particle_emitter_ptr { auto iter = _types.find(id); if(iter==_types.end()) { WARN("Created emiter of unknown type '"<<id.str()<<"'"); iter = _types.begin(); } auto emiter = Particle_emitter_ptr{}; if(iter->second->physics_simulation) { FAIL("NOT IMPLEMENTED, YET!"); } else { emiter = std::make_shared<Simple_particle_emitter>(iter->second.mgr(), *iter->second); } _emitters.emplace_back(emiter); return emiter; } void Particle_renderer::update(Time dt) { for(auto& e : _emitters) { if(e.use_count()<=1) { e->disable(); } e->update(dt); } _emitters.erase(std::remove_if(_emitters.begin(),_emitters.end(), [](auto& e){return e->dead();}), _emitters.end()); } void Particle_renderer::draw(Command_queue& queue)const { for(auto& e : _emitters) { auto cmd = create_command().shader(_simple_shader) .require_not(Gl_option::depth_write) .require(Gl_option::depth_test) .require(Gl_option::blend) .order_dependent(); cmd.uniforms().emplace("hue_change_in", e->hue_change_in() / (360_deg).value()); if(e->draw(cmd)) queue.push_back(cmd); } } void Particle_renderer::clear() { _emitters.clear(); } } namespace asset { auto Loader<renderer::Particle_type>::load(istream in) -> std::shared_ptr<renderer::Particle_type> { auto r = std::make_shared<renderer::Particle_type>(); sf2::deserialize_json(in, [&](auto &msg, uint32_t row, uint32_t column) { ERROR("Error parsing JSON from " << in.aid().str() << " at " << row << ":" << column << ": " << msg); }, *r); auto from_deg = [](float& v) { v = Angle::from_degrees(v).value(); }; from_deg(r->initial_pitch.min); from_deg(r->initial_pitch.max); from_deg(r->initial_yaw.min); from_deg(r->initial_yaw.max); from_deg(r->initial_roll.min); from_deg(r->initial_roll.max); from_deg(r->speed_pitch.min); from_deg(r->speed_pitch.max); from_deg(r->speed_yaw.min); from_deg(r->speed_yaw.max); from_deg(r->speed_roll.min); from_deg(r->speed_roll.max); from_deg(r->speed_pitch_global.min); from_deg(r->speed_pitch_global.max); from_deg(r->speed_yaw_global.min); from_deg(r->speed_yaw_global.max); from_deg(r->speed_roll_global.min); from_deg(r->speed_roll_global.max); from_deg(r->hue_change_in); return r; } void Loader<renderer::Particle_type>::store(ostream out, const renderer::Particle_type &asset) { auto to_deg = [](float& v) { v = Angle{v}.in_degrees(); }; auto r = asset; to_deg(r.initial_pitch.min); to_deg(r.initial_pitch.max); to_deg(r.initial_yaw.min); to_deg(r.initial_yaw.max); to_deg(r.initial_roll.min); to_deg(r.initial_roll.max); to_deg(r.speed_pitch.min); to_deg(r.speed_pitch.max); to_deg(r.speed_yaw.min); to_deg(r.speed_yaw.max); to_deg(r.speed_roll.min); to_deg(r.speed_roll.max); to_deg(r.speed_pitch_global.min); to_deg(r.speed_pitch_global.max); to_deg(r.speed_yaw_global.min); to_deg(r.speed_yaw_global.max); to_deg(r.speed_roll_global.min); to_deg(r.speed_roll_global.max); to_deg(r.hue_change_in); sf2::serialize_json(out, r); } } }
27.123711
118
0.678981
[ "object", "vector" ]
4e8b2a064245ad606425d63e70a4abff34418c17
36,658
cpp
C++
Katana-Plugins/LightViewerModifier/LightViewerModifier/src/LightViewerModifier.cpp
iceprincefounder/selected-sources
8e27a905ce1057d8f8f8ff44ddb746da7401c0e5
[ "Apache-2.0" ]
10
2018-08-08T21:40:14.000Z
2022-01-25T02:32:08.000Z
Katana-Plugins/LightViewerModifier/LightViewerModifier/src/LightViewerModifier.cpp
iceprincefounder/selected-sources
8e27a905ce1057d8f8f8ff44ddb746da7401c0e5
[ "Apache-2.0" ]
1
2018-08-04T11:03:26.000Z
2018-08-29T12:41:38.000Z
Katana-Plugins/LightViewerModifier/LightViewerModifier/src/LightViewerModifier.cpp
iceprincefounder/selected-sources
8e27a905ce1057d8f8f8ff44ddb746da7401c0e5
[ "Apache-2.0" ]
3
2019-11-07T06:31:06.000Z
2021-08-03T07:27:53.000Z
// Copyright (c) 2012 The Foundry Visionmongers Ltd. All Rights Reserved. #ifdef _WIN32 #include <FnPlatform/Windows.h> #define _USE_MATH_DEFINES // for C++ #include <cmath> #endif #include <FnViewerModifier/plugin/FnViewerModifier.h> #include <FnViewerModifier/plugin/FnViewerModifierInput.h> #include <FnAttribute/FnGroupBuilder.h> #include <FnAttribute/FnAttribute.h> #ifdef __APPLE__ #include <OpenGL/OpenGL.h> #include <OpenGL/glu.h> #else #include <GL/gl.h> #include <GL/glu.h> #endif #include <string> #include <iostream> #include <algorithm> #include <math.h> #include <vector> struct Vector3f { Vector3f() : x(0.0f), y(0.0f), z(0.0f) {} Vector3f(float x, float y, float z) : x(x), y(y), z(z) {} float x, y, z; }; /** * Draws a line between two points. This relies on the calling code to have * called glBegin(GL_LINES) and to call glEnd(). */ void drawLine(const Vector3f& pt1, const Vector3f& pt2) { glVertex3f(pt1.x, pt1.y, pt1.z); glVertex3f(pt2.x, pt2.y, pt2.z); } void drawCircle(float cx, float cy, float r, int num_segments) { glBegin(GL_LINE_LOOP); for (int ii = 0; ii < num_segments; ii++) { float theta = 2.0f * 3.1415926f * float(ii) / float(num_segments);//get the current angle float x = r * cosf(theta);//calculate the x component float y = r * sinf(theta);//calculate the y component glVertex2f(x + cx, y + cy);//output vertex } glEnd(); } /// Calculates the x and y point of a segment of a rounded rectangle. void calculateDirectionalPoint(float &x, float &y, int segmentIndex, int numSegments, float roundness) { double a = M_PI_2 / numSegments * segmentIndex; double tan = tanf(a); double tmp = 1.0 / (1.0 + pow(tan, (double)roundness)); x = pow(tmp, 1.0 / roundness); y = x * tan; } class DirectionalParams { public: static const int SEGMENTS = 10; float m_directionalMultiplier; float m_z; float m_cone_height; float m_cone_width; double m_roundness; DirectionalParams() : m_directionalMultiplier(0.0f), m_z(1.0f), m_cone_height(1.0f), m_cone_width(1.0f), m_roundness(1.0) {} /// Calculates the directional properties of the light void init(float uSize, float vSize, float directionalMultiplier, float centerOfInterest) { m_directionalMultiplier = directionalMultiplier; // cone z position m_z = -centerOfInterest * sinf(m_directionalMultiplier * M_PI_2); // rectangle "roundness" m_roundness = powf(50.0f, powf(m_directionalMultiplier, 4.0f)) * 2.0f; m_cone_height = vSize + cos(m_directionalMultiplier * M_PI_2) * centerOfInterest; m_cone_width = uSize + cos(m_directionalMultiplier * M_PI_2) * centerOfInterest; } /// Returns true if a directional multiplier has been set to a non-zero value bool active() const { return m_directionalMultiplier > 1e-4f; } }; /** * The LightViewerModifier controls how lights objects are displayed within * the viewer. Due to the inability to register multiple viewer modifiers for * the same location type ("light" locations in this case), this class must * be able to draw all types of light that may be encountered. The default for * lights that are not represented here is a standard point light. * * The type of light to draw is usually determined by the attributes that are * set on the input location, for example if a light has a cone angle attribute * it is assumed to be a spot light. It also possible to specify the light type * manually in the "material.lightParams.Type" or "material.viewerLightParams.Type" * attributes to one of the following: * * - "omni" (for point lights) * - "spot" * - "distant" * - "quad" * - "mesh" * - "sphere" * - "dome" */ class LightViewerModifier : public FnKat::ViewerModifier { public: enum LightType { LIGHT_POINT = 0, LIGHT_SPOT, LIGHT_QUAD, LIGHT_DISTANT, LIGHT_MESH, LIGHT_SPHERE, LIGHT_DOME, LIGHT_DISK, LIGHT_CYLINDER, }; LightType m_lightType; float m_coa; float m_uSize, m_vSize; float m_centerOfInterest; float m_radius; GLUquadric* m_quadric; DirectionalParams m_directionalParams; mutable FnKat::StringAttribute m_typeAttr; // Used to remember the type of light mutable bool m_testedTypeAttr; std::string m_metaLightType; std::string m_metaDefaultKey; LightViewerModifier(FnKat::GroupAttribute args) : FnKat::ViewerModifier(args), m_lightType(LIGHT_SPOT), m_coa(80.0f), m_uSize(1.0f), m_vSize(1.0f), m_centerOfInterest(10.0f), m_radius(1.0f), m_quadric(0), m_testedTypeAttr(false) { // Empty } static FnKat::ViewerModifier* create(FnKat::GroupAttribute args) { return (FnKat::ViewerModifier*)new LightViewerModifier(args); } static FnKat::GroupAttribute getArgumentTemplate() { FnKat::GroupBuilder gb; return gb.build(); } /** * Gets the type of scene graph location that this viewer modifier runs on. */ static const char* getLocationType() { return "light"; } /** * Called per instance before each draw */ void deepSetup(FnKat::ViewerModifierInput& input) { // Draw only the VMP representation in the viewer input.overrideHostGeometry(); } /** * Called once per VMP instance when constructed */ void setup(FnKat::ViewerModifierInput& input) { // Used for Spot, sphere and Dome lights m_quadric = gluNewQuadric(); // Ensure that we pick up any changed light type attributes m_testedTypeAttr = false; // Try to get light type from material.meta attribute // Call through to other is*Light methods to interpret type and // gather type-specific args. lookupMetaLightType(input); FnKat::DoubleAttribute centerOfInterestAttr = input.getGlobalAttribute("geometry.centerOfInterest"); m_centerOfInterest = centerOfInterestAttr.getValue(10.0f, false); // Default to point light m_lightType = LIGHT_POINT; if(isSpotLight(input)) { m_lightType = LIGHT_SPOT; } else if(isDistantLight(input)) { m_lightType = LIGHT_DISTANT; } else if(isPointLight(input)) { m_lightType = LIGHT_POINT; } else if(isQuadLight(input)) { m_lightType = LIGHT_QUAD; } else if(isMeshLight(input)) { m_lightType = LIGHT_MESH; } else if(isSphereLight(input)) { m_lightType = LIGHT_SPHERE; } else if(isDomeLight(input)) { m_lightType = LIGHT_DOME; } else if(isDiskLight(input)) { m_lightType = LIGHT_DISK; } else if(isCylinderLight(input)) { m_lightType = LIGHT_CYLINDER; } } /** * Draw the light representation. * Note that this is also called during the selection picking pass, during * which point you should not adjust the assigned color. * * eg. if(input.getDrawOption("isPicking")) * { * // Drawing code for the selection buffer * } */ void draw(FnKat::ViewerModifierInput& input) { // Don't draw the light representation if we're being looked through if (input.isLookedThrough()) { return; } glPushAttrib(GL_POLYGON_BIT | GL_LIGHTING_BIT | GL_LINE_BIT); glDisable(GL_LIGHTING); glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); glLineWidth(1); // Set the color to use for drawing the light's representation float color[4] = {1, 1, 0, 1}; // yellow by default if(input.isSelected()) { // Turn the color white color[2] = 1; } else { FnAttribute::FloatAttribute previewColorAttr = input.getAttribute( "geometry.previewColor"); if (previewColorAttr.isValid()) { FnAttribute::FloatAttribute::array_type previewColor = previewColorAttr.getNearestSample(0); if (previewColor.size() >= 3) { color[0] = previewColor[0]; color[1] = previewColor[1]; color[2] = previewColor[2]; } } } glColor4fv(color); // Draw light depending on light type switch (m_lightType) { case LIGHT_POINT: drawPointLight(input); break; case LIGHT_SPOT: drawSpotLight(input); break; case LIGHT_QUAD: drawQuadLight(input); break; case LIGHT_DISTANT: drawDistantLight(input); break; case LIGHT_MESH: // Draw nothing break; case LIGHT_SPHERE: drawSphereLight(input); break; case LIGHT_DOME: drawDomeLight(input); break; case LIGHT_DISK: drawDiskLight(input); break; case LIGHT_CYLINDER: drawCylinderLight(input); break; }; // Restore the original options if(input.getDrawOption("isPicking")) { glLineWidth(1); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } // Restore Draw State glPopAttrib(); } /** * Called when the location is removed/refreshed. */ void cleanup(FnKat::ViewerModifierInput& input) { // Empty } /** * Called per instance after each draw */ void deepCleanup(FnKat::ViewerModifierInput& input) { // Empty } /** * Returns a bounding box for the current location for use with the viewer * scene graph. */ FnKat::DoubleAttribute getLocalSpaceBoundingBox(FnKat::ViewerModifierInput& input) { if(m_lightType == LIGHT_QUAD) { if(m_directionalParams.active()) { double bounds[6] = { std::min(-m_uSize, -m_directionalParams.m_cone_width), std::max(m_uSize, m_directionalParams.m_cone_width), std::min(-m_vSize, -m_directionalParams.m_cone_height), std::max(m_vSize, m_directionalParams.m_cone_height), m_directionalParams.m_z, 1.0 }; return FnKat::DoubleAttribute(bounds, 6, 1); } else { double bounds[6] = {-m_uSize, m_uSize, -m_vSize, m_vSize, -1, 1}; return FnKat::DoubleAttribute(bounds, 6, 1); } } else if(m_lightType == LIGHT_SPHERE) { double bounds[6] = {-m_radius, m_radius, -m_radius, m_radius, -m_radius, m_radius}; return FnKat::DoubleAttribute(bounds, 6, 1); } else { double bounds[6] = {-1, 1, -1, 1, -1, 1}; return FnKat::DoubleAttribute(bounds, 6, 1); } } static void flush() {} static void onFrameBegin() {} static void onFrameEnd() {} private: //======================================================================= // Light type identification //======================================================================= void lookupMetaLightType(FnKat::ViewerModifierInput& input) { FnKat::GroupAttribute materialAttr = input.getGlobalAttribute("material"); FnKat::StringAttribute defaultKeyAttr = materialAttr.getChildByName("meta.defaultKey"); m_metaDefaultKey = defaultKeyAttr.getValue("", false); if (!m_metaDefaultKey.empty()) { FnKat::StringAttribute lightTypeAttr = materialAttr.getChildByName("meta.lightType." + m_metaDefaultKey); m_metaLightType = lightTypeAttr.getValue("", false); } else { FnKat::GroupAttribute lightTypeGroupAttr = materialAttr.getChildByName("meta.lightType"); for (int64_t i = 0, e = lightTypeGroupAttr.getNumberOfChildren(); i != e; ++i) { FnKat::StringAttribute lightTypeAttr = lightTypeGroupAttr.getChildByIndex(i); if (lightTypeAttr.isValid()) { m_metaDefaultKey = lightTypeGroupAttr.getChildName(i); m_metaLightType = lightTypeAttr.getValue("", false); break; } } } } FnKat::Attribute lookupMetaShaderParam(FnKat::ViewerModifierInput& input, const std::string & shaderName) { FnKat::StringAttribute nameAttr = input.getGlobalAttribute( "material.meta." + shaderName + "." + m_metaDefaultKey); if (nameAttr.isValid()) { FnKat::StringAttribute::array_type values = nameAttr.getNearestSample(0.0); for (FnKat::StringAttribute::array_type::const_iterator I = values.begin(), E = values.end(); I != E; ++I) { FnKat::Attribute shaderAttr = input.getGlobalAttribute( std::string("material.")+(*I)); if (shaderAttr.isValid()) { return shaderAttr; } } } return FnKat::Attribute(); } // isDiskLight bool isDiskLight(FnKat::ViewerModifierInput& input) { FnKat::StringAttribute aMaterialAttr = input.getGlobalAttribute("material.arnoldLightShader"); std::string lightShader = aMaterialAttr.getValue("",false); if(lightShader == "disk_light") { return true; } else { return false; } } // isCylinderLight bool isCylinderLight(FnKat::ViewerModifierInput& input) { FnKat::StringAttribute aMaterialAttr = input.getGlobalAttribute("material.arnoldLightShader"); std::string lightShader = aMaterialAttr.getValue("",false); if(lightShader == "cylinder_light") { return true; } else { return false; } } /** * Determine whether this is a spot light and store cone angle for drawing. */ bool isSpotLight(FnKat::ViewerModifierInput& input) { if (m_metaLightType == "spot") { FnKat::FloatAttribute coaAttr = lookupMetaShaderParam(input, "coneAngleName"); if (coaAttr.isValid()) { // Store the cone outer angle for use in drawing m_coa = coaAttr.getValue(80.0f, false); return true; } } static std::vector<std::string> coaAttrNames; if(coaAttrNames.empty()) { coaAttrNames.push_back("material.prmanLightParams.Cone_Outer_Angle"); coaAttrNames.push_back("material.prmanLightParams.OuterAngle"); coaAttrNames.push_back("material.arnoldLightParams.wide_angle"); coaAttrNames.push_back("material.arnoldLightParams.cone_angle"); coaAttrNames.push_back("material.testLightParams.coneAngle"); coaAttrNames.push_back("material.parameters.Cone_Outer_Angle"); coaAttrNames.push_back("material.parameters.OuterAngle"); coaAttrNames.push_back("material.parameters.wide_angle"); coaAttrNames.push_back("material.parameters.cone_angle"); coaAttrNames.push_back("material.viewerLightParams.Cone_Outer_Angle"); coaAttrNames.push_back("material.parameters.coneAngle"); coaAttrNames.push_back("material.vrayLightParams.coneAngle"); } std::vector<std::string>::const_iterator it = coaAttrNames.begin(); for(; it != coaAttrNames.end(); ++it) { FnKat::FloatAttribute coaAttr = input.getGlobalAttribute(*it); if(coaAttr.isValid()) { // Store the cone outer angle for use in drawing m_coa = coaAttr.getValue(80.0f, false); return true; } } // Test if light type parameter is set - in this case the default cone // angle is used return isLightOfType(input, "spot"); } /** * Determine whether this is a distance / directional light. */ bool isDistantLight(FnKat::ViewerModifierInput& input) const { FnKat::StringAttribute aMaterialAttr = input.getGlobalAttribute("material.arnoldLightShader"); std::string lightShader = aMaterialAttr.getValue("",false); if(lightShader == "distant_light") { return true; } else { return false; } } /* { static std::vector<std::string> distantLightAttrNames; if(distantLightAttrNames.empty()) { distantLightAttrNames.push_back("material.arnoldLightParams.direction"); distantLightAttrNames.push_back("material.parameters.direction"); distantLightAttrNames.push_back("material.testLightParams.physical_sun"); distantLightAttrNames.push_back("material.vrayLightParams.beamRadius"); distantLightAttrNames.push_back("material.parameters.beamRadius"); distantLightAttrNames.push_back("material.vrayLightParams.ozone"); distantLightAttrNames.push_back("material.parameters.ozone"); } std::vector<std::string>::const_iterator it = distantLightAttrNames.begin(); for(; it != distantLightAttrNames.end(); ++it) { // One of these attributes only needs to be valid if(input.getGlobalAttribute(*it).isValid()) { return true; } } // Test if light type parameter is set return isLightOfType(input, "distant"); }*/ /** * Determine whether this is a point light. */ bool isPointLight(FnKat::ViewerModifierInput& input) const { // Test if light type parameter is set return isLightOfType(input, "omni") || isLightOfType(input, "point"); } /** * Determine whether this is a quad light and store its dimensions. */ bool isQuadLight(FnKat::ViewerModifierInput& input) { static std::vector<std::string> quadLightAttrNames; if(quadLightAttrNames.empty()) { quadLightAttrNames.push_back("material.arnoldLightParams.vertices"); quadLightAttrNames.push_back("material.parameters.vertices"); quadLightAttrNames.push_back("material.testLightParams.disc"); } std::vector<std::string>::const_iterator it = quadLightAttrNames.begin(); for(; it != quadLightAttrNames.end(); ++it) { // These attributes only need to be valid if(input.getGlobalAttribute(*it).isValid()) { return true; } } // V-Ray Rectangle Light FnKat::FloatAttribute uSizeAttr = input.getGlobalAttribute("material.vrayLightParams.u_size"); FnKat::FloatAttribute vSizeAttr = input.getGlobalAttribute("material.vrayLightParams.v_size"); if(uSizeAttr.isValid() && vSizeAttr.isValid()) { m_uSize = uSizeAttr.getValue(0.0f, false); m_vSize = vSizeAttr.getValue(0.0f, false); FnKat::FloatAttribute directionalAttr = input.getGlobalAttribute("material.vrayLightParams.directional"); m_directionalParams.init(m_uSize, m_vSize, directionalAttr.getValue(0.0f, false), m_centerOfInterest); return true; } uSizeAttr = input.getGlobalAttribute("material.parameters.u_size"); vSizeAttr = input.getGlobalAttribute("material.parameters.v_size"); if(uSizeAttr.isValid() && vSizeAttr.isValid()) { m_uSize = uSizeAttr.getValue(0.0f, false); m_vSize = vSizeAttr.getValue(0.0f, false); FnKat::FloatAttribute directionalAttr = input.getGlobalAttribute("material.parameters.directional"); m_directionalParams.init(m_uSize, m_vSize, directionalAttr.getValue(0.0f, false), m_centerOfInterest); return true; } // Test if light type parameter is set - in this case the default // dimensions are used return isLightOfType(input, "quad"); } /** * Determine whether this is a Mesh light. */ bool isMeshLight(FnKat::ViewerModifierInput& input) const { if(input.getGlobalAttribute("material.arnoldLightParams.mesh").isValid()) return true; // Test if light type parameter is set return isLightOfType(input, "mesh"); } /** * Determine whether this is a Sphere light and store the sphere radius. */ bool isSphereLight(FnKat::ViewerModifierInput& input) { static std::vector<std::string> sphereLightAttrNames; if(sphereLightAttrNames.empty()) { sphereLightAttrNames.push_back("material.vrayLightParams.radius"); sphereLightAttrNames.push_back("material.parameters.radius"); } FnKat::FloatAttribute radiusAttr; std::vector<std::string>::const_iterator it = sphereLightAttrNames.begin(); for(; it != sphereLightAttrNames.end(); ++it) { radiusAttr = input.getGlobalAttribute(*it); if(radiusAttr.isValid()) { m_radius = radiusAttr.getValue(0.0f, false); return true; } } // Test if light type parameter is set - in this case the default // radius is used return isLightOfType(input, "sphere"); } /** * Determine whether this is a dome light. */ bool isDomeLight(FnKat::ViewerModifierInput& input) const { static std::vector<std::string> domeLightAttrNames; if(domeLightAttrNames.empty()) { domeLightAttrNames.push_back("material.vrayLightParams.dome_targetRadius"); domeLightAttrNames.push_back("material.parameters.dome_targetRadius"); } std::vector<std::string>::const_iterator it = domeLightAttrNames.begin(); for(; it != domeLightAttrNames.end(); ++it) { if(input.getGlobalAttribute(*it).isValid()) { return true; } } // Test if light type parameter is set return isLightOfType(input, "dome"); } /** * Checks certain attributes to determine whether the type of light has been * manually specified. */ bool isLightOfType(FnKat::ViewerModifierInput& input, std::string lightType) const { if (m_metaLightType == lightType) return true; if(m_testedTypeAttr) { if(m_typeAttr.getValue("", false) == lightType) { return true; } return false; } // Optimization to ensure that we only try to get the type once per draw m_testedTypeAttr = true; // Loop through the list of attributes where the type of light can be // specified directly static std::vector<std::string> typeAttrNames; if(typeAttrNames.empty()) { typeAttrNames.push_back("material.lightParams.Type"); typeAttrNames.push_back("material.viewerLightParams.Type"); } FnKat::StringAttribute typeAttr; std::vector<std::string>::const_iterator it = typeAttrNames.begin(); for(; it != typeAttrNames.end(); ++it) { typeAttr = input.getGlobalAttribute(*it); if(typeAttr.isValid()) { // Store the valid attribute to use in successive queries m_typeAttr = typeAttr; return typeAttr.getValue("", false) == lightType; } } return false; } //======================================================================= // Drawing helpers //======================================================================= void drawDiskLight(FnKat::ViewerModifierInput& input) { glPushMatrix(); glScalef(2.0, 2.0, 2.0); drawCircle(0,0,0.5,8); glPushMatrix(); glRotatef(45,0,0,1); glBegin(GL_LINES); glVertex3f( -0.1, 0, 0); glVertex3f( 0.1, 0, 0); glVertex3f( 0, -0.1, 0); glVertex3f( 0, 0.1, 0); glVertex3f( 0, 0, 0); glVertex3f( 0, 0, -1); glVertex3f( 0, 0, -1); glVertex3f( 0, 0.25, -0.75); glEnd(); glPopMatrix(); glPopMatrix(); } void drawCylinderLight(FnKat::ViewerModifierInput& input) { glPushMatrix(); glPushMatrix(); glRotatef(90,1,0,0); glTranslatef(0,0,1); drawCircle(0,0,1,8); glPopMatrix(); glPushMatrix(); glRotatef(90,1,0,0); glTranslatef(0,0,-1); drawCircle(0,0,1,8); glPopMatrix(); glPushMatrix(); glBegin(GL_LINES); glVertex3f( 1, 1, 0); glVertex3f( 1, -1, 0); glVertex3f(-1, 1, 0); glVertex3f(-1, -1, 0); glVertex3f( 0, 1, 1); glVertex3f( 0, -1, 1); glVertex3f( 0, 1, -1); glVertex3f( 0, -1, -1); float v = sqrt(2)/2; glVertex3f( v, 1, v); glVertex3f( v, -1, v); glVertex3f( -v, 1, v); glVertex3f( -v, -1, v); glVertex3f( v, 1, -v); glVertex3f( v, -1, -v); glVertex3f( -v, 1, -v); glVertex3f( -v, -1, -v); glEnd(); glPopMatrix(); glPopMatrix(); } /** * Draw the point light representation. */ void drawPointLight(FnKat::ViewerModifierInput& input) { glPushMatrix(); glScalef(0.2, 0.2, 0.2); glPushMatrix(); glRotatef(0,1,0,0); drawCircle(0,0,1,8); glPopMatrix(); glPushMatrix(); glRotatef(90,1,0,0); drawCircle(0,0,1,8); glPopMatrix(); glPushMatrix(); glRotatef(0,0,0,1); glRotatef(90,0,1,0); drawCircle(0,0,1,8); glPopMatrix(); glPopMatrix(); glPushMatrix(); glBegin(GL_LINES); glVertex3f( -1, 0, 0); glVertex3f( 1, 0, 0); glVertex3f( 0, -1, 0); glVertex3f( 0, 1, 0); glVertex3f( 0, 0, -1); glVertex3f( 0, 0, 1); glVertex3f( -0.707, -0.707, 0.000); glVertex3f( 0.707, 0.707, 0.000); glVertex3f( 0.000, -0.707, -0.707); glVertex3f( 0.000, 0.707, 0.707); glVertex3f( -0.707, 0.000, -0.707); glVertex3f( 0.707, 0.000, 0.707); glVertex3f( -0.707, 0.707, 0.000); glVertex3f( 0.707, -0.707, 0.000); glVertex3f( 0.000, -0.707, 0.707); glVertex3f( 0.000, 0.707, -0.707); glVertex3f( -0.707, 0.000, 0.707); glVertex3f( 0.707, 0.000, -0.707); glEnd(); glPopMatrix(); } /** * Draw the spot light representation. */ void drawSpotLight(FnKat::ViewerModifierInput& input) { float height=1; float scale=1; float coa = std::min(std::max(m_coa,0.0f), 180.0f); float tangent = tan(coa/2 * 3.14159f/180.0f); float radius = tangent*height; //normalize length to 1 if(height != 0 || radius != 0) { float length = sqrt(height*height + radius*radius); height /= length; radius /= length; } height*=scale; radius*=scale; glPushMatrix(); glScalef(2, 2, -2); gluCylinder(m_quadric, 0, radius, height, 8, 1); glPopMatrix(); } /** * Draw the quad light representation. */ void drawQuadLight(FnKat::ViewerModifierInput& input) { glPushMatrix(); // To simplify selecting the light, when we are "picking" set // PolygonMode to FILL and increase the line width. if(input.getDrawOption("isPicking")) { glLineWidth(10); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } glBegin(GL_POLYGON); glVertex3f(-m_uSize, -m_vSize, 0); glVertex3f(m_uSize, -m_vSize, 0); glVertex3f(m_uSize, m_vSize, 0); glVertex3f(-m_uSize, m_vSize, 0); glEnd(); float uvAverage = (m_uSize + m_vSize) * 0.5; glPushMatrix(); glRotatef(45,0,0,1); glBegin(GL_LINES); glVertex3f( -0.25, 0, 0); glVertex3f( 0.25, 0, 0); glVertex3f( 0, -0.25, 0); glVertex3f( 0, 0.25, 0); glEnd(); glPopMatrix(); glBegin(GL_LINES); glVertex3f(0, 0, 0); glVertex3f(0, 0, -uvAverage); glVertex3f(0, 0, -uvAverage); glVertex3f(0, uvAverage * 0.25f,-uvAverage * 0.75f); // Draw directionality cone if one exists if(m_directionalParams.active()) { // segment coordinates for the four quadrants Vector3f pt1[2], pt2[2], pt3[2], pt4[2]; // starting points of the cone curves pt1[0] = Vector3f(m_directionalParams.m_cone_width, 0.0f, m_directionalParams.m_z); pt2[0] = Vector3f(0.0f, m_directionalParams.m_cone_height, m_directionalParams.m_z); pt3[0] = Vector3f(-m_directionalParams.m_cone_width, 0.0f, m_directionalParams.m_z); pt4[0] = Vector3f(0.0f, -m_directionalParams.m_cone_height, m_directionalParams.m_z); // For each segment of the far cone draw a line between the current // point and the previous point. int pointId = 1; for (int i = 0; i < m_directionalParams.SEGMENTS; i++) { float x, y; calculateDirectionalPoint(x, y, i, m_directionalParams.SEGMENTS, m_directionalParams.m_roundness); float x2 = y * m_directionalParams.m_cone_width; float y2 = x * m_directionalParams.m_cone_height; x *= m_directionalParams.m_cone_width; y *= m_directionalParams.m_cone_height; pt1[pointId] = Vector3f(x, y, m_directionalParams.m_z); drawLine(pt1[0], pt1[1]); pt2[pointId] = Vector3f(-x2, y2, m_directionalParams.m_z); drawLine(pt2[0], pt2[1]); pt3[pointId] = Vector3f(-x, -y, m_directionalParams.m_z); drawLine(pt3[0], pt3[1]); pt4[pointId] = Vector3f(x2, -y2, m_directionalParams.m_z); drawLine(pt4[0], pt4[1]); pointId = 1 - pointId; if (i == m_directionalParams.SEGMENTS / 2) { // Draw the cone lines that connect the near and far planes // of the cone. pt1[pointId] = Vector3f(m_uSize, m_vSize, 0.0f); drawLine(pt1[0], pt1[1]); pt2[pointId] = Vector3f(-m_uSize, m_vSize, 0.0f); drawLine(pt2[0], pt2[1]); pt3[pointId] = Vector3f(-m_uSize, -m_vSize, 0.0f); drawLine(pt3[0], pt3[1]); pt4[pointId] = Vector3f(m_uSize, -m_vSize, 0.0f); drawLine(pt4[0], pt4[1]); } } // close the cone curves pt1[pointId] = Vector3f(0.0f, m_directionalParams.m_cone_height, m_directionalParams.m_z); drawLine(pt1[0], pt1[1]); pt2[pointId] = Vector3f(-m_directionalParams.m_cone_width, 0.0f, m_directionalParams.m_z); drawLine(pt2[0], pt2[1]); pt3[pointId] = Vector3f(0.0f, -m_directionalParams.m_cone_height, m_directionalParams.m_z); drawLine(pt3[0], pt3[1]); pt4[pointId] = Vector3f(m_directionalParams.m_cone_width, 0.0f, m_directionalParams.m_z); drawLine(pt4[0], pt4[1]); } glEnd(); glPopMatrix(); } /** * Draw the distant light representation. */ void drawDistantLight(FnKat::ViewerModifierInput& input) { glPushMatrix(); glScalef(1.5,1.5,1.5); glPushMatrix(); glTranslatef(0,-0.25,0); glBegin(GL_LINES); glVertex3f(0,0,1); glVertex3f(0,0,-1); glVertex3f(0,0,-0.9); glVertex3f(0,0.2,-0.7); glVertex3f(0.14,0,-1); glVertex3f(-0.14,0,-1); glVertex3f(0.14,0,-1); glVertex3f(0,0,-1.4); glVertex3f(-0.14,0,-1); glVertex3f(0,0,-1.4); glEnd(); glPopMatrix(); glPushMatrix(); glTranslatef(0.25,0.25,0); glRotatef(-45,0,0,1); glBegin(GL_LINES); glVertex3f(0,0,1); glVertex3f(0,0,-1); glVertex3f(0.14,0,-1); glVertex3f(-0.14,0,-1); glVertex3f(0.14,0,-1); glVertex3f(0,0,-1.4); glVertex3f(-0.14,0,-1); glVertex3f(0,0,-1.4); glEnd(); glPopMatrix(); glPushMatrix(); glTranslatef(-0.25,0.25,0); glRotatef(45,0,0,1); glBegin(GL_LINES); glVertex3f(0,0,1); glVertex3f(0,0,-1); glVertex3f(0.14,0,-1); glVertex3f(-0.14,0,-1); glVertex3f(0.14,0,-1); glVertex3f(0,0,-1.4); glVertex3f(-0.14,0,-1); glVertex3f(0,0,-1.4); glEnd(); glPopMatrix(); glPopMatrix(); } /** * Draw the sphere light representation. */ void drawSphereLight(FnKat::ViewerModifierInput& input) { // To simplify selecting the light, when we are "picking" set // PolygonMode increase the line width. if(input.getDrawOption("isPicking")) { glLineWidth(10); } glPushMatrix(); gluDisk(m_quadric, m_radius, m_radius, 64, 1); glRotatef(90.0f, 1.0f, 0.0f, 0.0f); gluDisk(m_quadric, m_radius, m_radius, 64, 1); glRotatef(90.0f, 0.0f, 1.0f, 0.0f); gluDisk(m_quadric, m_radius, m_radius, 64, 1); glPopMatrix(); } /** * Draw the dome light representation. */ void drawDomeLight(FnKat::ViewerModifierInput& input) { // To simplify selecting the light, when we are "picking" set // PolygonMode increase the line width. if(input.getDrawOption("isPicking")) { glLineWidth(10); } glPushMatrix(); drawHalfDisk(64, 1.0f); glRotatef(90.0f, 0.0f, 1.0f, 0.0f); drawHalfDisk(64, 1.0f); glRotatef(90.0f, 1.0f, 0.0f, 0.0f); gluDisk(m_quadric, 1.0f, 1.0f, 64, 1); glPopMatrix(); } /** * Draw a semi-circle. */ static void drawHalfDisk(int segments, float radius) { glBegin(GL_LINE_STRIP); for (int ii = 0; ii < segments + 1; ++ii) { float angle = (M_PI / segments) * ii; glVertex3f(radius*cosf(angle), radius*sinf(angle), 0.0f); } glEnd(); } }; DEFINE_VMP_PLUGIN(LightViewerModifier) void registerPlugins() { std::cout << "[LCA PLUGIN]: Register LightViewerModifier v2.5" << std::endl; REGISTER_PLUGIN(LightViewerModifier, "LightViewerModifier", 0, 2); }
31.358426
114
0.555104
[ "mesh", "geometry", "vector" ]
4e9257056b49ea5c1f8917a12d213f0ca7b4b9e9
3,158
cpp
C++
lib/PhasarLLVM/DataFlowSolver/IfdsIde/IFDSFieldSensTaintAnalysis/Stats/TraceStats.cpp
n-junge/phasar
baa80e78bf67b80f030db4d1eedfb97755d407fc
[ "MIT" ]
null
null
null
lib/PhasarLLVM/DataFlowSolver/IfdsIde/IFDSFieldSensTaintAnalysis/Stats/TraceStats.cpp
n-junge/phasar
baa80e78bf67b80f030db4d1eedfb97755d407fc
[ "MIT" ]
null
null
null
lib/PhasarLLVM/DataFlowSolver/IfdsIde/IFDSFieldSensTaintAnalysis/Stats/TraceStats.cpp
n-junge/phasar
baa80e78bf67b80f030db4d1eedfb97755d407fc
[ "MIT" ]
null
null
null
/** * @author Sebastian Roland <seroland86@gmail.com> */ #include "phasar/PhasarLLVM/DataFlowSolver/IfdsIde/IFDSFieldSensTaintAnalysis/Stats/TraceStats.h" #include "phasar/PhasarLLVM/DataFlowSolver/IfdsIde/IFDSFieldSensTaintAnalysis/Utils/Log.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/DebugInfoMetadata.h" namespace psr { long TraceStats::add(const llvm::Instruction *instruction, bool isReturnValue) { const llvm::DebugLoc debugLocInst = instruction->getDebugLoc(); if (!debugLocInst) return 0; const llvm::DebugLoc debugLocFn = debugLocInst.getFnDebugLoc(); if (!debugLocFn) return 0; const auto function = instruction->getFunction(); if (!function) return 0; const auto functionName = function->getName(); const auto fnScope = llvm::cast<llvm::DIScope>(debugLocFn.getScope()); const std::string file = fnScope->getDirectory().str() + "/" + fnScope->getFilename().str(); unsigned int lineNumber = debugLocInst->getLine(); LOG_DEBUG("Tainting " << file << ":" << functionName << ":" << lineNumber << ":" << isReturnValue); TraceStats::LineNumberStats &lineNumberStats = getLineNumberStats(file, functionName); LineNumberEntry lineNumberEntry(lineNumber); if (isReturnValue) { lineNumberStats.erase(lineNumberEntry); lineNumberEntry.setReturnValue(true); } lineNumberStats.insert(lineNumberEntry); return 1; } long TraceStats::add(const llvm::Instruction *instruction, const std::vector<const llvm::Value *> memLocationSeq) { bool isRetInstruction = llvm::isa<llvm::ReturnInst>(instruction); if (isRetInstruction) { const auto basicBlock = instruction->getParent(); const auto basicBlockName = basicBlock->getName(); bool isReturnBasicBlock = basicBlockName.compare_lower("return") == 0; if (isReturnBasicBlock) return 0; return add(instruction, true); } bool isGENMemoryLocation = !memLocationSeq.empty(); if (isGENMemoryLocation) { const auto memLocationFrame = memLocationSeq.front(); if (const auto allocaInst = llvm::dyn_cast<llvm::AllocaInst>(memLocationFrame)) { const auto instructionName = allocaInst->getName(); bool isRetVal = instructionName.compare_lower("retval") == 0; if (isRetVal) return add(instruction, true); } } return add(instruction, false); } TraceStats::FunctionStats &TraceStats::getFunctionStats(std::string file) { auto functionStatsEntry = stats.find(file); if (functionStatsEntry != stats.end()) return functionStatsEntry->second; stats.insert({file, FunctionStats()}); return stats.find(file)->second; } TraceStats::LineNumberStats & TraceStats::getLineNumberStats(std::string file, std::string function) { TraceStats::FunctionStats &functionStats = getFunctionStats(file); auto lineNumberEntry = functionStats.find(function); if (lineNumberEntry != functionStats.end()) return lineNumberEntry->second; functionStats.insert({function, LineNumberStats()}); return functionStats.find(function)->second; } } // namespace psr
28.45045
97
0.712476
[ "vector" ]
4e96c4c3dbffdb1bd6154db2dd9ce405b74187d1
2,731
cpp
C++
wordBoxes/wordboxesOLD/wordboxesmatrix4.cpp
SnailDragon/Cpp-Exploration
2cfbf39fd3ba30b45ad4b0b54ff614a3a2a8b95d
[ "MIT" ]
null
null
null
wordBoxes/wordboxesOLD/wordboxesmatrix4.cpp
SnailDragon/Cpp-Exploration
2cfbf39fd3ba30b45ad4b0b54ff614a3a2a8b95d
[ "MIT" ]
null
null
null
wordBoxes/wordboxesOLD/wordboxesmatrix4.cpp
SnailDragon/Cpp-Exploration
2cfbf39fd3ba30b45ad4b0b54ff614a3a2a8b95d
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <fstream> using namespace std; void PrintBox(vector<string> box); void SaveBox(vector<string> box); ofstream boxes; int main(){ boxes.open("fourboxes.txt"); int size = 4; ifstream wordBank; string filename = "words" + to_string(size) + ".txt"; wordBank.open(filename, fstream::in); vector<string> words; string line = ""; do { getline(wordBank, line); words.push_back(line); } while (line != ""); words.pop_back(); bool wordMatrix[26][26][26][26]; for(int i = 0; i < size; i++){ for(int j = 0; j < size; j++){ for(int x = 0; x < size; x++){ for(int z = 0; z < size; z++){ wordMatrix[i][j][x][z] = false; } } } } for(unsigned int i = 0; i < words.size(); i++){ wordMatrix[words.at(i).at(0)-'a'][words.at(i).at(1)-'a'][words.at(i).at(2)-'a'][words.at(i).at(3)-'a'] = true; } //int it = 0; for(int i = 0; i < words.size(); ++i){ for(int j = 0; j < words.size(); ++j){ for(int z = 0; z < words.size(); ++z){ for(int x = 0; x < words.size(); ++x){ //cout << "Processing box #" << it << endl; //it++; bool isWordBox = true; for(int in = 0; in < size; in++){ if(!wordMatrix[words.at(i).at(in)-'a'][words.at(j).at(in)-'a'][words.at(z).at(in)-'a'][words.at(x).at(in)-'a']){ isWordBox = false; } } if(isWordBox){ vector<string> testBox3; testBox3.push_back(words[i]); testBox3.push_back(words[j]); testBox3.push_back(words[z]); testBox3.push_back(words[x]); // PrintBox(testBox3); SaveBox(testBox3); PrintBox(testBox3); } // else{ // // PrintBox(testBox3); // cout << i << "." << j << "." << z << "." << x << endl; // } } } } cout << "Done i = " << i << endl; } return 0; } void SaveBox(vector<string> box){ for(int i = 0; i < box.size(); ++i){ boxes << box[i] << endl; } boxes << endl << endl; } void PrintBox(vector<string> box){ for(int i = 0; i < box.size(); ++i){ cout << box[i] << endl; } cout << endl; }
26.77451
136
0.403881
[ "vector" ]
4e980e6622b142b6cb98db2aaf85d8b4efb733fc
228
cpp
C++
src/cpptemplate.cpp
luowyang/UVaSolutions
09a89989d31c15ed66fdbcb5a0f8c3b32fef5ad9
[ "MIT" ]
null
null
null
src/cpptemplate.cpp
luowyang/UVaSolutions
09a89989d31c15ed66fdbcb5a0f8c3b32fef5ad9
[ "MIT" ]
null
null
null
src/cpptemplate.cpp
luowyang/UVaSolutions
09a89989d31c15ed66fdbcb5a0f8c3b32fef5ad9
[ "MIT" ]
null
null
null
/** * , UVa **/ #include <set> #include <map> #include <vector> #include <stack> #include <queue> #include <string> #include <cstdio> #include <iostream> #include <algorithm> using namespace std; int main() { return 0; }
12
20
0.649123
[ "vector" ]
4eb61c7bc2b4d459d3bf9ff9bd374c4cd0b4a01b
513
cpp
C++
3DArray.cpp
sinarashidiazar/cpp
97ff3b6821efb3857b7a1a4cc24a6294e7279e75
[ "MIT" ]
null
null
null
3DArray.cpp
sinarashidiazar/cpp
97ff3b6821efb3857b7a1a4cc24a6294e7279e75
[ "MIT" ]
null
null
null
3DArray.cpp
sinarashidiazar/cpp
97ff3b6821efb3857b7a1a4cc24a6294e7279e75
[ "MIT" ]
null
null
null
// pointeres to 3D-arrays #include <iostream> #include <conio.h> using namespace std; main() { int a[2][3][4]= { { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} } , { {13,14,15,16}, {17,18,19,20}, {21,22,23,24} } }; int (*p)[3][4]; p=a; cout<< *(*(*(p+0)+2)+1)<<endl; // 10 cout<< a[0][2][1]; //10 cout<<endl; cout<< *(*(*(p+1)+0)+3); // 3 getch(); }
11.4
39
0.327485
[ "3d" ]
4eb726ae6ecf2069bc9b582a2ca83f7f75243eda
685,800
cpp
C++
test/generated/tailoring_rule_test_zh_zhuyin_019.cpp
Ryan-rsm-McKenzie/text
15aaea4297e00ec4c74295e7913ead79c90e1502
[ "BSL-1.0" ]
265
2017-07-09T23:23:48.000Z
2022-03-24T10:14:19.000Z
test/generated/tailoring_rule_test_zh_zhuyin_019.cpp
Ryan-rsm-McKenzie/text
15aaea4297e00ec4c74295e7913ead79c90e1502
[ "BSL-1.0" ]
185
2017-08-30T16:44:51.000Z
2021-08-13T12:02:46.000Z
test/generated/tailoring_rule_test_zh_zhuyin_019.cpp
Ryan-rsm-McKenzie/text
15aaea4297e00ec4c74295e7913ead79c90e1502
[ "BSL-1.0" ]
25
2017-08-29T23:07:23.000Z
2021-09-03T06:31:29.000Z
// Copyright (C) 2020 T. Zachary Laine // // 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) // Warning! This file is autogenerated. #include <boost/text/collation_table.hpp> #include <boost/text/collate.hpp> #include <boost/text/data/all.hpp> #ifndef LIMIT_TESTING_FOR_CI #include <boost/text/save_load_table.hpp> #include <boost/filesystem.hpp> #endif #include <gtest/gtest.h> using namespace boost::text; auto const error = [](std::string const & s) { std::cout << s; }; auto const warning = [](std::string const & s) {}; collation_table make_save_load_table() { #ifdef LIMIT_TESTING_FOR_CI std::string const table_str(data::zh::zhuyin_collation_tailoring()); return tailored_collation_table( table_str, "zh::zhuyin_collation_tailoring()", error, warning); #else if (!exists(boost::filesystem::path("zh_zhuyin.table"))) { std::string const table_str(data::zh::zhuyin_collation_tailoring()); collation_table table = tailored_collation_table( table_str, "zh::zhuyin_collation_tailoring()", error, warning); save_table(table, "zh_zhuyin.table.19"); boost::filesystem::rename("zh_zhuyin.table.19", "zh_zhuyin.table"); } return load_table("zh_zhuyin.table"); #endif } collation_table const & table() { static collation_table retval = make_save_load_table(); return retval; } TEST(tailoring, zh_zhuyin_018_000) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x22cc6); auto const rel = std::vector<uint32_t>(1, 0x58ba); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x58ba); auto const rel = std::vector<uint32_t>(1, 0x5db4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5db4); auto const rel = std::vector<uint32_t>(1, 0x61ca); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x61ca); auto const rel = std::vector<uint32_t>(1, 0x64d9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x64d9); auto const rel = std::vector<uint32_t>(1, 0x6fb3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6fb3); auto const rel = std::vector<uint32_t>(1, 0x96a9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x96a9); auto const rel = std::vector<uint32_t>(1, 0x93ca); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x93ca); auto const rel = std::vector<uint32_t>(1, 0x9a41); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a41); auto const rel = std::vector<uint32_t>(1, 0x7ff6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7ff6); auto const rel = std::vector<uint32_t>{0xfdd0, 0x3121}; std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>{0xfdd0, 0x3121}; auto const rel = std::vector<uint32_t>(1, 0x8bb4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8bb4); auto const rel = std::vector<uint32_t>(1, 0x6ca4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6ca4); auto const rel = std::vector<uint32_t>(1, 0x6b27); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b27); auto const rel = std::vector<uint32_t>(1, 0x6bb4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6bb4); auto const rel = std::vector<uint32_t>(1, 0x74ef); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x74ef); auto const rel = std::vector<uint32_t>(1, 0x9e25); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e25); auto const rel = std::vector<uint32_t>(1, 0x5878); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5878); auto const rel = std::vector<uint32_t>(1, 0x6f1a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6f1a); auto const rel = std::vector<uint32_t>(1, 0x6b50); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b50); auto const rel = std::vector<uint32_t>(1, 0x6bc6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6bc6); auto const rel = std::vector<uint32_t>(1, 0x71b0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x71b0); auto const rel = std::vector<uint32_t>(1, 0x9d0e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d0e); auto const rel = std::vector<uint32_t>(1, 0x750c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x750c); auto const rel = std::vector<uint32_t>(1, 0x210bf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x210bf); auto const rel = std::vector<uint32_t>(1, 0x8b33); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b33); auto const rel = std::vector<uint32_t>(1, 0x6ad9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6ad9); auto const rel = std::vector<uint32_t>(1, 0x93c2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x93c2); auto const rel = std::vector<uint32_t>(1, 0x9dd7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dd7); auto const rel = std::vector<uint32_t>(1, 0x4972); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4972); auto const rel = std::vector<uint32_t>(1, 0x8192); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8192); auto const rel = std::vector<uint32_t>(1, 0x9f75); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f75); auto const rel = std::vector<uint32_t>(1, 0x20676); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x20676); auto const rel = std::vector<uint32_t>(1, 0x5418); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5418); auto const rel = std::vector<uint32_t>(1, 0x5455); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5455); auto const rel = std::vector<uint32_t>(1, 0x5076); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5076); auto const rel = std::vector<uint32_t>(1, 0x8162); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8162); auto const rel = std::vector<uint32_t>(1, 0x5614); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5614); auto const rel = std::vector<uint32_t>(1, 0x3496); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3496); auto const rel = std::vector<uint32_t>(1, 0x8026); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8026); auto const rel = std::vector<uint32_t>(1, 0x8545); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8545); auto const rel = std::vector<uint32_t>(1, 0x85d5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x85d5); auto const rel = std::vector<uint32_t>(1, 0x6004); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6004); auto const rel = std::vector<uint32_t>(1, 0x616a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x616a); auto const rel = std::vector<uint32_t>(1, 0x85f2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x85f2); auto const rel = std::vector<uint32_t>{0xfdd0, 0x3122}; std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>{0xfdd0, 0x3122}; auto const rel = std::vector<uint32_t>(1, 0x5b89); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b89); auto const rel = std::vector<uint32_t>(1, 0x4f92); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f92); auto const rel = std::vector<uint32_t>(1, 0x5cd6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5cd6); auto const rel = std::vector<uint32_t>(1, 0x6849); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6849); auto const rel = std::vector<uint32_t>(1, 0x6c28); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6c28); auto const rel = std::vector<uint32_t>(1, 0x5eb5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_001) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5eb5); auto const rel = std::vector<uint32_t>(1, 0x4002); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4002); auto const rel = std::vector<uint32_t>(1, 0x8c19); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8c19); auto const rel = std::vector<uint32_t>(1, 0x5a95); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5a95); auto const rel = std::vector<uint32_t>(1, 0x83f4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x83f4); auto const rel = std::vector<uint32_t>(1, 0x75f7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x75f7); auto const rel = std::vector<uint32_t>(1, 0x8164); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8164); auto const rel = std::vector<uint32_t>(1, 0x843b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x843b); auto const rel = std::vector<uint32_t>(1, 0x844a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x844a); auto const rel = std::vector<uint32_t>(1, 0x9e4c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e4c); auto const rel = std::vector<uint32_t>(1, 0x8a9d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a9d); auto const rel = std::vector<uint32_t>(1, 0x84ed); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x84ed); auto const rel = std::vector<uint32_t>(1, 0x978c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x978c); auto const rel = std::vector<uint32_t>(1, 0x978d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x978d); auto const rel = std::vector<uint32_t>(1, 0x76e6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x76e6); auto const rel = std::vector<uint32_t>(1, 0x8af3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8af3); auto const rel = std::vector<uint32_t>(1, 0x99a3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x99a3); auto const rel = std::vector<uint32_t>(1, 0x76eb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x76eb); auto const rel = std::vector<uint32_t>(1, 0x9d6a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d6a); auto const rel = std::vector<uint32_t>(1, 0x97fd); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x97fd); auto const rel = std::vector<uint32_t>(1, 0x9d95); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d95); auto const rel = std::vector<uint32_t>(1, 0x73b5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x73b5); auto const rel = std::vector<uint32_t>(1, 0x557d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x557d); auto const rel = std::vector<uint32_t>(1, 0x96f8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x96f8); auto const rel = std::vector<uint32_t>(1, 0x5111); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5111); auto const rel = std::vector<uint32_t>(1, 0x57b5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x57b5); auto const rel = std::vector<uint32_t>(1, 0x4ffa); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4ffa); auto const rel = std::vector<uint32_t>(1, 0x5535); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5535); auto const rel = std::vector<uint32_t>(1, 0x57ef); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x57ef); auto const rel = std::vector<uint32_t>(1, 0x94f5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x94f5); auto const rel = std::vector<uint32_t>(1, 0x63de); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x63de); auto const rel = std::vector<uint32_t>(1, 0x968c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x968c); auto const rel = std::vector<uint32_t>(1, 0x7f6f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7f6f); auto const rel = std::vector<uint32_t>(1, 0x92a8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x92a8); auto const rel = std::vector<uint32_t>(1, 0x72b4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x72b4); auto const rel = std::vector<uint32_t>(1, 0x5cb8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5cb8); auto const rel = std::vector<uint32_t>(1, 0x6309); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6309); auto const rel = std::vector<uint32_t>(1, 0x6d1d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6d1d); auto const rel = std::vector<uint32_t>(1, 0x6848); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6848); auto const rel = std::vector<uint32_t>(1, 0x80fa); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x80fa); auto const rel = std::vector<uint32_t>(1, 0x834c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x834c); auto const rel = std::vector<uint32_t>(1, 0x8c7b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8c7b); auto const rel = std::vector<uint32_t>(1, 0x5813); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5813); auto const rel = std::vector<uint32_t>(1, 0x5a69); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5a69); auto const rel = std::vector<uint32_t>(1, 0x4141); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4141); auto const rel = std::vector<uint32_t>(1, 0x667b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x667b); auto const rel = std::vector<uint32_t>(1, 0x6697); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6697); auto const rel = std::vector<uint32_t>(1, 0x930c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x930c); auto const rel = std::vector<uint32_t>(1, 0x95c7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x95c7); auto const rel = std::vector<uint32_t>(1, 0x9b9f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b9f); auto const rel = std::vector<uint32_t>(1, 0x4b97); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4b97); auto const rel = std::vector<uint32_t>(1, 0x9eef); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_002) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9eef); auto const rel = std::vector<uint32_t>{0xfdd0, 0x3123}; std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>{0xfdd0, 0x3123}; auto const rel = std::vector<uint32_t>(1, 0x5940); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5940); auto const rel = std::vector<uint32_t>(1, 0x6069); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6069); auto const rel = std::vector<uint32_t>(1, 0x217ef); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x217ef); auto const rel = std::vector<uint32_t>(1, 0x717e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x717e); auto const rel = std::vector<uint32_t>(1, 0x84bd); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x84bd); auto const rel = std::vector<uint32_t>(1, 0x5cce); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5cce); auto const rel = std::vector<uint32_t>(1, 0x6441); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6441); auto const rel = std::vector<uint32_t>(1, 0x4b53); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4b53); auto const rel = std::vector<uint32_t>{0xfdd0, 0x3124}; std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>{0xfdd0, 0x3124}; auto const rel = std::vector<uint32_t>(1, 0x80ae); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x80ae); auto const rel = std::vector<uint32_t>(1, 0x9aaf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9aaf); auto const rel = std::vector<uint32_t>(1, 0x536c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x536c); auto const rel = std::vector<uint32_t>(1, 0x5c87); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5c87); auto const rel = std::vector<uint32_t>(1, 0x6602); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6602); auto const rel = std::vector<uint32_t>(1, 0x663b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x663b); auto const rel = std::vector<uint32_t>(1, 0x44a2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x44a2); auto const rel = std::vector<uint32_t>(1, 0x3b7f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3b7f); auto const rel = std::vector<uint32_t>(1, 0x678a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x678a); auto const rel = std::vector<uint32_t>(1, 0x76ce); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x76ce); auto const rel = std::vector<uint32_t>(1, 0x91a0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91a0); auto const rel = std::vector<uint32_t>{0xfdd0, 0x3125}; std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>{0xfdd0, 0x3125}; auto const rel = std::vector<uint32_t>(1, 0x97a5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x97a5); auto const rel = std::vector<uint32_t>{0xfdd0, 0x3126}; std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>{0xfdd0, 0x3126}; auto const rel = std::vector<uint32_t>(1, 0x513f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x513f); auto const rel = std::vector<uint32_t>(1, 0x800c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x800c); auto const rel = std::vector<uint32_t>(1, 0x5150); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5150); auto const rel = std::vector<uint32_t>(1, 0x4f95); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f95); auto const rel = std::vector<uint32_t>(1, 0x5152); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5152); auto const rel = std::vector<uint32_t>(1, 0x5ccf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5ccf); auto const rel = std::vector<uint32_t>(1, 0x6d0f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6d0f); auto const rel = std::vector<uint32_t>(1, 0x9651); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9651); auto const rel = std::vector<uint32_t>(1, 0x682d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x682d); auto const rel = std::vector<uint32_t>(1, 0x80f9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x80f9); auto const rel = std::vector<uint32_t>(1, 0x834b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x834b); auto const rel = std::vector<uint32_t>(1, 0x5532); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5532); auto const rel = std::vector<uint32_t>(1, 0x9e38); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e38); auto const rel = std::vector<uint32_t>(1, 0x7cab); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7cab); auto const rel = std::vector<uint32_t>(1, 0x804f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x804f); auto const rel = std::vector<uint32_t>(1, 0x88bb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x88bb); auto const rel = std::vector<uint32_t>(1, 0x8f00); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f00); auto const rel = std::vector<uint32_t>(1, 0x42e9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x42e9); auto const rel = std::vector<uint32_t>(1, 0x9c95); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c95); auto const rel = std::vector<uint32_t>(1, 0x9af5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9af5); auto const rel = std::vector<uint32_t>(1, 0x96ad); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x96ad); auto const rel = std::vector<uint32_t>(1, 0x9b9e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b9e); auto const rel = std::vector<uint32_t>(1, 0x9d2f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d2f); auto const rel = std::vector<uint32_t>(1, 0x8f5c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f5c); auto const rel = std::vector<uint32_t>(1, 0x53bc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x53bc); auto const rel = std::vector<uint32_t>(1, 0x5c12); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5c12); auto const rel = std::vector<uint32_t>(1, 0x5c13); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_003) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5c13); auto const rel = std::vector<uint32_t>(1, 0x5c14); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5c14); auto const rel = std::vector<uint32_t>(1, 0x8033); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8033); auto const rel = std::vector<uint32_t>(1, 0x6d31); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6d31); auto const rel = std::vector<uint32_t>(1, 0x8fe9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8fe9); auto const rel = std::vector<uint32_t>(1, 0x9975); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9975); auto const rel = std::vector<uint32_t>(1, 0x682e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x682e); auto const rel = std::vector<uint32_t>(1, 0x6be6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6be6); auto const rel = std::vector<uint32_t>(1, 0x73e5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x73e5); auto const rel = std::vector<uint32_t>(1, 0x94d2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x94d2); auto const rel = std::vector<uint32_t>(1, 0x723e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x723e); auto const rel = std::vector<uint32_t>(1, 0x990c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x990c); auto const rel = std::vector<uint32_t>(1, 0x99ec); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x99ec); auto const rel = std::vector<uint32_t>(1, 0x85be); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x85be); auto const rel = std::vector<uint32_t>(1, 0x9087); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9087); auto const rel = std::vector<uint32_t>(1, 0x8db0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8db0); auto const rel = std::vector<uint32_t>(1, 0x4e8c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e8c); auto const rel = std::vector<uint32_t>(1, 0x5f0d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5f0d); auto const rel = std::vector<uint32_t>(1, 0x5f10); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5f10); auto const rel = std::vector<uint32_t>(1, 0x4f74); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f74); auto const rel = std::vector<uint32_t>(1, 0x5235); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5235); auto const rel = std::vector<uint32_t>(1, 0x54a1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x54a1); auto const rel = std::vector<uint32_t>(1, 0x36c5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x36c5); auto const rel = std::vector<uint32_t>(1, 0x8d30); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8d30); auto const rel = std::vector<uint32_t>(1, 0x8cae); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8cae); auto const rel = std::vector<uint32_t>(1, 0x8848); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8848); auto const rel = std::vector<uint32_t>(1, 0x8cb3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8cb3); auto const rel = std::vector<uint32_t>(1, 0x8a80); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a80); auto const rel = std::vector<uint32_t>(1, 0x927a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x927a); auto const rel = std::vector<uint32_t>(1, 0x6a32); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6a32); auto const rel = std::vector<uint32_t>{0xfdd0, 0x3127}; std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>{0xfdd0, 0x3127}; auto const rel = std::vector<uint32_t>(1, 0x4e00); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e00); auto const rel = std::vector<uint32_t>(1, 0x4e4a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e4a); auto const rel = std::vector<uint32_t>(1, 0x5f0c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5f0c); auto const rel = std::vector<uint32_t>(1, 0x8864); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8864); auto const rel = std::vector<uint32_t>(1, 0x4f0a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f0a); auto const rel = std::vector<uint32_t>(1, 0x8863); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8863); auto const rel = std::vector<uint32_t>(1, 0x533b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x533b); auto const rel = std::vector<uint32_t>(1, 0x541a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x541a); auto const rel = std::vector<uint32_t>(1, 0x58f1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x58f1); auto const rel = std::vector<uint32_t>(1, 0x4f9d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f9d); auto const rel = std::vector<uint32_t>(1, 0x54bf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x54bf); auto const rel = std::vector<uint32_t>(1, 0x20c96); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x20c96); auto const rel = std::vector<uint32_t>(1, 0x36c4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x36c4); auto const rel = std::vector<uint32_t>(1, 0x3cd6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3cd6); auto const rel = std::vector<uint32_t>(1, 0x6d22); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6d22); auto const rel = std::vector<uint32_t>(1, 0x794e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x794e); auto const rel = std::vector<uint32_t>(1, 0x2343f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x2343f); auto const rel = std::vector<uint32_t>(1, 0x6098); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6098); auto const rel = std::vector<uint32_t>(1, 0x7317); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7317); auto const rel = std::vector<uint32_t>(1, 0x94f1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x94f1); auto const rel = std::vector<uint32_t>(1, 0x58f9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_004) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x58f9); auto const rel = std::vector<uint32_t>(1, 0x63d6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x63d6); auto const rel = std::vector<uint32_t>(1, 0x6b39); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b39); auto const rel = std::vector<uint32_t>(1, 0x86dc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x86dc); auto const rel = std::vector<uint32_t>(1, 0x90fc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x90fc); auto const rel = std::vector<uint32_t>(1, 0x5adb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5adb); auto const rel = std::vector<uint32_t>(1, 0x6f2a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6f2a); auto const rel = std::vector<uint32_t>(1, 0x7995); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7995); auto const rel = std::vector<uint32_t>(1, 0x7a26); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7a26); auto const rel = std::vector<uint32_t>(1, 0x92a5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x92a5); auto const rel = std::vector<uint32_t>(1, 0x5b04); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b04); auto const rel = std::vector<uint32_t>(1, 0x566b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x566b); auto const rel = std::vector<uint32_t>(1, 0x5901); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5901); auto const rel = std::vector<uint32_t>(1, 0x747f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x747f); auto const rel = std::vector<uint32_t>(1, 0x9e65); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e65); auto const rel = std::vector<uint32_t>(1, 0x7e44); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e44); auto const rel = std::vector<uint32_t>(1, 0x4ad1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4ad1); auto const rel = std::vector<uint32_t>(1, 0x6ab9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6ab9); auto const rel = std::vector<uint32_t>(1, 0x6bc9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6bc9); auto const rel = std::vector<uint32_t>(1, 0x91ab); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91ab); auto const rel = std::vector<uint32_t>(1, 0x9edf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9edf); auto const rel = std::vector<uint32_t>(1, 0x8b69); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b69); auto const rel = std::vector<uint32_t>(1, 0x9dd6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dd6); auto const rel = std::vector<uint32_t>(1, 0x9ef3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ef3); auto const rel = std::vector<uint32_t>(1, 0x4e41); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e41); auto const rel = std::vector<uint32_t>(1, 0x4eea); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4eea); auto const rel = std::vector<uint32_t>(1, 0x531c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x531c); auto const rel = std::vector<uint32_t>(1, 0x572f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x572f); auto const rel = std::vector<uint32_t>(1, 0x5937); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5937); auto const rel = std::vector<uint32_t>(1, 0x519d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x519d); auto const rel = std::vector<uint32_t>(1, 0x5b90); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b90); auto const rel = std::vector<uint32_t>(1, 0x6c82); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6c82); auto const rel = std::vector<uint32_t>(1, 0x8bd2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8bd2); auto const rel = std::vector<uint32_t>(1, 0x8fc6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8fc6); auto const rel = std::vector<uint32_t>(1, 0x4f87); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f87); auto const rel = std::vector<uint32_t>(1, 0x5b9c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b9c); auto const rel = std::vector<uint32_t>(1, 0x6021); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6021); auto const rel = std::vector<uint32_t>(1, 0x6cb6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6cb6); auto const rel = std::vector<uint32_t>(1, 0x72cb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x72cb); auto const rel = std::vector<uint32_t>(1, 0x9974); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9974); auto const rel = std::vector<uint32_t>(1, 0x54a6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x54a6); auto const rel = std::vector<uint32_t>(1, 0x59e8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x59e8); auto const rel = std::vector<uint32_t>(1, 0x5cd3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5cd3); auto const rel = std::vector<uint32_t>(1, 0x5df8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5df8); auto const rel = std::vector<uint32_t>(1, 0x5f2c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5f2c); auto const rel = std::vector<uint32_t>(1, 0x605e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x605e); auto const rel = std::vector<uint32_t>(1, 0x62f8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x62f8); auto const rel = std::vector<uint32_t>(1, 0x67c2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x67c2); auto const rel = std::vector<uint32_t>(1, 0x73c6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x73c6); auto const rel = std::vector<uint32_t>(1, 0x886a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x886a); auto const rel = std::vector<uint32_t>(1, 0x8d3b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8d3b); auto const rel = std::vector<uint32_t>(1, 0x8fe4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_005) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8fe4); auto const rel = std::vector<uint32_t>(1, 0x5ba7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5ba7); auto const rel = std::vector<uint32_t>(1, 0x6245); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6245); auto const rel = std::vector<uint32_t>(1, 0x6818); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6818); auto const rel = std::vector<uint32_t>(1, 0x684b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x684b); auto const rel = std::vector<uint32_t>(1, 0x3ebf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3ebf); auto const rel = std::vector<uint32_t>(1, 0x74f5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x74f5); auto const rel = std::vector<uint32_t>(1, 0x7719); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7719); auto const rel = std::vector<uint32_t>(1, 0x80f0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x80f0); auto const rel = std::vector<uint32_t>(1, 0x8a11); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a11); auto const rel = std::vector<uint32_t>(1, 0x8ca4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8ca4); auto const rel = std::vector<uint32_t>(1, 0x8ffb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8ffb); auto const rel = std::vector<uint32_t>(1, 0x75cd); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x75cd); auto const rel = std::vector<uint32_t>(1, 0x79fb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x79fb); auto const rel = std::vector<uint32_t>(1, 0x801b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x801b); auto const rel = std::vector<uint32_t>(1, 0x8898); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8898); auto const rel = std::vector<uint32_t>(1, 0x51d2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x51d2); auto const rel = std::vector<uint32_t>(1, 0x7fa0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7fa0); auto const rel = std::vector<uint32_t>(1, 0x8413); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8413); auto const rel = std::vector<uint32_t>(1, 0x86e6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x86e6); auto const rel = std::vector<uint32_t>(1, 0x8a51); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a51); auto const rel = std::vector<uint32_t>(1, 0x8a52); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a52); auto const rel = std::vector<uint32_t>(1, 0x8cbd); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8cbd); auto const rel = std::vector<uint32_t>(1, 0x5a90); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5a90); auto const rel = std::vector<uint32_t>(1, 0x6686); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6686); auto const rel = std::vector<uint32_t>(1, 0x6938); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6938); auto const rel = std::vector<uint32_t>(1, 0x8a83); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a83); auto const rel = std::vector<uint32_t>(1, 0x8de0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8de0); auto const rel = std::vector<uint32_t>(1, 0x9057); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9057); auto const rel = std::vector<uint32_t>(1, 0x9809); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9809); auto const rel = std::vector<uint32_t>(1, 0x9890); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9890); auto const rel = std::vector<uint32_t>(1, 0x98f4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x98f4); auto const rel = std::vector<uint32_t>(1, 0x7591); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7591); auto const rel = std::vector<uint32_t>(1, 0x5100); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5100); auto const rel = std::vector<uint32_t>(1, 0x71aa); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x71aa); auto const rel = std::vector<uint32_t>(1, 0x7bb7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7bb7); auto const rel = std::vector<uint32_t>(1, 0x5dac); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5dac); auto const rel = std::vector<uint32_t>(1, 0x5f5b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5f5b); auto const rel = std::vector<uint32_t>(1, 0x5f5c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5f5c); auto const rel = std::vector<uint32_t>(1, 0x8794); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8794); auto const rel = std::vector<uint32_t>(1, 0x907a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x907a); auto const rel = std::vector<uint32_t>(1, 0x9824); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9824); auto const rel = std::vector<uint32_t>(1, 0x5bf2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5bf2); auto const rel = std::vector<uint32_t>(1, 0x5db7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5db7); auto const rel = std::vector<uint32_t>(1, 0x7c03); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c03); auto const rel = std::vector<uint32_t>(1, 0x984a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x984a); auto const rel = std::vector<uint32_t>(1, 0x294e7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x294e7); auto const rel = std::vector<uint32_t>(1, 0x4c4c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4c4c); auto const rel = std::vector<uint32_t>(1, 0x5f5d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5f5d); auto const rel = std::vector<uint32_t>(1, 0x5f5e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5f5e); auto const rel = std::vector<uint32_t>(1, 0x8b3b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b3b); auto const rel = std::vector<uint32_t>(1, 0x93d4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_006) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x93d4); auto const rel = std::vector<uint32_t>(1, 0x89fa); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x89fa); auto const rel = std::vector<uint32_t>(1, 0x3c18); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3c18); auto const rel = std::vector<uint32_t>(1, 0x8b89); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b89); auto const rel = std::vector<uint32_t>(1, 0x9e03); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e03); auto const rel = std::vector<uint32_t>(1, 0x4e59); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e59); auto const rel = std::vector<uint32_t>(1, 0x5df2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5df2); auto const rel = std::vector<uint32_t>(1, 0x4ee5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4ee5); auto const rel = std::vector<uint32_t>(1, 0x9487); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9487); auto const rel = std::vector<uint32_t>(1, 0x4f41); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f41); auto const rel = std::vector<uint32_t>(1, 0x20bcb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x20bcb); auto const rel = std::vector<uint32_t>(1, 0x653a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x653a); auto const rel = std::vector<uint32_t>(1, 0x77e3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77e3); auto const rel = std::vector<uint32_t>(1, 0x8094); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8094); auto const rel = std::vector<uint32_t>(1, 0x5ea1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5ea1); auto const rel = std::vector<uint32_t>(1, 0x8223); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8223); auto const rel = std::vector<uint32_t>(1, 0x82e1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x82e1); auto const rel = std::vector<uint32_t>(1, 0x82e2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x82e2); auto const rel = std::vector<uint32_t>(1, 0x8681); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8681); auto const rel = std::vector<uint32_t>(1, 0x91d4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91d4); auto const rel = std::vector<uint32_t>(1, 0x501a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x501a); auto const rel = std::vector<uint32_t>(1, 0x6246); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6246); auto const rel = std::vector<uint32_t>(1, 0x914f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x914f); auto const rel = std::vector<uint32_t>(1, 0x506f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x506f); auto const rel = std::vector<uint32_t>(1, 0x7b16); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7b16); auto const rel = std::vector<uint32_t>(1, 0x9018); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9018); auto const rel = std::vector<uint32_t>(1, 0x5d3a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5d3a); auto const rel = std::vector<uint32_t>(1, 0x65d1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x65d1); auto const rel = std::vector<uint32_t>(1, 0x6905); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6905); auto const rel = std::vector<uint32_t>(1, 0x9ce6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ce6); auto const rel = std::vector<uint32_t>(1, 0x926f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x926f); auto const rel = std::vector<uint32_t>(1, 0x65d6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x65d6); auto const rel = std::vector<uint32_t>(1, 0x88ff); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x88ff); auto const rel = std::vector<uint32_t>(1, 0x8e26); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e26); auto const rel = std::vector<uint32_t>(1, 0x8f22); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f22); auto const rel = std::vector<uint32_t>(1, 0x657c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x657c); auto const rel = std::vector<uint32_t>(1, 0x8798); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8798); auto const rel = std::vector<uint32_t>(1, 0x49e7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x49e7); auto const rel = std::vector<uint32_t>(1, 0x6aa5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6aa5); auto const rel = std::vector<uint32_t>(1, 0x4b72); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4b72); auto const rel = std::vector<uint32_t>(1, 0x7912); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7912); auto const rel = std::vector<uint32_t>(1, 0x8264); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8264); auto const rel = std::vector<uint32_t>(1, 0x87fb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x87fb); auto const rel = std::vector<uint32_t>(1, 0x9857); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9857); auto const rel = std::vector<uint32_t>(1, 0x8f59); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f59); auto const rel = std::vector<uint32_t>(1, 0x9f6e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f6e); auto const rel = std::vector<uint32_t>(1, 0x4e42); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e42); auto const rel = std::vector<uint32_t>(1, 0x20086); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x20086); auto const rel = std::vector<uint32_t>(1, 0x4e49); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e49); auto const rel = std::vector<uint32_t>(1, 0x4ebf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4ebf); auto const rel = std::vector<uint32_t>(1, 0x5f0b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5f0b); auto const rel = std::vector<uint32_t>(1, 0x5208); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_007) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5208); auto const rel = std::vector<uint32_t>(1, 0x5fc6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5fc6); auto const rel = std::vector<uint32_t>(1, 0x808a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x808a); auto const rel = std::vector<uint32_t>(1, 0x827a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x827a); auto const rel = std::vector<uint32_t>(1, 0x8bae); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8bae); auto const rel = std::vector<uint32_t>(1, 0x4ea6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4ea6); auto const rel = std::vector<uint32_t>(1, 0x3439); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3439); auto const rel = std::vector<uint32_t>(1, 0x4f07); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f07); auto const rel = std::vector<uint32_t>(1, 0x5c79); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5c79); auto const rel = std::vector<uint32_t>(1, 0x5f02); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5f02); auto const rel = std::vector<uint32_t>(1, 0x4f3f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f3f); auto const rel = std::vector<uint32_t>(1, 0x4f5a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f5a); auto const rel = std::vector<uint32_t>(1, 0x52ae); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x52ae); auto const rel = std::vector<uint32_t>(1, 0x5453); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5453); auto const rel = std::vector<uint32_t>(1, 0x5744); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5744); auto const rel = std::vector<uint32_t>(1, 0x5f79); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5f79); auto const rel = std::vector<uint32_t>(1, 0x6291); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6291); auto const rel = std::vector<uint32_t>(1, 0x6759); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6759); auto const rel = std::vector<uint32_t>(1, 0x8034); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8034); auto const rel = std::vector<uint32_t>(1, 0x8285); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8285); auto const rel = std::vector<uint32_t>(1, 0x8bd1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8bd1); auto const rel = std::vector<uint32_t>(1, 0x9091); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9091); auto const rel = std::vector<uint32_t>(1, 0x4f7e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f7e); auto const rel = std::vector<uint32_t>(1, 0x546d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x546d); auto const rel = std::vector<uint32_t>(1, 0x5479); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5479); auto const rel = std::vector<uint32_t>(1, 0x5cc4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5cc4); auto const rel = std::vector<uint32_t>(1, 0x6008); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6008); auto const rel = std::vector<uint32_t>(1, 0x603f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x603f); auto const rel = std::vector<uint32_t>(1, 0x6613); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6613); auto const rel = std::vector<uint32_t>(1, 0x678d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x678d); auto const rel = std::vector<uint32_t>(1, 0x6b25); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b25); auto const rel = std::vector<uint32_t>(1, 0x3cd1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3cd1); auto const rel = std::vector<uint32_t>(1, 0x6cc6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6cc6); auto const rel = std::vector<uint32_t>(1, 0x7088); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7088); auto const rel = std::vector<uint32_t>(1, 0x79c7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x79c7); auto const rel = std::vector<uint32_t>(1, 0x7ece); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7ece); auto const rel = std::vector<uint32_t>(1, 0x82c5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x82c5); auto const rel = std::vector<uint32_t>(1, 0x8be3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8be3); auto const rel = std::vector<uint32_t>(1, 0x9a7f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a7f); auto const rel = std::vector<uint32_t>(1, 0x4fcb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4fcb); auto const rel = std::vector<uint32_t>(1, 0x5955); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5955); auto const rel = std::vector<uint32_t>(1, 0x5e1f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5e1f); auto const rel = std::vector<uint32_t>(1, 0x5e20); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5e20); auto const rel = std::vector<uint32_t>(1, 0x5f08); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5f08); auto const rel = std::vector<uint32_t>(1, 0x223d7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x223d7); auto const rel = std::vector<uint32_t>(1, 0x67bb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x67bb); auto const rel = std::vector<uint32_t>(1, 0x6d02); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6d02); auto const rel = std::vector<uint32_t>(1, 0x6d42); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6d42); auto const rel = std::vector<uint32_t>(1, 0x73b4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x73b4); auto const rel = std::vector<uint32_t>(1, 0x75ab); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x75ab); auto const rel = std::vector<uint32_t>(1, 0x7fbf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7fbf); auto const rel = std::vector<uint32_t>(1, 0x263f8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_008) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x263f8); auto const rel = std::vector<uint32_t>(1, 0x8f76); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f76); auto const rel = std::vector<uint32_t>(1, 0x3465); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3465); auto const rel = std::vector<uint32_t>(1, 0x5508); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5508); auto const rel = std::vector<uint32_t>(1, 0x57bc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x57bc); auto const rel = std::vector<uint32_t>(1, 0x6092); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6092); auto const rel = std::vector<uint32_t>(1, 0x6339); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6339); auto const rel = std::vector<uint32_t>(1, 0x6359); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6359); auto const rel = std::vector<uint32_t>(1, 0x6827); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6827); auto const rel = std::vector<uint32_t>(1, 0x683a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x683a); auto const rel = std::vector<uint32_t>(1, 0x6b2d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b2d); auto const rel = std::vector<uint32_t>(1, 0x6d65); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6d65); auto const rel = std::vector<uint32_t>(1, 0x6d73); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6d73); auto const rel = std::vector<uint32_t>(1, 0x76ca); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x76ca); auto const rel = std::vector<uint32_t>(1, 0x8875); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8875); auto const rel = std::vector<uint32_t>(1, 0x8c0a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8c0a); auto const rel = std::vector<uint32_t>(1, 0x52da); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x52da); auto const rel = std::vector<uint32_t>(1, 0x57f6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x57f6); auto const rel = std::vector<uint32_t>(1, 0x57f8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x57f8); auto const rel = std::vector<uint32_t>(1, 0x60a5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x60a5); auto const rel = std::vector<uint32_t>(1, 0x639c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x639c); auto const rel = std::vector<uint32_t>(1, 0x6bb9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6bb9); auto const rel = std::vector<uint32_t>(1, 0x7570); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7570); auto const rel = std::vector<uint32_t>(1, 0x785b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x785b); auto const rel = std::vector<uint32_t>(1, 0x7f9b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7f9b); auto const rel = std::vector<uint32_t>(1, 0x7fca); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7fca); auto const rel = std::vector<uint32_t>(1, 0x7fcc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7fcc); auto const rel = std::vector<uint32_t>(1, 0x88a3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x88a3); auto const rel = std::vector<uint32_t>(1, 0x8a32); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a32); auto const rel = std::vector<uint32_t>(1, 0x8a33); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a33); auto const rel = std::vector<uint32_t>(1, 0x8c59); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8c59); auto const rel = std::vector<uint32_t>(1, 0x8c5b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8c5b); auto const rel = std::vector<uint32_t>(1, 0x91f4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91f4); auto const rel = std::vector<uint32_t>(1, 0x966d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x966d); auto const rel = std::vector<uint32_t>(1, 0x96bf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x96bf); auto const rel = std::vector<uint32_t>(1, 0x5e46); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5e46); auto const rel = std::vector<uint32_t>(1, 0x6561); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6561); auto const rel = std::vector<uint32_t>(1, 0x6679); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6679); auto const rel = std::vector<uint32_t>(1, 0x68ed); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x68ed); auto const rel = std::vector<uint32_t>(1, 0x6b94); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b94); auto const rel = std::vector<uint32_t>(1, 0x6e59); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6e59); auto const rel = std::vector<uint32_t>(1, 0x7132); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7132); auto const rel = std::vector<uint32_t>(1, 0x2497f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x2497f); auto const rel = std::vector<uint32_t>(1, 0x433b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x433b); auto const rel = std::vector<uint32_t>(1, 0x86e1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x86e1); auto const rel = std::vector<uint32_t>(1, 0x8a4d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a4d); auto const rel = std::vector<uint32_t>(1, 0x8dc7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8dc7); auto const rel = std::vector<uint32_t>(1, 0x8efc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8efc); auto const rel = std::vector<uint32_t>(1, 0x9038); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9038); auto const rel = std::vector<uint32_t>(1, 0x9220); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9220); auto const rel = std::vector<uint32_t>(1, 0x4e84); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e84); auto const rel = std::vector<uint32_t>(1, 0x517f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_009) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x517f); auto const rel = std::vector<uint32_t>(1, 0x3534); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3534); auto const rel = std::vector<uint32_t>(1, 0x610f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x610f); auto const rel = std::vector<uint32_t>(1, 0x6ea2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6ea2); auto const rel = std::vector<uint32_t>(1, 0x7348); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7348); auto const rel = std::vector<uint32_t>(1, 0x75ec); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x75ec); auto const rel = std::vector<uint32_t>(1, 0x776a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x776a); auto const rel = std::vector<uint32_t>(1, 0x7ae9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7ae9); auto const rel = std::vector<uint32_t>(1, 0x41fc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x41fc); auto const rel = std::vector<uint32_t>(1, 0x7f22); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7f22); auto const rel = std::vector<uint32_t>(1, 0x7fa9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7fa9); auto const rel = std::vector<uint32_t>(1, 0x8084); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8084); auto const rel = std::vector<uint32_t>(1, 0x88d4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x88d4); auto const rel = std::vector<uint32_t>(1, 0x88db); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x88db); auto const rel = std::vector<uint32_t>(1, 0x8a63); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a63); auto const rel = std::vector<uint32_t>(1, 0x9aae); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9aae); auto const rel = std::vector<uint32_t>(1, 0x52e9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x52e9); auto const rel = std::vector<uint32_t>(1, 0x5ad5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5ad5); auto const rel = std::vector<uint32_t>(1, 0x5ed9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5ed9); auto const rel = std::vector<uint32_t>(1, 0x698f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x698f); auto const rel = std::vector<uint32_t>(1, 0x7617); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7617); auto const rel = std::vector<uint32_t>(1, 0x8189); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8189); auto const rel = std::vector<uint32_t>(1, 0x8734); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8734); auto const rel = std::vector<uint32_t>(1, 0x977e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x977e); auto const rel = std::vector<uint32_t>(1, 0x99c5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x99c5); auto const rel = std::vector<uint32_t>(1, 0x5104); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5104); auto const rel = std::vector<uint32_t>(1, 0x3989); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3989); auto const rel = std::vector<uint32_t>(1, 0x648e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x648e); auto const rel = std::vector<uint32_t>(1, 0x69f8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x69f8); auto const rel = std::vector<uint32_t>(1, 0x6bc5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6bc5); auto const rel = std::vector<uint32_t>(1, 0x6f69); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6f69); auto const rel = std::vector<uint32_t>(1, 0x71a0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x71a0); auto const rel = std::vector<uint32_t>(1, 0x71a4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x71a4); auto const rel = std::vector<uint32_t>(1, 0x761e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x761e); auto const rel = std::vector<uint32_t>(1, 0x84fa); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x84fa); auto const rel = std::vector<uint32_t>(1, 0x8abc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8abc); auto const rel = std::vector<uint32_t>(1, 0x9552); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9552); auto const rel = std::vector<uint32_t>(1, 0x9e5d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e5d); auto const rel = std::vector<uint32_t>(1, 0x9e62); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e62); auto const rel = std::vector<uint32_t>(1, 0x9ed3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ed3); auto const rel = std::vector<uint32_t>(1, 0x5293); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5293); auto const rel = std::vector<uint32_t>(1, 0x3601); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3601); auto const rel = std::vector<uint32_t>(1, 0x571b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x571b); auto const rel = std::vector<uint32_t>(1, 0x58bf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x58bf); auto const rel = std::vector<uint32_t>(1, 0x5b11); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b11); auto const rel = std::vector<uint32_t>(1, 0x5b1f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b1f); auto const rel = std::vector<uint32_t>(1, 0x5da7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5da7); auto const rel = std::vector<uint32_t>(1, 0x61b6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x61b6); auto const rel = std::vector<uint32_t>(1, 0x61cc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x61cc); auto const rel = std::vector<uint32_t>(1, 0x66c0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66c0); auto const rel = std::vector<uint32_t>(1, 0x6baa); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6baa); auto const rel = std::vector<uint32_t>(1, 0x3d69); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_010) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3d69); auto const rel = std::vector<uint32_t>(1, 0x6fba); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6fba); auto const rel = std::vector<uint32_t>(1, 0x71bc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x71bc); auto const rel = std::vector<uint32_t>(1, 0x71da); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x71da); auto const rel = std::vector<uint32_t>(1, 0x7631); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7631); auto const rel = std::vector<uint32_t>(1, 0x7796); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7796); auto const rel = std::vector<uint32_t>(1, 0x7a53); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7a53); auto const rel = std::vector<uint32_t>(1, 0x7e0a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e0a); auto const rel = std::vector<uint32_t>(1, 0x8257); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8257); auto const rel = std::vector<uint32_t>(1, 0x87a0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x87a0); auto const rel = std::vector<uint32_t>(1, 0x5bf1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5bf1); auto const rel = std::vector<uint32_t>(1, 0x6581); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6581); auto const rel = std::vector<uint32_t>(1, 0x66ce); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66ce); auto const rel = std::vector<uint32_t>(1, 0x6a8d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6a8d); auto const rel = std::vector<uint32_t>(1, 0x6b5d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b5d); auto const rel = std::vector<uint32_t>(1, 0x71e1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x71e1); auto const rel = std::vector<uint32_t>(1, 0x71f1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x71f1); auto const rel = std::vector<uint32_t>(1, 0x7ff3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7ff3); auto const rel = std::vector<uint32_t>(1, 0x7ffc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7ffc); auto const rel = std::vector<uint32_t>(1, 0x81c6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x81c6); auto const rel = std::vector<uint32_t>(1, 0x858f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x858f); auto const rel = std::vector<uint32_t>(1, 0x8939); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8939); auto const rel = std::vector<uint32_t>(1, 0x8cf9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8cf9); auto const rel = std::vector<uint32_t>(1, 0x9ba8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ba8); auto const rel = std::vector<uint32_t>(1, 0x7654); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7654); auto const rel = std::vector<uint32_t>(1, 0x8d00); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8d00); auto const rel = std::vector<uint32_t>(1, 0x93b0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x93b0); auto const rel = std::vector<uint32_t>(1, 0x9571); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9571); auto const rel = std::vector<uint32_t>(1, 0x7e76); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e76); auto const rel = std::vector<uint32_t>(1, 0x7e79); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e79); auto const rel = std::vector<uint32_t>(1, 0x85d9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x85d9); auto const rel = std::vector<uint32_t>(1, 0x85dd); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x85dd); auto const rel = std::vector<uint32_t>(1, 0x8c77); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8c77); auto const rel = std::vector<uint32_t>(1, 0x972c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x972c); auto const rel = std::vector<uint32_t>(1, 0x9be3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9be3); auto const rel = std::vector<uint32_t>(1, 0x9d82); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d82); auto const rel = std::vector<uint32_t>(1, 0x9d83); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d83); auto const rel = std::vector<uint32_t>(1, 0x39a4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x39a4); auto const rel = std::vector<uint32_t>(1, 0x7037); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7037); auto const rel = std::vector<uint32_t>(1, 0x8b6f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b6f); auto const rel = std::vector<uint32_t>(1, 0x8b70); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b70); auto const rel = std::vector<uint32_t>(1, 0x91b3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91b3); auto const rel = std::vector<uint32_t>(1, 0x91b7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91b7); auto const rel = std::vector<uint32_t>(1, 0x9950); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9950); auto const rel = std::vector<uint32_t>(1, 0x2113b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x2113b); auto const rel = std::vector<uint32_t>(1, 0x25725); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x25725); auto const rel = std::vector<uint32_t>(1, 0x8619); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8619); auto const rel = std::vector<uint32_t>(1, 0x943f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x943f); auto const rel = std::vector<uint32_t>(1, 0x9dc1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dc1); auto const rel = std::vector<uint32_t>(1, 0x9dca); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dca); auto const rel = std::vector<uint32_t>(1, 0x56c8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56c8); auto const rel = std::vector<uint32_t>(1, 0x61ff); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_011) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x61ff); auto const rel = std::vector<uint32_t>(1, 0x9a5b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a5b); auto const rel = std::vector<uint32_t>(1, 0x9de7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9de7); auto const rel = std::vector<uint32_t>(1, 0x9dfe); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dfe); auto const rel = std::vector<uint32_t>(1, 0x8649); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8649); auto const rel = std::vector<uint32_t>(1, 0x897c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x897c); auto const rel = std::vector<uint32_t>(1, 0x9f78); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f78); auto const rel = std::vector<uint32_t>(1, 0x8b9b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b9b); auto const rel = std::vector<uint32_t>(1, 0x5307); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5307); auto const rel = std::vector<uint32_t>(1, 0x8fb7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8fb7); auto const rel = std::vector<uint32_t>(1, 0x7569); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7569); auto const rel = std::vector<uint32_t>(1, 0x692c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x692c); auto const rel = std::vector<uint32_t>(1, 0x841f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x841f); auto const rel = std::vector<uint32_t>(1, 0x9d8d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d8d); auto const rel = std::vector<uint32_t>(1, 0x7c4e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c4e); auto const rel = std::vector<uint32_t>(1, 0x4e2b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e2b); auto const rel = std::vector<uint32_t>(1, 0x5727); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5727); auto const rel = std::vector<uint32_t>(1, 0x538b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x538b); auto const rel = std::vector<uint32_t>(1, 0x5416); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5416); auto const rel = std::vector<uint32_t>(1, 0x5e98); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5e98); auto const rel = std::vector<uint32_t>(1, 0x62bc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x62bc); auto const rel = std::vector<uint32_t>(1, 0x6792); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6792); auto const rel = std::vector<uint32_t>(1, 0x57ad); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x57ad); auto const rel = std::vector<uint32_t>(1, 0x9e26); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e26); auto const rel = std::vector<uint32_t>(1, 0x6860); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6860); auto const rel = std::vector<uint32_t>(1, 0x9e2d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e2d); auto const rel = std::vector<uint32_t>(1, 0x57e1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x57e1); auto const rel = std::vector<uint32_t>(1, 0x5b72); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b72); auto const rel = std::vector<uint32_t>(1, 0x690f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x690f); auto const rel = std::vector<uint32_t>(1, 0x9d09); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d09); auto const rel = std::vector<uint32_t>(1, 0x930f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x930f); auto const rel = std::vector<uint32_t>(1, 0x9d28); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d28); auto const rel = std::vector<uint32_t>(1, 0x58d3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x58d3); auto const rel = std::vector<uint32_t>(1, 0x9d76); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d76); auto const rel = std::vector<uint32_t>(1, 0x941a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x941a); auto const rel = std::vector<uint32_t>(1, 0x7259); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7259); auto const rel = std::vector<uint32_t>(1, 0x4f22); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f22); auto const rel = std::vector<uint32_t>(1, 0x5391); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5391); auto const rel = std::vector<uint32_t>(1, 0x5c88); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5c88); auto const rel = std::vector<uint32_t>(1, 0x5393); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5393); auto const rel = std::vector<uint32_t>(1, 0x73a1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x73a1); auto const rel = std::vector<uint32_t>(1, 0x82bd); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x82bd); auto const rel = std::vector<uint32_t>(1, 0x7b0c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7b0c); auto const rel = std::vector<uint32_t>(1, 0x869c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x869c); auto const rel = std::vector<uint32_t>(1, 0x5810); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5810); auto const rel = std::vector<uint32_t>(1, 0x5d15); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5d15); auto const rel = std::vector<uint32_t>(1, 0x5d16); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5d16); auto const rel = std::vector<uint32_t>(1, 0x6daf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6daf); auto const rel = std::vector<uint32_t>(1, 0x731a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x731a); auto const rel = std::vector<uint32_t>(1, 0x740a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x740a); auto const rel = std::vector<uint32_t>(1, 0x7458); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7458); auto const rel = std::vector<uint32_t>(1, 0x775a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_012) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x775a); auto const rel = std::vector<uint32_t>(1, 0x8859); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8859); auto const rel = std::vector<uint32_t>(1, 0x6f04); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6f04); auto const rel = std::vector<uint32_t>(1, 0x9f56); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f56); auto const rel = std::vector<uint32_t>(1, 0x2a632); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x2a632); auto const rel = std::vector<uint32_t>(1, 0x24d13); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x24d13); auto const rel = std::vector<uint32_t>(1, 0x538a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x538a); auto const rel = std::vector<uint32_t>(1, 0x5e8c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5e8c); auto const rel = std::vector<uint32_t>(1, 0x54d1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x54d1); auto const rel = std::vector<uint32_t>(1, 0x5516); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5516); auto const rel = std::vector<uint32_t>(1, 0x555e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x555e); auto const rel = std::vector<uint32_t>(1, 0x75d6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x75d6); auto const rel = std::vector<uint32_t>(1, 0x96c5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x96c5); auto const rel = std::vector<uint32_t>(1, 0x7602); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7602); auto const rel = std::vector<uint32_t>(1, 0x279dd); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x279dd); auto const rel = std::vector<uint32_t>(1, 0x8565); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8565); auto const rel = std::vector<uint32_t>(1, 0x529c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x529c); auto const rel = std::vector<uint32_t>(1, 0x5720); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5720); auto const rel = std::vector<uint32_t>(1, 0x8f67); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f67); auto const rel = std::vector<uint32_t>(1, 0x4e9a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e9a); auto const rel = std::vector<uint32_t>(1, 0x897e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x897e); auto const rel = std::vector<uint32_t>(1, 0x8bb6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8bb6); auto const rel = std::vector<uint32_t>(1, 0x4e9c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e9c); auto const rel = std::vector<uint32_t>(1, 0x72bd); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x72bd); auto const rel = std::vector<uint32_t>(1, 0x4e9e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e9e); auto const rel = std::vector<uint32_t>(1, 0x8ecb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8ecb); auto const rel = std::vector<uint32_t>(1, 0x8fd3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8fd3); auto const rel = std::vector<uint32_t>(1, 0x5a05); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5a05); auto const rel = std::vector<uint32_t>(1, 0x631c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x631c); auto const rel = std::vector<uint32_t>(1, 0x7811); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7811); auto const rel = std::vector<uint32_t>(1, 0x4ff9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4ff9); auto const rel = std::vector<uint32_t>(1, 0x6c29); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6c29); auto const rel = std::vector<uint32_t>(1, 0x5a6d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5a6d); auto const rel = std::vector<uint32_t>(1, 0x6397); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6397); auto const rel = std::vector<uint32_t>(1, 0x8a1d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a1d); auto const rel = std::vector<uint32_t>(1, 0x94d4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x94d4); auto const rel = std::vector<uint32_t>(1, 0x63e0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x63e0); auto const rel = std::vector<uint32_t>(1, 0x6c2c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6c2c); auto const rel = std::vector<uint32_t>(1, 0x7330); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7330); auto const rel = std::vector<uint32_t>(1, 0x8050); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8050); auto const rel = std::vector<uint32_t>(1, 0x26716); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x26716); auto const rel = std::vector<uint32_t>(1, 0x5714); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5714); auto const rel = std::vector<uint32_t>(1, 0x7a0f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7a0f); auto const rel = std::vector<uint32_t>(1, 0x7aab); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7aab); auto const rel = std::vector<uint32_t>(1, 0x9f7e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f7e); auto const rel = std::vector<uint32_t>(1, 0x2e84); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x2e84); auto const rel = std::vector<uint32_t>(1, 0x4e5b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e5b); auto const rel = std::vector<uint32_t>(1, 0x5440); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5440); auto const rel = std::vector<uint32_t>(1, 0x54df); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x54df); auto const rel = std::vector<uint32_t>(1, 0x5537); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5537); auto const rel = std::vector<uint32_t>(1, 0x55b2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x55b2); auto const rel = std::vector<uint32_t>(1, 0x503b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_013) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x503b); auto const rel = std::vector<uint32_t>(1, 0x6396); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6396); auto const rel = std::vector<uint32_t>(1, 0x668d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x668d); auto const rel = std::vector<uint32_t>(1, 0x6930); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6930); auto const rel = std::vector<uint32_t>(1, 0x564e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x564e); auto const rel = std::vector<uint32_t>(1, 0x6f71); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6f71); auto const rel = std::vector<uint32_t>(1, 0x882e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x882e); auto const rel = std::vector<uint32_t>(1, 0x7237); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7237); auto const rel = std::vector<uint32_t>(1, 0x8036); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8036); auto const rel = std::vector<uint32_t>(1, 0x6353); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6353); auto const rel = std::vector<uint32_t>(1, 0x94d8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x94d8); auto const rel = std::vector<uint32_t>(1, 0x63f6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x63f6); auto const rel = std::vector<uint32_t>(1, 0x91fe); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91fe); auto const rel = std::vector<uint32_t>(1, 0x723a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x723a); auto const rel = std::vector<uint32_t>(1, 0x92e3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x92e3); auto const rel = std::vector<uint32_t>(1, 0x64e8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x64e8); auto const rel = std::vector<uint32_t>(1, 0x9381); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9381); auto const rel = std::vector<uint32_t>(1, 0x4e5f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e5f); auto const rel = std::vector<uint32_t>(1, 0x5414); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5414); auto const rel = std::vector<uint32_t>(1, 0x51b6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x51b6); auto const rel = std::vector<uint32_t>(1, 0x57dc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x57dc); auto const rel = std::vector<uint32_t>(1, 0x91ce); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91ce); auto const rel = std::vector<uint32_t>(1, 0x5622); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5622); auto const rel = std::vector<uint32_t>(1, 0x6f1c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6f1c); auto const rel = std::vector<uint32_t>(1, 0x58c4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x58c4); auto const rel = std::vector<uint32_t>(1, 0x4e1a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e1a); auto const rel = std::vector<uint32_t>(1, 0x53f6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x53f6); auto const rel = std::vector<uint32_t>(1, 0x66f3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66f3); auto const rel = std::vector<uint32_t>(1, 0x9875); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9875); auto const rel = std::vector<uint32_t>(1, 0x66f5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66f5); auto const rel = std::vector<uint32_t>(1, 0x591c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x591c); auto const rel = std::vector<uint32_t>(1, 0x62b4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x62b4); auto const rel = std::vector<uint32_t>(1, 0x90ba); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x90ba); auto const rel = std::vector<uint32_t>(1, 0x4eb1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4eb1); auto const rel = std::vector<uint32_t>(1, 0x67bc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x67bc); auto const rel = std::vector<uint32_t>(1, 0x9801); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9801); auto const rel = std::vector<uint32_t>(1, 0x6654); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6654); auto const rel = std::vector<uint32_t>(1, 0x67bd); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x67bd); auto const rel = std::vector<uint32_t>(1, 0x70e8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x70e8); auto const rel = std::vector<uint32_t>(1, 0x35a1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x35a1); auto const rel = std::vector<uint32_t>(1, 0x5558); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5558); auto const rel = std::vector<uint32_t>(1, 0x6db2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6db2); auto const rel = std::vector<uint32_t>(1, 0x8c12); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8c12); auto const rel = std::vector<uint32_t>(1, 0x5828); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5828); auto const rel = std::vector<uint32_t>(1, 0x6b97); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b97); auto const rel = std::vector<uint32_t>(1, 0x814b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x814b); auto const rel = std::vector<uint32_t>(1, 0x696a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x696a); auto const rel = std::vector<uint32_t>(1, 0x696d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x696d); auto const rel = std::vector<uint32_t>(1, 0x8449); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8449); auto const rel = std::vector<uint32_t>(1, 0x9113); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9113); auto const rel = std::vector<uint32_t>(1, 0x998c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x998c); auto const rel = std::vector<uint32_t>(1, 0x50f7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_014) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x50f7); auto const rel = std::vector<uint32_t>(1, 0x6b4b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b4b); auto const rel = std::vector<uint32_t>(1, 0x58b7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x58b7); auto const rel = std::vector<uint32_t>(1, 0x420e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x420e); auto const rel = std::vector<uint32_t>(1, 0x9765); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9765); auto const rel = std::vector<uint32_t>(1, 0x5daa); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5daa); auto const rel = std::vector<uint32_t>(1, 0x5dab); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5dab); auto const rel = std::vector<uint32_t>(1, 0x64db); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x64db); auto const rel = std::vector<uint32_t>(1, 0x66c4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66c4); auto const rel = std::vector<uint32_t>(1, 0x66c5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66c5); auto const rel = std::vector<uint32_t>(1, 0x6fb2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6fb2); auto const rel = std::vector<uint32_t>(1, 0x71c1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x71c1); auto const rel = std::vector<uint32_t>(1, 0x2681c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x2681c); auto const rel = std::vector<uint32_t>(1, 0x8b01); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b01); auto const rel = std::vector<uint32_t>(1, 0x9134); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9134); auto const rel = std::vector<uint32_t>(1, 0x9923); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9923); auto const rel = std::vector<uint32_t>(1, 0x5688); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5688); auto const rel = std::vector<uint32_t>(1, 0x64eb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x64eb); auto const rel = std::vector<uint32_t>(1, 0x66d7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66d7); auto const rel = std::vector<uint32_t>(1, 0x76a3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x76a3); auto const rel = std::vector<uint32_t>(1, 0x77b1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77b1); auto const rel = std::vector<uint32_t>(1, 0x9371); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9371); auto const rel = std::vector<uint32_t>(1, 0x64ea); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x64ea); auto const rel = std::vector<uint32_t>(1, 0x77b8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77b8); auto const rel = std::vector<uint32_t>(1, 0x790f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x790f); auto const rel = std::vector<uint32_t>(1, 0x42a6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x42a6); auto const rel = std::vector<uint32_t>(1, 0x9391); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9391); auto const rel = std::vector<uint32_t>(1, 0x9941); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9941); auto const rel = std::vector<uint32_t>(1, 0x9d7a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d7a); auto const rel = std::vector<uint32_t>(1, 0x7217); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7217); auto const rel = std::vector<uint32_t>(1, 0x9437); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9437); auto const rel = std::vector<uint32_t>(1, 0x9768); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9768); auto const rel = std::vector<uint32_t>(1, 0x9a5c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a5c); auto const rel = std::vector<uint32_t>(1, 0x9e08); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e08); auto const rel = std::vector<uint32_t>(1, 0x4eaa); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4eaa); auto const rel = std::vector<uint32_t>(1, 0x5e7a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5e7a); auto const rel = std::vector<uint32_t>(1, 0x592d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x592d); auto const rel = std::vector<uint32_t>(1, 0x5406); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5406); auto const rel = std::vector<uint32_t>(1, 0x5996); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5996); auto const rel = std::vector<uint32_t>(1, 0x6796); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6796); auto const rel = std::vector<uint32_t>(1, 0x6b80); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b80); auto const rel = std::vector<uint32_t>(1, 0x7945); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7945); auto const rel = std::vector<uint32_t>(1, 0x8a1e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a1e); auto const rel = std::vector<uint32_t>(1, 0x5593); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5593); auto const rel = std::vector<uint32_t>(1, 0x6946); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6946); auto const rel = std::vector<uint32_t>(1, 0x8170); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8170); auto const rel = std::vector<uint32_t>(1, 0x847d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x847d); auto const rel = std::vector<uint32_t>(1, 0x4301); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4301); auto const rel = std::vector<uint32_t>(1, 0x4645); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4645); auto const rel = std::vector<uint32_t>(1, 0x9d01); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d01); auto const rel = std::vector<uint32_t>(1, 0x9080); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9080); auto const rel = std::vector<uint32_t>(1, 0x723b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_015) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x723b); auto const rel = std::vector<uint32_t>(1, 0x5c27); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5c27); auto const rel = std::vector<uint32_t>(1, 0x5c2d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5c2d); auto const rel = std::vector<uint32_t>(1, 0x80b4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x80b4); auto const rel = std::vector<uint32_t>(1, 0x579a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x579a); auto const rel = std::vector<uint32_t>(1, 0x59da); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x59da); auto const rel = std::vector<uint32_t>(1, 0x5ce3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5ce3); auto const rel = std::vector<uint32_t>(1, 0x409a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x409a); auto const rel = std::vector<uint32_t>(1, 0x8f7a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f7a); auto const rel = std::vector<uint32_t>(1, 0x5004); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5004); auto const rel = std::vector<uint32_t>(1, 0x70d1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x70d1); auto const rel = std::vector<uint32_t>(1, 0x73e7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x73e7); auto const rel = std::vector<uint32_t>(1, 0x7a91); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7a91); auto const rel = std::vector<uint32_t>(1, 0x509c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x509c); auto const rel = std::vector<uint32_t>(1, 0x582f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x582f); auto const rel = std::vector<uint32_t>(1, 0x63fa); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x63fa); auto const rel = std::vector<uint32_t>(1, 0x8c23); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8c23); auto const rel = std::vector<uint32_t>(1, 0x8efa); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8efa); auto const rel = std::vector<uint32_t>(1, 0x347e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x347e); auto const rel = std::vector<uint32_t>(1, 0x55c2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x55c2); auto const rel = std::vector<uint32_t>(1, 0x5ab1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5ab1); auto const rel = std::vector<uint32_t>(1, 0x5fad); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5fad); auto const rel = std::vector<uint32_t>(1, 0x612e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x612e); auto const rel = std::vector<uint32_t>(1, 0x6416); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6416); auto const rel = std::vector<uint32_t>(1, 0x6447); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6447); auto const rel = std::vector<uint32_t>(1, 0x733a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x733a); auto const rel = std::vector<uint32_t>(1, 0x3a31); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3a31); auto const rel = std::vector<uint32_t>(1, 0x669a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x669a); auto const rel = std::vector<uint32_t>(1, 0x69a3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x69a3); auto const rel = std::vector<uint32_t>(1, 0x7464); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7464); auto const rel = std::vector<uint32_t>(1, 0x7476); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7476); auto const rel = std::vector<uint32_t>(1, 0x9059); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9059); auto const rel = std::vector<uint32_t>(1, 0x9065); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9065); auto const rel = std::vector<uint32_t>(1, 0x929a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x929a); auto const rel = std::vector<uint32_t>(1, 0x98d6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x98d6); auto const rel = std::vector<uint32_t>(1, 0x9906); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9906); auto const rel = std::vector<uint32_t>(1, 0x5da2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5da2); auto const rel = std::vector<uint32_t>(1, 0x5da4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5da4); auto const rel = std::vector<uint32_t>(1, 0x7aaf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7aaf); auto const rel = std::vector<uint32_t>(1, 0x7ab0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7ab0); auto const rel = std::vector<uint32_t>(1, 0x4504); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4504); auto const rel = std::vector<uint32_t>(1, 0x991a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x991a); auto const rel = std::vector<uint32_t>(1, 0x7e47); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e47); auto const rel = std::vector<uint32_t>(1, 0x8b20); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b20); auto const rel = std::vector<uint32_t>(1, 0x8b21); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b21); auto const rel = std::vector<uint32_t>(1, 0x26fbe); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x26fbe); auto const rel = std::vector<uint32_t>(1, 0x9390); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9390); auto const rel = std::vector<uint32_t>(1, 0x9cd0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9cd0); auto const rel = std::vector<uint32_t>(1, 0x4b19); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4b19); auto const rel = std::vector<uint32_t>(1, 0x98bb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x98bb); auto const rel = std::vector<uint32_t>(1, 0x8628); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8628); auto const rel = std::vector<uint32_t>(1, 0x908e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_016) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x908e); auto const rel = std::vector<uint32_t>(1, 0x9864); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9864); auto const rel = std::vector<uint32_t>(1, 0x9c29); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c29); auto const rel = std::vector<uint32_t>(1, 0x4ef8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4ef8); auto const rel = std::vector<uint32_t>(1, 0x5b8e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b8e); auto const rel = std::vector<uint32_t>(1, 0x5c86); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5c86); auto const rel = std::vector<uint32_t>(1, 0x62ad); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x62ad); auto const rel = std::vector<uint32_t>(1, 0x6773); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6773); auto const rel = std::vector<uint32_t>(1, 0x72d5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x72d5); auto const rel = std::vector<uint32_t>(1, 0x54ac); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x54ac); auto const rel = std::vector<uint32_t>(1, 0x67fc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x67fc); auto const rel = std::vector<uint32_t>(1, 0x82ed); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x82ed); auto const rel = std::vector<uint32_t>(1, 0x7711); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7711); auto const rel = std::vector<uint32_t>(1, 0x7a85); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7a85); auto const rel = std::vector<uint32_t>(1, 0x7a88); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7a88); auto const rel = std::vector<uint32_t>(1, 0x8200); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8200); auto const rel = std::vector<uint32_t>(1, 0x5060); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5060); auto const rel = std::vector<uint32_t>(1, 0x5a79); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5a79); auto const rel = std::vector<uint32_t>(1, 0x5d3e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5d3e); auto const rel = std::vector<uint32_t>(1, 0x6e94); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6e94); auto const rel = std::vector<uint32_t>(1, 0x699a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x699a); auto const rel = std::vector<uint32_t>(1, 0x84d4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x84d4); auto const rel = std::vector<uint32_t>(1, 0x9d22); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d22); auto const rel = std::vector<uint32_t>(1, 0x9f3c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f3c); auto const rel = std::vector<uint32_t>(1, 0x95c4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x95c4); auto const rel = std::vector<uint32_t>(1, 0x9a15); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a15); auto const rel = std::vector<uint32_t>(1, 0x9f69); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f69); auto const rel = std::vector<uint32_t>(1, 0x9dd5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dd5); auto const rel = std::vector<uint32_t>(1, 0x7a7e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7a7e); auto const rel = std::vector<uint32_t>(1, 0x8981); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8981); auto const rel = std::vector<uint32_t>(1, 0x94a5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x94a5); auto const rel = std::vector<uint32_t>(1, 0x25052); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x25052); auto const rel = std::vector<uint32_t>(1, 0x836f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x836f); auto const rel = std::vector<uint32_t>(1, 0x7a94); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7a94); auto const rel = std::vector<uint32_t>(1, 0x888e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x888e); auto const rel = std::vector<uint32_t>(1, 0x7b44); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7b44); auto const rel = std::vector<uint32_t>(1, 0x8a4f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a4f); auto const rel = std::vector<uint32_t>(1, 0x846f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x846f); auto const rel = std::vector<uint32_t>(1, 0x718e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x718e); auto const rel = std::vector<uint32_t>(1, 0x899e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x899e); auto const rel = std::vector<uint32_t>(1, 0x977f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x977f); auto const rel = std::vector<uint32_t>(1, 0x735f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x735f); auto const rel = std::vector<uint32_t>(1, 0x9e5e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e5e); auto const rel = std::vector<uint32_t>(1, 0x25aaf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x25aaf); auto const rel = std::vector<uint32_t>(1, 0x85ac); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x85ac); auto const rel = std::vector<uint32_t>(1, 0x66dc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66dc); auto const rel = std::vector<uint32_t>(1, 0x71ff); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x71ff); auto const rel = std::vector<uint32_t>(1, 0x825e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x825e); auto const rel = std::vector<uint32_t>(1, 0x77c5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77c5); auto const rel = std::vector<uint32_t>(1, 0x85e5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x85e5); auto const rel = std::vector<uint32_t>(1, 0x8000); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8000); auto const rel = std::vector<uint32_t>(1, 0x7e85); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_017) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e85); auto const rel = std::vector<uint32_t>(1, 0x9dc2); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dc2); auto const rel = std::vector<uint32_t>(1, 0x8b91); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b91); auto const rel = std::vector<uint32_t>(1, 0x9470); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9470); auto const rel = std::vector<uint32_t>(1, 0x4f18); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f18); auto const rel = std::vector<uint32_t>(1, 0x5fe7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5fe7); auto const rel = std::vector<uint32_t>(1, 0x6538); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6538); auto const rel = std::vector<uint32_t>(1, 0x5466); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5466); auto const rel = std::vector<uint32_t>(1, 0x602e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x602e); auto const rel = std::vector<uint32_t>(1, 0x6cd1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6cd1); auto const rel = std::vector<uint32_t>(1, 0x5e7d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5e7d); auto const rel = std::vector<uint32_t>(1, 0x60a0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x60a0); auto const rel = std::vector<uint32_t>(1, 0x900c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x900c); auto const rel = std::vector<uint32_t>(1, 0x9e80); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e80); auto const rel = std::vector<uint32_t>(1, 0x6efa); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6efa); auto const rel = std::vector<uint32_t>(1, 0x6182); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6182); auto const rel = std::vector<uint32_t>(1, 0x512a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x512a); auto const rel = std::vector<uint32_t>(1, 0x5698); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5698); auto const rel = std::vector<uint32_t>(1, 0x7000); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7000); auto const rel = std::vector<uint32_t>(1, 0x913e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x913e); auto const rel = std::vector<uint32_t>(1, 0x6acc); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6acc); auto const rel = std::vector<uint32_t>(1, 0x7e8b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e8b); auto const rel = std::vector<uint32_t>(1, 0x8030); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8030); auto const rel = std::vector<uint32_t>(1, 0x5c22); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5c22); auto const rel = std::vector<uint32_t>(1, 0x5c24); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5c24); auto const rel = std::vector<uint32_t>(1, 0x7531); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7531); auto const rel = std::vector<uint32_t>(1, 0x6c8b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6c8b); auto const rel = std::vector<uint32_t>(1, 0x72b9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x72b9); auto const rel = std::vector<uint32_t>(1, 0x3f55); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3f55); auto const rel = std::vector<uint32_t>(1, 0x233de); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x233de); auto const rel = std::vector<uint32_t>(1, 0x6cb9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6cb9); auto const rel = std::vector<uint32_t>(1, 0x80ac); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x80ac); auto const rel = std::vector<uint32_t>(1, 0x90ae); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x90ae); auto const rel = std::vector<uint32_t>(1, 0x6023); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6023); auto const rel = std::vector<uint32_t>(1, 0x65bf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x65bf); auto const rel = std::vector<uint32_t>(1, 0x75a3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x75a3); auto const rel = std::vector<uint32_t>(1, 0x5cf3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5cf3); auto const rel = std::vector<uint32_t>(1, 0x6d5f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6d5f); auto const rel = std::vector<uint32_t>(1, 0x79de); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x79de); auto const rel = std::vector<uint32_t>(1, 0x4343); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4343); auto const rel = std::vector<uint32_t>(1, 0x94c0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x94c0); auto const rel = std::vector<uint32_t>(1, 0x5064); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5064); auto const rel = std::vector<uint32_t>(1, 0x839c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x839c); auto const rel = std::vector<uint32_t>(1, 0x83b8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x83b8); auto const rel = std::vector<uint32_t>(1, 0x86b0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x86b0); auto const rel = std::vector<uint32_t>(1, 0x8a27); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a27); auto const rel = std::vector<uint32_t>(1, 0x6e38); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6e38); auto const rel = std::vector<uint32_t>(1, 0x7336); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7336); auto const rel = std::vector<uint32_t>(1, 0x9030); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9030); auto const rel = std::vector<uint32_t>(1, 0x90f5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x90f5); auto const rel = std::vector<uint32_t>(1, 0x9c7f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c7f); auto const rel = std::vector<uint32_t>(1, 0x6962); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_018) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6962); auto const rel = std::vector<uint32_t>(1, 0x7337); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7337); auto const rel = std::vector<uint32_t>(1, 0x904a); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x904a); auto const rel = std::vector<uint32_t>(1, 0x923e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x923e); auto const rel = std::vector<uint32_t>(1, 0x9c89); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c89); auto const rel = std::vector<uint32_t>(1, 0x8f0f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f0f); auto const rel = std::vector<uint32_t>(1, 0x99c0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x99c0); auto const rel = std::vector<uint32_t>(1, 0x8763); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8763); auto const rel = std::vector<uint32_t>(1, 0x9b77); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b77); auto const rel = std::vector<uint32_t>(1, 0x8555); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8555); auto const rel = std::vector<uint32_t>(1, 0x8f36); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f36); auto const rel = std::vector<uint32_t>(1, 0x9b8b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b8b); auto const rel = std::vector<uint32_t>(1, 0x6afe); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6afe); auto const rel = std::vector<uint32_t>(1, 0x53cb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x53cb); auto const rel = std::vector<uint32_t>(1, 0x6709); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6709); auto const rel = std::vector<uint32_t>(1, 0x4e23); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4e23); auto const rel = std::vector<uint32_t>(1, 0x5363); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5363); auto const rel = std::vector<uint32_t>(1, 0x9149); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9149); auto const rel = std::vector<uint32_t>(1, 0x82c3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x82c3); auto const rel = std::vector<uint32_t>(1, 0x3dad); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x3dad); auto const rel = std::vector<uint32_t>(1, 0x7f91); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7f91); auto const rel = std::vector<uint32_t>(1, 0x5eae); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5eae); auto const rel = std::vector<uint32_t>(1, 0x682f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x682f); auto const rel = std::vector<uint32_t>(1, 0x7f90); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7f90); auto const rel = std::vector<uint32_t>(1, 0x6884); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6884); auto const rel = std::vector<uint32_t>(1, 0x8048); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8048); auto const rel = std::vector<uint32_t>(1, 0x811c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x811c); auto const rel = std::vector<uint32_t>(1, 0x83a0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x83a0); auto const rel = std::vector<uint32_t>(1, 0x94d5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x94d5); auto const rel = std::vector<uint32_t>(1, 0x6e75); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6e75); auto const rel = std::vector<uint32_t>(1, 0x870f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x870f); auto const rel = std::vector<uint32_t>(1, 0x7989); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7989); auto const rel = std::vector<uint32_t>(1, 0x92aa); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x92aa); auto const rel = std::vector<uint32_t>(1, 0x4b00); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4b00); auto const rel = std::vector<uint32_t>(1, 0x69f1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x69f1); auto const rel = std::vector<uint32_t>(1, 0x7256); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7256); auto const rel = std::vector<uint32_t>(1, 0x9edd); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9edd); auto const rel = std::vector<uint32_t>(1, 0x61ee); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x61ee); auto const rel = std::vector<uint32_t>(1, 0x2e80); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x2e80); auto const rel = std::vector<uint32_t>(1, 0x53c8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x53c8); auto const rel = std::vector<uint32_t>(1, 0x53f3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x53f3); auto const rel = std::vector<uint32_t>(1, 0x5e7c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5e7c); auto const rel = std::vector<uint32_t>(1, 0x4f51); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f51); auto const rel = std::vector<uint32_t>(1, 0x4f91); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4f91); auto const rel = std::vector<uint32_t>(1, 0x72d6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x72d6); auto const rel = std::vector<uint32_t>(1, 0x7cff); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7cff); auto const rel = std::vector<uint32_t>(1, 0x54ca); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x54ca); auto const rel = std::vector<uint32_t>(1, 0x56ff); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56ff); auto const rel = std::vector<uint32_t>(1, 0x59f7); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x59f7); auto const rel = std::vector<uint32_t>(1, 0x5ba5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5ba5); auto const rel = std::vector<uint32_t>(1, 0x5cdf); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5cdf); auto const rel = std::vector<uint32_t>(1, 0x67da); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_zhuyin_019_019) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x67da); auto const rel = std::vector<uint32_t>(1, 0x7270); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7270); auto const rel = std::vector<uint32_t>(1, 0x8bf1); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8bf1); auto const rel = std::vector<uint32_t>(1, 0x5500); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5500); auto const rel = std::vector<uint32_t>(1, 0x7950); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7950); auto const rel = std::vector<uint32_t>(1, 0x8ff6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8ff6); auto const rel = std::vector<uint32_t>(1, 0x4001); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4001); auto const rel = std::vector<uint32_t>(1, 0x86b4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x86b4); auto const rel = std::vector<uint32_t>(1, 0x4eb4); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4eb4); auto const rel = std::vector<uint32_t>(1, 0x8c81); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8c81); auto const rel = std::vector<uint32_t>(1, 0x91c9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91c9); auto const rel = std::vector<uint32_t>(1, 0x916d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x916d); auto const rel = std::vector<uint32_t>(1, 0x8a98); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8a98); auto const rel = std::vector<uint32_t>(1, 0x9f2c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f2c); auto const rel = std::vector<uint32_t>(1, 0x5b67); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b67); auto const rel = std::vector<uint32_t>(1, 0x848f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x848f); auto const rel = std::vector<uint32_t>(1, 0x7257); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7257); auto const rel = std::vector<uint32_t>(1, 0x6079); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6079); auto const rel = std::vector<uint32_t>(1, 0x5266); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5266); auto const rel = std::vector<uint32_t>(1, 0x70df); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x70df); auto const rel = std::vector<uint32_t>(1, 0x73da); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x73da); auto const rel = std::vector<uint32_t>(1, 0x80ed); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x80ed); auto const rel = std::vector<uint32_t>(1, 0x5063); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5063); auto const rel = std::vector<uint32_t>(1, 0x5571); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5571); auto const rel = std::vector<uint32_t>(1, 0x5d26); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5d26); auto const rel = std::vector<uint32_t>(1, 0x393f); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x393f); auto const rel = std::vector<uint32_t>(1, 0x6dca); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6dca); auto const rel = std::vector<uint32_t>(1, 0x6df9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6df9); auto const rel = std::vector<uint32_t>(1, 0x7109); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7109); auto const rel = std::vector<uint32_t>(1, 0x7111); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7111); auto const rel = std::vector<uint32_t>(1, 0x479b); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x479b); auto const rel = std::vector<uint32_t>(1, 0x9609); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9609); auto const rel = std::vector<uint32_t>(1, 0x6e6e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6e6e); auto const rel = std::vector<uint32_t>(1, 0x7312); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7312); auto const rel = std::vector<uint32_t>(1, 0x814c); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x814c); auto const rel = std::vector<uint32_t>(1, 0x83f8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x83f8); auto const rel = std::vector<uint32_t>(1, 0x7159); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7159); auto const rel = std::vector<uint32_t>(1, 0x787d); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x787d); auto const rel = std::vector<uint32_t>(1, 0x5ae3); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5ae3); auto const rel = std::vector<uint32_t>(1, 0x6f39); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6f39); auto const rel = std::vector<uint32_t>(1, 0x4167); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4167); auto const rel = std::vector<uint32_t>(1, 0x9122); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9122); auto const rel = std::vector<uint32_t>(1, 0x9183); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9183); auto const rel = std::vector<uint32_t>(1, 0x95b9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x95b9); auto const rel = std::vector<uint32_t>(1, 0x5b2e); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b2e); auto const rel = std::vector<uint32_t>(1, 0x61e8); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x61e8); auto const rel = std::vector<uint32_t>(1, 0x7bf6); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7bf6); auto const rel = std::vector<uint32_t>(1, 0x61d5); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x61d5); auto const rel = std::vector<uint32_t>(1, 0x81d9); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x81d9); auto const rel = std::vector<uint32_t>(1, 0x9eeb); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9eeb); auto const rel = std::vector<uint32_t>(1, 0x8ba0); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8ba0); auto const rel = std::vector<uint32_t>(1, 0x4e25); std::string const res_str = to_string(res); std::string const rel_str = to_string(rel); auto const res_view = as_utf32(res); auto const rel_view = as_utf32(rel); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); EXPECT_EQ(collate( res_view.begin(), res_view.end(), rel_view.begin(), rel_view.end(), table(), collation_strength::primary), -1); } }
35.153006
76
0.597496
[ "vector" ]
4ec071dbde5fdc9f277948b3ac3691518b44cd4b
1,964
cpp
C++
source/pic2card/mystique/models/pth/detr_cpp/detr_infer.cpp
sqrrrl/AdaptiveCards
951a10b3b565c80a5b350d9b7622a634aaf5cd48
[ "MIT" ]
null
null
null
source/pic2card/mystique/models/pth/detr_cpp/detr_infer.cpp
sqrrrl/AdaptiveCards
951a10b3b565c80a5b350d9b7622a634aaf5cd48
[ "MIT" ]
null
null
null
source/pic2card/mystique/models/pth/detr_cpp/detr_infer.cpp
sqrrrl/AdaptiveCards
951a10b3b565c80a5b350d9b7622a634aaf5cd48
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <stdio.h> #include <opencv2/opencv.hpp> #include <torch/script.h> // One-stop header. // #include <pybind11/pybind11.h> using namespace cv; using namespace std; vector<int> random_scale(Mat image) {} // Scale sizes int main(int argc, const char *argv[]) { string model_path = "/mnt1/haridas/projects/pic2card-models/pytorch/detr_trace.pt"; string image_path = "/mnt1/haridas/projects/mystique/data/templates_test_data/1.png"; // if (argc != 3) // { // std::cerr << "usage: detr-app <path-to-exported-script-module> <image-path> \n"; // return -1; // } try { // Deserialize image_pathiptModule from a file using torch::jit::load(). Mat image = cv::imread(image_path, 1); cv::cvtColor(image, image, cv::COLOR_BGR2RGB); cv::Size scale(500, 600); cv::resize(image, image, scale); image.convertTo(image, CV_32FC3, 1.0f / 255.0f); std::cout << "Image: " << image.size(); auto input_tensor = torch::from_blob(image.data, {1, 500, 600, 3}); input_tensor = input_tensor.permute({0, 3, 1, 2}); std::cout << "Tensor: " << input_tensor[0][0].sizes(); // Apply normalization based on imagenet data. input_tensor[0][0] = input_tensor[0][0].sub_(0.485).div_(0.229); input_tensor[0][1] = input_tensor[0][1].sub_(0.456).div_(0.224); input_tensor[0][2] = input_tensor[0][2].sub_(0.406).div_(0.225); torch::jit::script::Module module; module = torch::jit::load(model_path); // Create a vector of inputs. std::vector<torch::jit::IValue> inputs; //inputs.push_back(torch::ones({1, 3, 500, 600})); inputs.push_back(input_tensor); // Execute the model and turn its output into a tensor. c10::IValue output = module.forward(inputs); std::cout << output; } catch (const c10::Error &e) { std::cerr << "error loading the model\n"; std::cout << e.what() << "\n"; return -1; } std::cout << "ok\n"; }
30.215385
87
0.639002
[ "vector", "model" ]
4ec0f903d3bf1d45299ccfc96a65b74f82857ce3
2,261
cpp
C++
Hooks/OpenGL.cpp
pwnedboi/csgobase
1144a6990cc08d3c7b57c3badf93b903468395d1
[ "MIT" ]
9
2018-06-28T19:40:34.000Z
2020-11-02T09:01:33.000Z
Hooks/OpenGL.cpp
pwnedboi/csgobase
1144a6990cc08d3c7b57c3badf93b903468395d1
[ "MIT" ]
1
2018-09-01T20:55:55.000Z
2018-09-01T20:55:55.000Z
Hooks/OpenGL.cpp
pwnedboi/csgobase
1144a6990cc08d3c7b57c3badf93b903468395d1
[ "MIT" ]
5
2018-09-01T20:53:21.000Z
2020-06-16T19:33:23.000Z
/* glHook.cpp * * * */ #include "main.h" #include "util_sdl.h" #include "menu.h" #include "visuals.h" #include "imgui.h" #include "imgui_impl_sdl_gl2.h" uintptr_t oSwapWindow = NULL; uintptr_t* pSwapWindow = nullptr; void SwapWindow_hk(SDL_Window* window) { static SDL_GLContext context = NULL; static void (*oSDL_GL_SwapWindow)(SDL_Window*)= reinterpret_cast<void (*)(SDL_Window*)>(oSwapWindow); static SDL_GLContext original_context = SDL_GL_GetCurrentContext(); if(!context) { context = SDL_GL_CreateContext(window); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; ImGui_ImplSdlGL2_Init(window); /* * Init the menu */ menu->init(); /* * Init the fonts */ render->init_fonts(); } SDL_GL_MakeCurrent(window, context); /* * Disable vsync */ if(SDL_GL_SetSwapInterval(0) < 0) print("Unable to disable vsync!"); ImGui_ImplSdlGL2_NewFrame(window); /* * Draw everything between start and finish */ render->start(); /* * Should probably use pEngine->IsInGame */ if(Global::local) { visuals->draw_player_esp(); } render->finish(); /* * Draw the menu */ if(set.menu) menu->display(); /* * Draw the mouse */ static ImGuiIO& io = ImGui::GetIO(); io.MouseDrawCursor = set.menu; ImGui::Render(); ImGui_ImplSdlGL2_RenderDrawData(ImGui::GetDrawData()); oSDL_GL_SwapWindow(window); SDL_GL_MakeCurrent(window, original_context); glFlush(); } void OpenGL_hk() { GLHelper::module mod("libSDL2-2.0.0.dylib"); uintptr_t SwapWindowFn = reinterpret_cast<uintptr_t>(dlsym(RTLD_DEFAULT, "SDL_GL_SwapWindow")); uintptr_t sdl_lib = reinterpret_cast<uintptr_t>(mod.start()); pSwapWindow = reinterpret_cast<uintptr_t*>(GLHelper::get_absolue_address(sdl_lib, SwapWindowFn, 0xF, 0x4)); oSwapWindow = *pSwapWindow; *pSwapWindow = reinterpret_cast<uintptr_t>(&SwapWindow_hk); }
21.130841
123
0.582928
[ "render" ]
4ecbffec76cb8ec57377ac27d5999aed89a796e3
2,769
cpp
C++
Pipe.cpp
xeranimus/happy-pipes
929953a6e565ca0d385f9ae77f9dfe36ae731cb6
[ "MIT" ]
null
null
null
Pipe.cpp
xeranimus/happy-pipes
929953a6e565ca0d385f9ae77f9dfe36ae731cb6
[ "MIT" ]
null
null
null
Pipe.cpp
xeranimus/happy-pipes
929953a6e565ca0d385f9ae77f9dfe36ae731cb6
[ "MIT" ]
null
null
null
#include "Pipe.h" bool contains(SDL_Rect rect, SDL_Point point) { return (point.x >= rect.x && point.x <= rect.w) && (point.y >= rect.y && point.y <= rect.h); } Pipe::Pipe(int direct, SDL_Color color, SDL_Point position) { int red = rand() % 0xFF; int green = rand() % 0xFF; primary = {red, green, 0}; currentDirect = direct; currentPos = position; } void Pipe::wraparound() { switch (currentDirect) { case UP: positions.push_back({currentPos.x, 0}); positions.push_back({-1,-1}); positions.push_back({currentPos.x, boundingBox.h}); currentPos.y = boundingBox.h + currentPos.y % boundingBox.h; break; case DOWN: positions.push_back({currentPos.x, boundingBox.h}); positions.push_back({-1,-1}); positions.push_back({currentPos.x, 0}); currentPos.y = currentPos.y % boundingBox.h; break; case LEFT: positions.push_back({0, currentPos.y}); positions.push_back({-1,-1}); positions.push_back({boundingBox.w, currentPos.y}); currentPos.x = boundingBox.w + currentPos.x % boundingBox.w; break; case RIGHT: positions.push_back({boundingBox.w, currentPos.y}); positions.push_back({-1,-1}); positions.push_back({0, currentPos.y}); currentPos.x = currentPos.x % boundingBox.w; break; } } void Pipe::grow() { if (stop) return; if (!contains(boundingBox, currentPos)) wraparound(); positions.push_back(currentPos); if (rand() % 10 == 0) change_direction(rand()); int increment = rand(); switch (currentDirect) { case UP: currentPos.y -= increment % (boundingBox.h / 25); break; case DOWN: currentPos.y += increment % (boundingBox.h / 25); break; case LEFT: currentPos.x -= increment % (boundingBox.w / 25); break; case RIGHT: currentPos.x += increment % (boundingBox.w / 25); break; } } void Pipe::change_direction(int direct) { currentDirect = (2 + (currentDirect / 2) * 2) % SIZE + (direct % 2); //std::cerr << "changing direction\n"; } SDL_Color Pipe::get_color() { return primary; } int Pipe::get_width() { return width; } std::vector<SDL_Point> Pipe::get_positions() { return std::vector<SDL_Point>(positions); } int Pipe::get_position_count() { return positions.size(); } Pipe::Line Pipe::peek_line() { return lineStack.back(); }
24.945946
97
0.541351
[ "vector" ]
4ecc69924a420fe150aaee2970b83e24d540b100
3,019
cpp
C++
sources/applications/axislicenseinterface/src/protocols/axislicenseprotocolfactory.cpp
rdkcmf/rdkc-rms
65ab1efcee9e3de46a888c125f591cd48b815601
[ "Apache-2.0" ]
3
2020-07-30T19:41:00.000Z
2020-10-28T12:52:37.000Z
sources/applications/axislicenseinterface/src/protocols/axislicenseprotocolfactory.cpp
rdkcmf/rdkc-rms
65ab1efcee9e3de46a888c125f591cd48b815601
[ "Apache-2.0" ]
null
null
null
sources/applications/axislicenseinterface/src/protocols/axislicenseprotocolfactory.cpp
rdkcmf/rdkc-rms
65ab1efcee9e3de46a888c125f591cd48b815601
[ "Apache-2.0" ]
2
2020-05-11T03:19:00.000Z
2021-07-07T17:40:47.000Z
/** ########################################################################## # If not stated otherwise in this file or this component's LICENSE # file the following copyright and licenses apply: # # Copyright 2019 RDK Management # # 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 "protocols/axislicenseprotocolfactory.h" #include "protocols/protocoltypes.h" #include "protocols/axislicenseinterface/axislicenseinterfaceprotocol.h" using namespace app_axislicenseinterface; AxisLicenseProtocolFactory::AxisLicenseProtocolFactory() { ADD_VECTOR_END(_resolvedChains[CONF_PROTOCOL_HTTPS_AXIS_LICENSE_INTERFACE], PT_TCP); ADD_VECTOR_END(_resolvedChains[CONF_PROTOCOL_HTTPS_AXIS_LICENSE_INTERFACE], PT_OUTBOUND_SSL); ADD_VECTOR_END(_resolvedChains[CONF_PROTOCOL_HTTPS_AXIS_LICENSE_INTERFACE], PT_OUTBOUND_HTTP); ADD_VECTOR_END(_resolvedChains[CONF_PROTOCOL_HTTPS_AXIS_LICENSE_INTERFACE], PT_AXIS_LICENSE_INTERFACE); ADD_VECTOR_END(_resolvedChains[CONF_PROTOCOL_HTTP_AXIS_LICENSE_INTERFACE], PT_TCP); ADD_VECTOR_END(_resolvedChains[CONF_PROTOCOL_HTTP_AXIS_LICENSE_INTERFACE], PT_OUTBOUND_HTTP); ADD_VECTOR_END(_resolvedChains[CONF_PROTOCOL_HTTP_AXIS_LICENSE_INTERFACE], PT_AXIS_LICENSE_INTERFACE); } AxisLicenseProtocolFactory::~AxisLicenseProtocolFactory() { } vector<uint64_t> AxisLicenseProtocolFactory::HandledProtocols() { vector<uint64_t> result; ADD_VECTOR_END(result, PT_AXIS_LICENSE_INTERFACE); return result; } vector<string> AxisLicenseProtocolFactory::HandledProtocolChains() { vector<string> result; FOR_MAP(_resolvedChains, string, vector<uint64_t>, i) { ADD_VECTOR_END(result, MAP_KEY(i)); } return result; } vector<uint64_t> AxisLicenseProtocolFactory::ResolveProtocolChain(string name) { if (!MAP_HAS1(_resolvedChains, name)) { FATAL("Invalid protocol chain: %s.", STR(name)); return vector<uint64_t > (); } return _resolvedChains[name]; } BaseProtocol *AxisLicenseProtocolFactory::SpawnProtocol(uint64_t type, Variant &parameters) { BaseProtocol *pResult = NULL; switch (type) { case PT_AXIS_LICENSE_INTERFACE: pResult = new AxisLicenseInterfaceProtocol(); break; default: { FATAL("Spawning protocol %s not yet implemented", STR(tagToString(type))); break; } } if (pResult != NULL) { if (!pResult->Initialize(parameters)) { FATAL("Unable to initialize protocol %s", STR(tagToString(type))); delete pResult; pResult = NULL; } } return pResult; }
34.306818
104
0.752567
[ "vector" ]