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
c6c433f824ceb0b59ddfc3100bbb30ca12d8b827
1,293
cpp
C++
Triangulation_on_sphere_2/examples/Triangulation_on_sphere_2/triang_on_sphere_range.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
3,227
2015-03-05T00:19:18.000Z
2022-03-31T08:20:35.000Z
Triangulation_on_sphere_2/examples/Triangulation_on_sphere_2/triang_on_sphere_range.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
5,574
2015-03-05T00:01:56.000Z
2022-03-31T15:08:11.000Z
Triangulation_on_sphere_2/examples/Triangulation_on_sphere_2/triang_on_sphere_range.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
1,274
2015-03-05T00:01:12.000Z
2022-03-31T14:47:56.000Z
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Delaunay_triangulation_on_sphere_2.h> #include <CGAL/Projection_on_sphere_traits_3.h> #include <iostream> #include <fstream> typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef CGAL::Projection_on_sphere_traits_3<K> Traits; typedef CGAL::Delaunay_triangulation_on_sphere_2<Traits> DToS2; typedef DToS2::Point_3 Point; int main(int argc, char** argv) { std::cout.precision(17); const std::string filename = (argc > 1) ? argv[1] : CGAL::data_file_path("points_3/radar.xyz"); std::vector<Point> points; double x, y, z; std::ifstream in(filename); if(!in) { std::cerr << "Invalid input file: " << filename << std::endl; return EXIT_FAILURE; } while(in >> x >> y >> z) points.emplace_back(x, y, z); std::cout << points.size() << " points in input" << std::endl; Traits traits(Point(0, 0, 0), 100); DToS2 dtos(points.begin(), points.end(), traits); std::cout << dtos.number_of_vertices() << " vertices" << std::endl; std::cout << dtos.number_of_faces() << " solid faces" << std::endl; CGAL::IO::write_OFF("result.off", dtos, CGAL::parameters::stream_precision(17)); return EXIT_SUCCESS; }
27.510638
97
0.668213
[ "vector", "solid" ]
c6c52759254b9ecb980c4c31c468bd05b18b10c9
3,876
cpp
C++
src/shapes/curve.cpp
zq317157782/raiden
09376a9499f8b86e86c3049b4e654957cb4dc29e
[ "BSD-2-Clause" ]
21
2016-12-14T09:46:27.000Z
2021-12-28T10:05:04.000Z
src/shapes/curve.cpp
zq317157782/raiden
09376a9499f8b86e86c3049b4e654957cb4dc29e
[ "BSD-2-Clause" ]
2
2016-12-02T07:47:14.000Z
2018-01-30T18:11:09.000Z
src/shapes/curve.cpp
zq317157782/raiden
09376a9499f8b86e86c3049b4e654957cb4dc29e
[ "BSD-2-Clause" ]
null
null
null
#include "curve.h" #include "paramset.h" #include "mmath.h" #include "logging.h" std::vector<std::shared_ptr<Shape>> CreateCurves(const Transform *o2w, const Transform *w2o, bool reverseOrientation, const Point3f *c, Float w0, Float w1, CurveType type,const Normal3f* norm,int splitDepth){ std::shared_ptr<CurveCommon> common=std::make_shared<CurveCommon>(c,w0,w1,type,norm); int segmentNum=1<<splitDepth; std::vector<std::shared_ptr<Shape>> curves; curves.reserve(segmentNum); for(int i=0;i<segmentNum;++i){ Float u0=i/(Float)segmentNum; Float u1=(i+1)/(Float)segmentNum; curves.push_back(std::make_shared<Curve>(o2w,w2o,reverseOrientation,common,u0,u1)); } return curves; } std::vector<std::shared_ptr<Shape>> CreateCurveShape(const Transform *o2w, const Transform *w2o, bool reverseOrientation, const ParamSet &params){ int np=0; const Point3f* cp=params.FindPoint3f("P",&np);//所得所有的控制点 int splitDepth=params.FindOneInt("splitdepth",3);//获得每个线段的分割深度 n=1<<splitDepth int degree= params.FindOneInt("degree",3); if(((np - 1 - degree) % degree) != 0){ LError<<"Invalid number of control points "<<np<<": for the degree"<<degree<<"Bezier basis "<<degree+1<<" n*"<<degree<<"are required, for n >= 0."; return {}; } CurveType type; std::string curveType=params.FindOneString("type","flat"); if(curveType=="flat"){ type=CurveType::FLAT; } else if(curveType=="cylinder"){ type=CurveType::CYLINDER; } else if(curveType=="ribbon"){ type=CurveType::RIBBON; } Float width=params.FindOneFloat("width",1); Float width0=params.FindOneFloat("width0",width); Float width1=params.FindOneFloat("width1",width); int segmentNum=(np-1)/degree; int nn=0; const Normal3f* norm=params.FindNormal3f("N",&nn); if(norm){ if (type != CurveType::RIBBON) { LWarning<<"Curve normals are only used with \"ribbon\" type curves."; norm = nullptr; } else{ if(nn!=(segmentNum+1)){ LError<<"Invalid number of normals "<<nn<<": must provide "<<segmentNum+1<<" normals for ribbon curves with "<<segmentNum<<" segments."; return {}; } } } else{ if(type==CurveType::RIBBON){ LError<<"Must provide normals \"N\" at curve endpoints with ribbon curves."; return {}; } } const Point3f* cpBase=cp; std::vector<std::shared_ptr<Shape>> curves; for(int i=0;i<segmentNum;++i){ Point3f segCP[4]; if(degree==2){ segCP[0]=cpBase[0]; segCP[1]=Lerp(2.0f/3.0f,cpBase[0],cpBase[1]); segCP[2]=Lerp(1.0f/3.0f,cpBase[1],cpBase[2]); segCP[3]=cpBase[2]; } else{ for(int j=0;j<4;++j){ segCP[j]=cpBase[j]; } } cpBase+=degree; auto c=CreateCurves(o2w,w2o,reverseOrientation,segCP,width0,width1,type,norm,splitDepth); curves.insert(curves.end(), c.begin(), c.end()); } return curves; }
40.8
163
0.487358
[ "shape", "vector", "transform" ]
c6da0fd8ce6ca9c005fb151c12adaa0944ad8ccf
2,122
cpp
C++
201803/3.cpp
qzylalala/CSP
8bd474b0cb70b90c41e3fb87452724c5a2bc14fa
[ "Apache-2.0" ]
23
2021-03-01T07:07:48.000Z
2022-03-19T12:49:14.000Z
201803/3.cpp
qzylalala/CSP
8bd474b0cb70b90c41e3fb87452724c5a2bc14fa
[ "Apache-2.0" ]
null
null
null
201803/3.cpp
qzylalala/CSP
8bd474b0cb70b90c41e3fb87452724c5a2bc14fa
[ "Apache-2.0" ]
2
2021-08-30T09:35:17.000Z
2021-09-10T12:26:13.000Z
#include <iostream> #include <cstring> #include <algorithm> #include <vector> using namespace std; const int N = 110; int n, m; struct Url { string path, name; }url[N]; string get_number(string& str) { string res; for (auto c: str) if (c >= '0' && c <= '9') res += c; else { res.clear(); return res; } // 去掉前导0 int k = 0; while (k + 1 < res.size() && res[k] == '0') k ++ ; return res.substr(k); } vector<string> get(string& path, string& str) { vector<string> res(1); int i, j; for (i = 1, j = 1; i < path.size() && j < str.size();) { int u = i + 1, v = j + 1; while (u < path.size() && path[u] != '/') u ++ ; while (v < str.size() && str[v] != '/') v ++ ; string a = path.substr(i, u - i), b = str.substr(j, v - j); if (a == "<str>") { res.push_back(b); i = u + 1, j = v + 1; } else if (a == "<int>") { auto t = get_number(b); if (t.empty()) { res.clear(); return res; } res.push_back(t); i = u + 1, j = v + 1; } else if (a == "<path>") { res.push_back(str.substr(j)); return res; } else if (a != b) { res.clear(); return res; } else i = u + 1, j = v + 1; } if (i - path.size() != j - str.size()) res.clear(); return res; } void work(string& str) { for (int i = 0; i < n; i ++ ) { auto res = get(url[i].path, str); if (res.size()) { cout << url[i].name; for (int j = 1; j < res.size(); j ++ ) cout << ' ' << res[j]; cout << endl; return; } } puts("404"); } int main() { cin >> n >> m; for (int i = 0; i < n; i ++ ) cin >> url[i].path >> url[i].name; while (m -- ) { string str; cin >> str; work(str); } return 0; }
19.831776
68
0.377474
[ "vector" ]
c6e224c2bbd75c65b4a5583f4ec1a7e19d6af3d4
8,208
hpp
C++
cpp/include/ibs_bits/Integrators.hpp
tomerten/IBS
5013cc7b3fe81ab121b4bfe8684ae186027083cf
[ "MIT" ]
null
null
null
cpp/include/ibs_bits/Integrators.hpp
tomerten/IBS
5013cc7b3fe81ab121b4bfe8684ae186027083cf
[ "MIT" ]
null
null
null
cpp/include/ibs_bits/Integrators.hpp
tomerten/IBS
5013cc7b3fe81ab121b4bfe8684ae186027083cf
[ "MIT" ]
null
null
null
#include <functional> /** * Simpson integrator with decade splitting. * * @param a lambda**2 coefficient integral denominator * @param b lambda coefficient integral denominator * @param c constant integral denominator * @param cl longitudinal growth time factor * @param cx horizontal growth time factor * @param cy vertical growht time factor * @param cprime scaling factor * @param cyy scaling factor adapted to sqrt denominator * @param tl1 longitudinal lambda coefficient integral numerator * @param tl2 longitudinal constant term integral numerator * @param tx1 horizontal lambda coefficient integral numerator * @param tx2 horizontal constant term integral numerator * @param ty1 vertical lambda coefficient integral numerator * @param ty2 vertical constant term integral numerator * @param[in,out] tau outputArray * 0 -> IBS amplitude growth rate longitudinal * 1 -> IBS amplitude growth rate horizontal * 2 -> IBS amplitude growth rate vertical */ void SimpsonDecade(double a, double b, double c, double cl, double cx, double cy, double cprime, double cyy, double tl1, double tl2, double tx1, double tx2, double ty1, double ty2, double *tau); /** * The IBS integral integrand function. * * @param lambda integration variable * @param ax lambda coefficient integral numerator * @param bx constant term integral numerator * @param a lambda**2 coefficient integral denominator * @param b lambda coefficient integral denominator * @param c constant integral denominator * * @return integrand value * * @note CERN NOTE CERN-AB-2006-002 EQ 8 */ double IBSIntegralIntegrand(double lambda, double ax, double bx, double a, double b, double c); /** * Standard Simpson integration. * * @param ibsintegrand IBS integrand as in CERN NOTE CERN-AB-2006-002 EQ 8 * @param ax lambda coefficient integral numerator * @param bx constant term integral numerator * @param a lambda**2 coefficient integral denominator * @param b lambda coefficient integral denominator * @param c constant integral denominator * @param al lower integration boundary * @param bl higher integration boundary * @param n number of interval splits for the Simpson method * * @return Simpson integral value * */ double simpson(const std::function<double(double, double, double, double, double, double)> &ibsintegrand, double ax, double bx, double a, double b, double c, double al, double bl, int n); /** * Standard Simpson integration. * * @param BjorkenMtingwaIntegrand IBS Bjorken-Mtingwa integrand as in CERN NOTE * CERN-AB-2006-002 * @param ax horizontal lambda coefficient integral numerator * @param bx horizontal constant term integral numerator * @param ay vertical lambda coefficient integral numerator * @param by vertical constant term integral numerator * @param as longitudinal lambda coefficient integral numerator * @param bs longitudinal constant term integral numerator * @param a lambda**2 coefficient integral denominator * @param b lambda coefficient integral denominator * @param c constant integral denominator * @param[in, out] integral outputArray * 0 -> IBS longitudinal amplitude growth rate * 1 -> IBS horizontal amplitude growth rate * 2 -> IBS vertical amplitude growth rate * */ void intSimpson( const std::function<double(double, double, double, double, double, double)> &BjorkenMtingwaIntegrand, double ax, double bx, double ay, double by, double as, double bs, double a, double b, double ci, double *integral); /** * Zimmerman IBS model growth rates adapted from MADX implementation. * * @param pnumber number of real particles in the bunch * @param ex horizontal emittance * @param ey vertical emittance * @param sigs bunch length * @param sige energy spread dE/E * @param gammas relativistic gamma * @param betax horizontal beta function * @param betay vertical beta function * @param alx horizontal alpha * @param aly vertical alpha * @param dx horizontal dispersion * @param dpx derivative horizontal dispersion * @param dy vertical dispersion * @param dpy derivative vertical dispersion * @param[in, out] tau output Array * 0 -> IBS longitudinal amplitude growth rate * 1 -> IBS horizontal amplitude growth rate * 2 -> IBS vertical amplitude growth rate * * @note Based on implementation of twsint in MADX (copyright CERN) CERN NOTE * CERN-AB-2006-002 EQ 8. * */ void twsint(double pnumber, double ex, double ey, double sigs, double sige, double gammas, double betax, double betay, double alx, double aly, double dx, double dpx, double dy, double dpy, double *tau); /* ============================================================================== MODEL INTEGRATORS ============================================================================== */ /** * BJorken-Mtingwa IBS model growth rates using Simpson Decade Integratino. * * @param pnumber number of real particles in the bunch * @param ex horizontal emittance * @param ey vertical emittance * @param sigs bunch length * @param sige energy spread dE/E * @param gammas relativistic gamma * @param betax horizontal beta function * @param betay vertical beta function * @param alx horizontal alpha * @param aly vertical alpha * @param dx horizontal dispersion * @param dpx derivative horizontal dispersion * @param dy vertical dispersion * @param dpy derivative vertical dispersion * @param[in, out] tau output Array * 0 -> IBS longitudinal amplitude growth rate * 1 -> IBS horizontal amplitude growth rate * 2 -> IBS vertical amplitude growth rate * * @note CERN NOTE CERN-AB-2006-002 EQ 8. * */ void BjorkenMtingwaInt(double pnumber, double ex, double ey, double sigs, double sige, double gammas, double betx, double bety, double alx, double aly, double dx, double dpx, double dy, double dpy, double *tau); /** * Conte-Martini IBS model growth rates using Simpson Decade Integratino. * * @param pnumber number of real particles in the bunch * @param ex horizontal emittance * @param ey vertical emittance * @param sigs bunch length * @param sige energy spread dE/E * @param gammas relativistic gamma * @param betax horizontal beta function * @param betay vertical beta function * @param alx horizontal alpha * @param aly vertical alpha * @param dx horizontal dispersion * @param dpx derivative horizontal dispersion * @param dy vertical dispersion * @param dpy derivative vertical dispersion * @param[in, out] tau output Array * 0 -> IBS longitudinal amplitude growth rate * 1 -> IBS horizontal amplitude growth rate * 2 -> IBS vertical amplitude growth rate * * @note CERN NOTE CERN-AB-2006-002 EQ 8. * */ void ConteMartiniInt(double pnumber, double ex, double ey, double sigs, double sige, double gammas, double betx, double bety, double alx, double aly, double dx, double dpx, double dy, double dpy, double *tau); /** * Zimmerman IBS model growth rates using Simpson Decade Integration. * * @param pnumber number of real particles in the bunch * @param ex horizontal emittance * @param ey vertical emittance * @param sigs bunch length * @param sige energy spread dE/E * @param gammas relativistic gamma * @param betax horizontal beta function * @param betay vertical beta function * @param alx horizontal alpha * @param aly vertical alpha * @param dx horizontal dispersion * @param dpx derivative horizontal dispersion * @param dy vertical dispersion * @param dpy derivative vertical dispersion * @param[in, out] tau output Array * 0 -> IBS longitudinal amplitude growth rate * 1 -> IBS horizontal amplitude growth rate * 2 -> IBS vertical amplitude growth rate * * @note CERN NOTE CERN-AB-2006-002 EQ 8. * */ void MadxInt(double pnumber, double ex, double ey, double sigs, double sige, double gammas, double betx, double bety, double alx, double aly, double dx, double dpx, double dy, double dpy, double *tau);
37.651376
80
0.704435
[ "model" ]
c6e2e8425204327b6eeea69165bf23f9241276a9
5,244
cpp
C++
coloring/src/pcd_transfrom_node.cpp
l756302098/ros_practice
4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7
[ "MIT" ]
null
null
null
coloring/src/pcd_transfrom_node.cpp
l756302098/ros_practice
4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7
[ "MIT" ]
null
null
null
coloring/src/pcd_transfrom_node.cpp
l756302098/ros_practice
4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7
[ "MIT" ]
null
null
null
#include "ros/ros.h" #include <nav_msgs/Odometry.h> // PCL #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_cloud.h> #include <pcl/io/ply_io.h> #include <pcl/point_types.h> #include <pcl/octree/octree.h> #include <pcl/filters/passthrough.h> #include <pcl/filters/project_inliers.h> #include <pcl/ModelCoefficients.h> #include <pcl/common/transforms.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/filters/voxel_grid.h> #include <pcl/filters/approximate_voxel_grid.h> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; int get_filenames(const std::string& dir, std::vector<std::string>& filenames) { fs::path path(dir); if (!fs::exists(path)) { return -1; } fs::directory_iterator end_iter; for (fs::directory_iterator iter(path); iter!=end_iter; ++iter) { if (fs::is_regular_file(iter->status())) { filenames.push_back(iter->path().string()); } // if (fs::is_directory(iter->status())) // { // get_filenames(iter->path().string(), filenames); // } } return filenames.size(); } Eigen::Affine3f pose_to_eigen(float px,float py,float pz,float qx,float qy,float qz,float qw) { //RotationMatrix to Quaterniond Eigen::Quaternionf q; q.x() = qx; q.y() = qy; q.z() = qz; q.w() = qw; //Quaterniond to RotationMatrix Eigen::Matrix3f Rx = q.toRotationMatrix(); // laser ->world Eigen::Affine3f laser_to_world = Eigen::Affine3f::Identity(); laser_to_world.translation() << px, py, pz; laser_to_world.linear() = Rx; // world -> laser Eigen::Affine3f world_to_laser= Eigen::Affine3f::Identity(); world_to_laser.matrix() = laser_to_world.matrix().inverse(); return world_to_laser; } int main(int argc, char **argv) { ros::init(argc, argv, "coloring_node"); ROS_INFO("coloring_node started..."); std::string root_path; float px,py,pz,qx,qy,qz,qw; ros::NodeHandle nh_("~"); nh_.param<std::string>("root_path", root_path, ""); nh_.param<float>("pos_x", px,0); nh_.param<float>("pos_y", py,0); nh_.param<float>("pos_z", pz,0); nh_.param<float>("qua_x", qx,0); nh_.param<float>("qua_y", qy,0); nh_.param<float>("qua_z", qz,0); nh_.param<float>("qua_w", qw,1); ros::Publisher odom_pub = nh_.advertise<nav_msgs::Odometry>("/odom", 1, true); //read pcd std::vector<std::string> pcd_names; get_filenames(root_path+"/pcd",pcd_names); pcl::PointCloud<pcl::PointXYZ>::Ptr target_ptr (new pcl::PointCloud<pcl::PointXYZ>); for (size_t i = 0; i < pcd_names.size(); i++) { /* code */ std::string fileName = pcd_names[i]; // load pcd file pcl::PointCloud<pcl::PointXYZ>::Ptr frame_ptr (new pcl::PointCloud<pcl::PointXYZ>); if(pcl::io::loadPCDFile<pcl::PointXYZ>(fileName, *frame_ptr)==-1) { std::cout << "load cloud failed!" << std::endl; } *target_ptr=*target_ptr+*frame_ptr; } pcl::PCDWriter writer; writer.write<pcl::PointXYZ>(root_path+"/fore.pcd", *target_ptr); //transfrom pcl::PointCloud<pcl::PointXYZ>::Ptr cam_frame_cloud(new pcl::PointCloud<pcl::PointXYZ>()); Eigen::Affine3f init_pose = pose_to_eigen(px,py,pz,qx,qy,qz,qw); Eigen::AngleAxisf h_vector(M_PI /18 * 19, Eigen::Vector3f(0, 0, 1)); Eigen::Matrix3f h_rotation_matrix = Eigen::Matrix3f::Identity(); h_rotation_matrix = h_vector.toRotationMatrix(); init_pose.rotate(h_rotation_matrix); Eigen::AngleAxisf v_vector(M_PI / 6, Eigen::Vector3f(0, 1, 0)); Eigen::Matrix3f v_rotation_matrix = Eigen::Matrix3f::Identity(); v_rotation_matrix = v_vector.toRotationMatrix(); init_pose.rotate(v_rotation_matrix); pcl::transformPointCloud(*target_ptr, *cam_frame_cloud, init_pose); writer.write<pcl::PointXYZ>(root_path+"/back.pcd", *cam_frame_cloud); std::cout << "saved color pointscloud total count " << target_ptr->size() << std::endl; //Eigen::Affine3f init_pose = pose_to_eigen(0,0,0,0,0,0,1); // Eigen::AngleAxisf h_vector(M_PI /18 * 19, Eigen::Vector3f(0, 0, 1)); // Eigen::Matrix3f h_rotation_matrix = Eigen::Matrix3f::Identity(); // h_rotation_matrix = h_vector.toRotationMatrix(); // init_pose.rotate(h_rotation_matrix); // Eigen::AngleAxisf v_vector(M_PI /18 * 3, Eigen::Vector3f(0, 1, 0)); // Eigen::Matrix3f v_rotation_matrix = Eigen::Matrix3f::Identity(); // v_rotation_matrix = v_vector.toRotationMatrix(); // init_pose.rotate(v_rotation_matrix); Eigen::Matrix3f rotation_matrix = init_pose.linear(); Eigen::Quaternionf quaternion(rotation_matrix); nav_msgs::Odometry pose; pose.header.stamp = ros::Time::now(); pose.header.frame_id = "map"; pose.pose.pose.position.x = init_pose.translation().x(); pose.pose.pose.position.y = init_pose.translation().y(); pose.pose.pose.position.z = init_pose.translation().z(); pose.pose.pose.orientation.x = quaternion.x(); pose.pose.pose.orientation.y = quaternion.y(); pose.pose.pose.orientation.z = quaternion.z(); pose.pose.pose.orientation.w = quaternion.w(); ros::Rate rate(10); while(ros::ok()) { odom_pub.publish(pose); ros::spinOnce(); rate.sleep(); } return 0; }
33.832258
93
0.663043
[ "vector" ]
c6e336c73bf224c09e62b33773e6a23a9f403dbb
935
hpp
C++
wav2midi/scale.hpp
mrk21/wav2midi
01b7667c2fd7e18893a5cc97069aabc9397126e6
[ "MIT" ]
29
2018-11-14T04:46:38.000Z
2022-01-04T13:28:38.000Z
wav2midi/scale.hpp
mrk21/wav2midi
01b7667c2fd7e18893a5cc97069aabc9397126e6
[ "MIT" ]
1
2019-01-12T21:40:34.000Z
2019-01-12T22:06:01.000Z
wav2midi/scale.hpp
mrk21/wav2midi
01b7667c2fd7e18893a5cc97069aabc9397126e6
[ "MIT" ]
8
2018-07-04T14:34:41.000Z
2021-07-30T13:38:35.000Z
#ifndef WAV2MIDI_AUDIO_SCALE_HPP #define WAV2MIDI_AUDIO_SCALE_HPP #include <vector> #include <string> namespace wav2midi { class scale { public: static constexpr auto n = 88u; class item { public: uint32_t no() const; uint32_t local_no() const; uint32_t octave() const; double frequency() const; const std::string & name() const; item(uint32_t no); private: uint32_t no_; uint32_t local_no_; uint32_t octave_; double frequency_; std::string name_; }; scale(); const item & operator [](uint32_t no) const; const item & match(double frequency) const; static uint32_t frequency_to_no(double frequency); static double no_to_frequency(uint32_t no); private: std::vector<item> items_; }; } #endif
22.261905
58
0.568984
[ "vector" ]
c6ef03e7cb2add326e1f923372aeb88e1a020e99
137,612
cpp
C++
third_party/skia_m84/third_party/externals/angle2/src/compiler/translator/glslang_lex_autogen.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
null
null
null
third_party/skia_m84/third_party/externals/angle2/src/compiler/translator/glslang_lex_autogen.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
null
null
null
third_party/skia_m84/third_party/externals/angle2/src/compiler/translator/glslang_lex_autogen.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
null
null
null
#line 17 "glslang.l" // GENERATED FILE - DO NOT EDIT. // Generated by generate_parser.py from glslang.l // // Copyright 2019 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // glslang.l: // Lexer for the OpenGL shading language. // Ignore errors in auto-generated code. #if defined(__GNUC__) # pragma GCC diagnostic ignored "-Wswitch-enum" # pragma GCC diagnostic ignored "-Wunused-function" # pragma GCC diagnostic ignored "-Wunused-variable" #elif defined(_MSC_VER) # pragma warning(disable : 4005) # pragma warning(disable : 4065) # pragma warning(disable : 4189) # pragma warning(disable : 4244) # pragma warning(disable : 4505) # pragma warning(disable : 4701) # pragma warning(disable : 4702) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wimplicit-fallthrough" # if defined(__APPLE__) // Older clang versions don't have -Wextra-semi-stmt, and detecting Apple clang versions is // difficult because they use different yet overlapping version numbers vs. regular clang. # pragma clang diagnostic ignored "-Wunknown-warning-option" # endif // Flex isn't semi-colon clean. # pragma clang diagnostic ignored "-Wextra-semi-stmt" # pragma clang diagnostic ignored "-Wunreachable-code" #endif #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 4 #if YY_FLEX_SUBMINOR_VERSION > 0 # define FLEX_BETA #endif #ifdef yyget_lval # define yyget_lval_ALREADY_DEFINED #else # define yyget_lval yyget_lval #endif #ifdef yyset_lval # define yyset_lval_ALREADY_DEFINED #else # define yyset_lval yyset_lval #endif #ifdef yyget_lloc # define yyget_lloc_ALREADY_DEFINED #else # define yyget_lloc yyget_lloc #endif #ifdef yyset_lloc # define yyset_lloc_ALREADY_DEFINED #else # define yyset_lloc yyset_lloc #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H # define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ # if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ # ifndef __STDC_LIMIT_MACROS # define __STDC_LIMIT_MACROS 1 # endif # include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; # else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ # ifndef INT8_MIN # define INT8_MIN (-128) # endif # ifndef INT16_MIN # define INT16_MIN (-32767 - 1) # endif # ifndef INT32_MIN # define INT32_MIN (-2147483647 - 1) # endif # ifndef INT8_MAX # define INT8_MAX (127) # endif # ifndef INT16_MAX # define INT16_MAX (32767) # endif # ifndef INT32_MAX # define INT32_MAX (2147483647) # endif # ifndef UINT8_MAX # define UINT8_MAX (255U) # endif # ifndef UINT16_MAX # define UINT16_MAX (65535U) # endif # ifndef UINT32_MAX # define UINT32_MAX (4294967295U) # endif # ifndef SIZE_MAX # define SIZE_MAX (~(size_t)0) # endif # endif /* ! C99 */ #endif /* ! FLEXINT_H */ /* begin standard C++ headers. */ /* TODO: this is always defined, so inline it */ #define yyconst const #if defined(__GNUC__) && __GNUC__ >= 3 # define yynoreturn __attribute__((__noreturn__)) #else # define yynoreturn #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an * integer in range [0..255] for use as an array index. */ #define YY_SC_TO_UI(c) ((YY_CHAR)(c)) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T # define YY_TYPEDEF_YY_SCANNER_T typedef void *yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart(yyin, yyscanner) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE # ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ # define YY_BUF_SIZE 32768 # else # define YY_BUF_SIZE 16384 # endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE # define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T # define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do \ { \ int yyl; \ for (yyl = n; yyl < yyleng; ++yyl) \ if (yytext[yyl] == '\n') \ --yylineno; \ } while (0) #define YY_LINENO_REWIND_TO(dst) \ do \ { \ const char *p; \ for (p = yy_cp - 1; p >= (dst); --p) \ if (*p == '\n') \ --yylineno; \ } while (0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg); \ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } while (0) #define unput(c) yyunput(c, yyg->yytext_ptr, yyscanner) #ifndef YY_STRUCT_YY_BUFFER_STATE # define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ int yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; # define YY_BUFFER_NEW 0 # define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ # define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER \ (yyg->yy_buffer_stack ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void yyrestart(FILE *input_file, yyscan_t yyscanner); void yy_switch_to_buffer(YY_BUFFER_STATE new_buffer, yyscan_t yyscanner); YY_BUFFER_STATE yy_create_buffer(FILE *file, int size, yyscan_t yyscanner); void yy_delete_buffer(YY_BUFFER_STATE b, yyscan_t yyscanner); void yy_flush_buffer(YY_BUFFER_STATE b, yyscan_t yyscanner); void yypush_buffer_state(YY_BUFFER_STATE new_buffer, yyscan_t yyscanner); void yypop_buffer_state(yyscan_t yyscanner); static void yyensure_buffer_stack(yyscan_t yyscanner); static void yy_load_buffer_state(yyscan_t yyscanner); static void yy_init_buffer(YY_BUFFER_STATE b, FILE *file, yyscan_t yyscanner); #define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER, yyscanner) YY_BUFFER_STATE yy_scan_buffer(char *base, yy_size_t size, yyscan_t yyscanner); YY_BUFFER_STATE yy_scan_string(const char *yy_str, yyscan_t yyscanner); YY_BUFFER_STATE yy_scan_bytes(const char *bytes, int len, yyscan_t yyscanner); void *yyalloc(yy_size_t, yyscan_t yyscanner); void *yyrealloc(void *, yy_size_t, yyscan_t yyscanner); void yyfree(void *, yyscan_t yyscanner); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if (!YY_CURRENT_BUFFER) \ { \ yyensure_buffer_stack(yyscanner); \ YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin, YY_BUF_SIZE, yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if (!YY_CURRENT_BUFFER) \ { \ yyensure_buffer_stack(yyscanner); \ YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin, YY_BUF_SIZE, yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define yywrap(yyscanner) (/*CONSTCOND*/ 1) #define YY_SKIP_YYWRAP typedef flex_uint8_t YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state(yyscan_t yyscanner); static yy_state_type yy_try_NUL_trans(yy_state_type current_state, yyscan_t yyscanner); static int yy_get_next_buffer(yyscan_t yyscanner); static void yynoreturn yy_fatal_error(const char *msg, yyscan_t yyscanner); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (int)(yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 249 #define YY_END_OF_BUFFER 250 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static const flex_int16_t yy_accept[902] = { 0, 0, 0, 0, 0, 250, 248, 247, 247, 231, 237, 242, 226, 227, 235, 234, 223, 232, 230, 236, 189, 189, 224, 220, 238, 225, 239, 243, 186, 228, 229, 241, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 221, 240, 222, 233, 246, 245, 249, 244, 217, 203, 222, 211, 206, 201, 209, 199, 210, 200, 195, 202, 194, 188, 189, 0, 192, 0, 229, 221, 228, 218, 214, 216, 215, 219, 186, 207, 213, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 13, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 16, 186, 186, 25, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 208, 212, 244, 0, 198, 194, 0, 197, 191, 0, 193, 187, 204, 205, 186, 186, 146, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 14, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 30, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 26, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 0, 195, 0, 194, 196, 190, 186, 186, 186, 186, 33, 186, 186, 186, 19, 183, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 17, 149, 186, 186, 186, 186, 22, 186, 186, 153, 164, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 161, 4, 38, 39, 40, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 152, 34, 186, 186, 31, 186, 186, 186, 186, 186, 186, 186, 50, 51, 52, 32, 186, 186, 186, 186, 186, 186, 186, 186, 11, 186, 56, 57, 58, 186, 147, 186, 186, 7, 186, 186, 186, 186, 173, 174, 175, 186, 35, 186, 165, 29, 176, 177, 178, 2, 170, 171, 172, 186, 186, 186, 27, 168, 186, 186, 186, 186, 186, 53, 54, 55, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 114, 186, 186, 186, 186, 186, 186, 186, 186, 162, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 148, 186, 186, 185, 59, 60, 61, 186, 186, 15, 186, 186, 186, 119, 186, 186, 9, 186, 186, 117, 186, 186, 186, 163, 158, 120, 186, 186, 186, 186, 186, 186, 154, 186, 186, 186, 186, 186, 89, 41, 44, 46, 45, 42, 48, 47, 49, 43, 186, 186, 186, 186, 169, 145, 186, 186, 156, 186, 186, 186, 37, 115, 28, 182, 23, 157, 88, 186, 167, 18, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 20, 36, 186, 186, 186, 186, 186, 186, 121, 94, 100, 186, 186, 186, 186, 186, 91, 93, 3, 186, 186, 186, 186, 112, 186, 186, 186, 186, 186, 186, 186, 150, 186, 186, 186, 186, 186, 8, 186, 186, 10, 186, 186, 186, 186, 186, 186, 21, 108, 12, 159, 122, 95, 102, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 155, 186, 186, 186, 106, 113, 109, 186, 186, 186, 186, 186, 186, 186, 186, 151, 123, 96, 101, 186, 186, 166, 186, 110, 186, 186, 186, 186, 6, 186, 186, 186, 186, 186, 186, 186, 186, 186, 105, 160, 1, 186, 186, 186, 186, 186, 186, 184, 186, 118, 5, 179, 62, 65, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 107, 186, 186, 186, 186, 186, 186, 103, 186, 186, 186, 186, 186, 136, 70, 71, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 116, 186, 186, 186, 104, 138, 75, 76, 186, 186, 186, 186, 111, 186, 186, 186, 186, 186, 186, 186, 131, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 69, 186, 186, 186, 186, 63, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 132, 124, 186, 97, 186, 186, 186, 74, 186, 186, 72, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 133, 186, 186, 79, 186, 186, 77, 186, 186, 125, 98, 186, 127, 186, 128, 186, 186, 186, 186, 186, 186, 24, 186, 186, 186, 186, 67, 186, 66, 142, 186, 186, 186, 126, 99, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 140, 143, 186, 134, 186, 68, 186, 186, 186, 186, 186, 186, 186, 186, 186, 141, 144, 186, 186, 186, 186, 137, 73, 186, 186, 186, 180, 186, 186, 186, 80, 186, 186, 186, 139, 78, 186, 186, 186, 186, 186, 186, 186, 186, 186, 84, 186, 186, 186, 186, 186, 186, 186, 186, 186, 85, 186, 186, 186, 186, 81, 186, 87, 86, 90, 186, 129, 130, 92, 186, 186, 186, 64, 186, 186, 186, 181, 186, 135, 82, 186, 186, 186, 186, 83, 0}; static const YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1, 1, 5, 6, 1, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 1, 31, 32, 33, 34, 35, 36, 37, 38, 38, 38, 38, 39, 40, 38, 41, 38, 38, 42, 43, 44, 45, 46, 47, 48, 49, 38, 50, 1, 51, 52, 53, 1, 54, 55, 56, 57, 58, 59, 60, 61, 62, 38, 63, 64, 65, 66, 67, 68, 38, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; static const YY_CHAR yy_meta[82] = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 4, 4, 4, 4, 3, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 6, 6, 6, 6, 1, 1, 1, 6, 4, 4, 4, 4, 3, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 1, 1, 1, 1}; static const flex_int16_t yy_base[908] = { 0, 0, 0, 81, 0, 1155, 1156, 1156, 1156, 1126, 135, 159, 1156, 1156, 1125, 156, 1156, 155, 153, 1124, 175, 166, 1122, 1156, 175, 1122, 153, 1156, 0, 1156, 1156, 157, 1096, 148, 158, 168, 178, 141, 175, 1081, 187, 193, 154, 159, 161, 1075, 199, 1088, 208, 185, 215, 220, 117, 1073, 1156, 178, 1156, 1156, 1156, 1156, 1156, 0, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 240, 1156, 248, 241, 259, 317, 1156, 0, 1156, 1156, 1156, 1116, 1156, 1156, 1156, 1115, 0, 1156, 1156, 1072, 1070, 1075, 224, 1072, 1080, 1078, 1078, 1065, 1068, 1079, 231, 1073, 1061, 1058, 1071, 1058, 1055, 1055, 1061, 192, 236, 1055, 1065, 1051, 1057, 1060, 1061, 0, 1053, 1063, 241, 1062, 1043, 1056, 1037, 227, 1041, 1054, 1045, 253, 1038, 254, 1050, 1052, 248, 1041, 257, 1028, 1037, 274, 287, 1041, 1037, 1039, 1028, 1031, 279, 260, 292, 1040, 1028, 1040, 150, 1033, 1032, 1020, 1156, 1156, 0, 341, 1156, 312, 357, 1156, 1156, 367, 377, 357, 1156, 1156, 1038, 1029, 0, 1025, 1020, 1024, 1033, 1027, 1029, 345, 1013, 1013, 1024, 1016, 279, 1026, 1023, 1023, 1021, 1018, 1010, 1016, 1003, 1001, 1013, 999, 1015, 0, 1012, 1000, 1007, 1004, 1008, 1009, 1002, 999, 988, 987, 1000, 1003, 991, 1002, 998, 986, 992, 983, 387, 988, 991, 982, 989, 978, 982, 973, 987, 986, 977, 983, 340, 967, 970, 968, 967, 977, 967, 962, 960, 962, 972, 958, 960, 957, 968, 967, 970, 952, 350, 960, 956, 954, 963, 942, 401, 960, 962, 951, 943, 980, 422, 432, 442, 454, 1156, 1156, 947, 938, 948, 947, 0, 945, 949, 404, 0, 0, 937, 935, 935, 936, 931, 939, 928, 945, 934, 407, 0, 0, 928, 938, 937, 937, 0, 922, 413, 0, 0, 924, 416, 931, 932, 923, 917, 916, 917, 916, 916, 393, 462, 911, 0, 0, 907, 906, 905, 907, 908, 913, 907, 903, 916, 911, 911, 909, 908, 902, 896, 898, 897, 901, 906, 892, 895, 890, 898, 903, 891, 888, 900, 891, 0, 0, 897, 893, 0, 885, 885, 890, 881, 888, 465, 885, 0, 0, 0, 0, 875, 887, 886, 873, 874, 883, 884, 884, 0, 869, 0, 0, 0, 870, 0, 878, 869, 0, 868, 869, 863, 873, 0, 0, 0, 864, 0, 860, 0, 0, 0, 0, 0, 0, 0, 0, 0, 870, 469, 869, 0, 0, 867, 863, 860, 908, 907, 0, 0, 0, 850, 475, 478, 481, 855, 851, 856, 847, 845, 858, 843, 0, 843, 856, 845, 841, 847, 842, 849, 849, 0, 846, 843, 847, 831, 829, 832, 838, 844, 839, 838, 826, 0, 828, 829, 0, 0, 0, 0, 826, 829, 0, 823, 833, 824, 0, 834, 814, 0, 823, 818, 0, 811, 811, 824, 0, 826, 0, 487, 845, 844, 843, 804, 803, 0, 820, 819, 814, 855, 846, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 801, 814, 801, 798, 0, 0, 803, 350, 0, 800, 807, 806, 0, 792, 0, 0, 0, 0, 0, 789, 0, 0, 788, 799, 490, 792, 798, 797, 794, 789, 786, 808, 792, 777, 777, 790, 775, 787, 0, 0, 780, 809, 808, 807, 768, 767, 478, 481, 0, 779, 782, 780, 769, 765, 780, 0, 0, 776, 773, 772, 762, 0, 761, 751, 768, 754, 498, 762, 765, 0, 788, 787, 786, 747, 746, 0, 760, 747, 0, 757, 750, 742, 743, 749, 752, 0, 0, 0, 0, 778, 777, 0, 748, 751, 736, 743, 734, 741, 742, 742, 741, 727, 509, 738, 738, 0, 739, 728, 727, 0, 0, 0, 758, 757, 756, 717, 716, 712, 724, 719, 0, 753, 752, 0, 723, 726, 0, 518, 0, 704, 725, 743, 711, 0, 707, 706, 715, 715, 703, 717, 701, 715, 710, 0, 0, 0, 733, 732, 731, 692, 691, 690, 0, 690, 0, 0, 486, 497, 718, 700, 703, 686, 699, 697, 685, 684, 693, 693, 716, 715, 714, 675, 674, 0, 679, 669, 672, 673, 672, 682, 0, 685, 681, 683, 679, 666, 703, 507, 0, 674, 677, 667, 668, 660, 667, 658, 683, 667, 663, 665, 663, 663, 662, 661, 0, 649, 648, 658, 0, 684, 512, 0, 655, 658, 655, 640, 0, 656, 655, 639, 631, 639, 629, 637, 0, 634, 633, 658, 642, 640, 640, 633, 623, 626, 640, 624, 661, 635, 636, 633, 630, 644, 617, 618, 630, 629, 613, 612, 611, 636, 620, 618, 618, 621, 616, 597, 596, 0, 628, 596, 626, 594, 598, 597, 634, 608, 605, 0, 609, 599, 600, 584, 586, 570, 118, 177, 173, 196, 239, 254, 279, 276, 290, 0, 299, 341, 396, 372, 409, 0, 419, 420, 0, 0, 449, 0, 450, 0, 464, 478, 476, 475, 479, 484, 0, 479, 489, 481, 489, 516, 493, 0, 0, 507, 508, 528, 0, 0, 510, 511, 497, 496, 499, 512, 504, 517, 518, 497, 498, 506, 0, 0, 522, 534, 504, 536, 526, 520, 508, 526, 520, 553, 510, 511, 519, 0, 0, 554, 536, 534, 535, 0, 0, 539, 528, 534, 0, 535, 521, 544, 0, 532, 559, 564, 0, 0, 548, 555, 540, 538, 539, 531, 548, 555, 556, 0, 554, 538, 578, 575, 539, 572, 600, 544, 545, 0, 562, 564, 565, 556, 0, 581, 0, 0, 0, 591, 0, 0, 0, 559, 560, 554, 0, 580, 556, 557, 0, 615, 0, 0, 584, 599, 587, 592, 0, 1156, 635, 640, 645, 650, 653, 656}; static const flex_int16_t yy_def[908] = { 0, 901, 1, 901, 3, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 902, 901, 901, 901, 901, 901, 901, 903, 901, 901, 901, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 901, 901, 901, 901, 901, 901, 901, 904, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 905, 901, 906, 20, 902, 901, 901, 907, 901, 901, 901, 901, 901, 901, 901, 901, 903, 901, 901, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 901, 901, 904, 901, 901, 906, 901, 901, 901, 901, 901, 907, 901, 901, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 901, 901, 901, 901, 901, 901, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 903, 0, 901, 901, 901, 901, 901, 901}; static const flex_int16_t yy_nxt[1238] = { 0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 23, 24, 25, 26, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 28, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 28, 53, 28, 54, 55, 56, 57, 58, 59, 60, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 58, 58, 58, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 58, 58, 58, 58, 63, 64, 65, 68, 70, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 155, 74, 81, 86, 87, 71, 69, 89, 156, 66, 74, 795, 75, 75, 75, 75, 75, 75, 75, 75, 76, 76, 82, 77, 83, 84, 92, 107, 158, 108, 126, 90, 77, 78, 255, 128, 256, 130, 109, 129, 93, 94, 78, 127, 99, 79, 77, 95, 100, 96, 131, 110, 97, 98, 101, 77, 796, 102, 103, 111, 78, 112, 104, 116, 113, 144, 797, 105, 145, 78, 114, 117, 79, 106, 119, 133, 146, 120, 195, 159, 121, 122, 118, 147, 137, 123, 124, 798, 125, 196, 134, 138, 139, 135, 74, 140, 152, 161, 162, 148, 153, 141, 142, 149, 143, 164, 165, 150, 166, 154, 151, 901, 197, 175, 184, 216, 77, 176, 185, 186, 161, 162, 799, 217, 229, 198, 78, 207, 164, 165, 208, 209, 224, 233, 210, 166, 211, 221, 901, 77, 230, 231, 800, 222, 248, 225, 234, 226, 801, 167, 237, 167, 249, 78, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 239, 238, 246, 247, 250, 164, 165, 280, 281, 260, 802, 260, 251, 240, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 803, 262, 804, 262, 164, 165, 263, 263, 263, 263, 263, 263, 263, 263, 263, 263, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 265, 274, 312, 313, 314, 326, 547, 345, 805, 327, 548, 264, 401, 402, 275, 346, 352, 353, 354, 366, 367, 368, 378, 379, 380, 806, 807, 265, 386, 387, 388, 390, 391, 392, 264, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 263, 263, 263, 263, 263, 263, 263, 263, 263, 263, 808, 162, 263, 263, 263, 263, 263, 263, 263, 263, 263, 263, 403, 404, 405, 442, 443, 444, 465, 466, 467, 809, 810, 165, 162, 477, 478, 479, 480, 481, 482, 483, 484, 485, 468, 469, 527, 528, 529, 556, 557, 558, 580, 811, 812, 582, 165, 598, 599, 600, 679, 813, 530, 531, 581, 559, 560, 583, 632, 633, 634, 681, 680, 601, 602, 814, 603, 654, 655, 656, 682, 712, 683, 684, 635, 636, 734, 604, 815, 816, 713, 817, 714, 657, 658, 735, 818, 736, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 76, 76, 794, 793, 792, 76, 88, 88, 88, 88, 88, 160, 160, 160, 160, 160, 72, 791, 72, 163, 790, 163, 169, 169, 169, 789, 788, 787, 786, 785, 784, 783, 782, 781, 780, 779, 778, 777, 776, 775, 774, 773, 772, 771, 770, 769, 768, 767, 766, 765, 764, 763, 762, 761, 760, 759, 758, 757, 756, 755, 754, 753, 752, 751, 750, 749, 748, 747, 746, 745, 744, 743, 742, 741, 740, 739, 738, 737, 733, 732, 731, 730, 729, 728, 727, 726, 725, 724, 723, 722, 721, 720, 719, 718, 717, 716, 715, 711, 710, 709, 708, 707, 706, 705, 704, 703, 702, 701, 700, 699, 698, 697, 696, 695, 694, 693, 692, 691, 690, 689, 688, 687, 686, 685, 678, 677, 676, 675, 674, 673, 672, 671, 670, 669, 668, 667, 666, 665, 664, 663, 662, 661, 660, 659, 653, 652, 651, 650, 649, 648, 647, 646, 645, 644, 643, 642, 641, 640, 639, 638, 637, 631, 630, 629, 628, 627, 626, 625, 624, 623, 622, 621, 620, 619, 618, 617, 616, 615, 614, 613, 612, 611, 610, 609, 608, 607, 606, 605, 597, 596, 595, 594, 593, 592, 591, 590, 589, 588, 587, 586, 585, 584, 579, 578, 577, 576, 575, 574, 573, 572, 571, 570, 569, 568, 567, 566, 565, 564, 563, 562, 561, 555, 554, 553, 552, 551, 550, 549, 546, 545, 544, 543, 542, 541, 540, 539, 538, 537, 536, 535, 534, 533, 532, 526, 525, 524, 523, 522, 521, 520, 519, 518, 517, 516, 515, 514, 513, 512, 511, 510, 509, 508, 507, 506, 505, 504, 503, 502, 501, 500, 499, 498, 497, 496, 495, 494, 493, 492, 491, 490, 489, 488, 487, 486, 476, 475, 474, 473, 472, 471, 470, 464, 463, 462, 461, 460, 459, 458, 457, 456, 455, 454, 453, 452, 451, 450, 449, 448, 447, 446, 445, 441, 440, 439, 438, 437, 436, 435, 434, 433, 432, 431, 430, 429, 428, 427, 426, 425, 424, 423, 422, 421, 420, 419, 418, 417, 416, 415, 414, 413, 412, 411, 410, 409, 408, 407, 406, 400, 399, 398, 397, 396, 395, 394, 393, 389, 385, 384, 383, 382, 381, 377, 376, 375, 374, 373, 372, 371, 370, 369, 365, 364, 363, 362, 361, 360, 359, 358, 357, 356, 355, 351, 350, 349, 348, 347, 344, 343, 342, 341, 340, 339, 338, 337, 336, 335, 334, 333, 332, 331, 330, 329, 328, 325, 324, 323, 322, 321, 320, 319, 318, 317, 316, 315, 311, 310, 309, 308, 307, 306, 305, 304, 303, 302, 301, 300, 299, 298, 297, 296, 295, 294, 293, 292, 291, 290, 289, 288, 287, 286, 285, 284, 283, 282, 279, 278, 277, 276, 273, 272, 271, 270, 269, 268, 267, 266, 259, 258, 257, 254, 253, 252, 245, 244, 243, 242, 241, 236, 235, 232, 228, 227, 223, 220, 219, 218, 215, 214, 213, 212, 206, 205, 204, 203, 202, 201, 200, 199, 194, 193, 192, 191, 190, 189, 188, 187, 183, 182, 181, 180, 179, 178, 177, 174, 173, 172, 171, 170, 157, 136, 132, 115, 91, 85, 80, 73, 67, 62, 901, 5, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901}; static const flex_int16_t yy_chk[1238] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 10, 10, 11, 15, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 52, 21, 24, 26, 26, 17, 15, 31, 52, 11, 20, 760, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 24, 21, 24, 24, 33, 37, 55, 37, 42, 31, 20, 21, 154, 43, 154, 44, 37, 43, 33, 33, 20, 42, 35, 20, 21, 34, 35, 34, 44, 38, 34, 34, 35, 20, 761, 35, 36, 38, 21, 38, 36, 40, 38, 49, 762, 36, 49, 20, 38, 40, 20, 36, 41, 46, 49, 41, 111, 55, 41, 41, 40, 49, 48, 41, 41, 763, 41, 111, 46, 48, 48, 46, 76, 48, 51, 72, 72, 50, 51, 48, 48, 50, 48, 74, 74, 50, 75, 51, 50, 75, 112, 94, 102, 127, 76, 94, 102, 102, 72, 72, 764, 127, 136, 112, 76, 122, 74, 74, 122, 122, 133, 138, 122, 75, 122, 131, 75, 76, 136, 136, 765, 131, 149, 133, 138, 133, 766, 77, 141, 77, 149, 76, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 142, 141, 148, 148, 150, 163, 163, 186, 186, 161, 767, 161, 150, 142, 161, 161, 161, 161, 161, 161, 161, 161, 161, 161, 768, 164, 770, 164, 163, 163, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 169, 181, 218, 218, 218, 230, 493, 248, 771, 230, 493, 168, 307, 307, 181, 248, 254, 254, 254, 273, 273, 273, 285, 285, 285, 772, 773, 169, 294, 294, 294, 298, 298, 298, 168, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 774, 261, 263, 263, 263, 263, 263, 263, 263, 263, 263, 263, 308, 308, 308, 350, 350, 350, 394, 394, 394, 776, 777, 263, 261, 407, 407, 407, 408, 408, 408, 409, 409, 409, 394, 394, 464, 464, 464, 510, 510, 510, 532, 780, 782, 533, 263, 552, 552, 552, 642, 784, 464, 464, 532, 510, 510, 533, 588, 588, 588, 643, 642, 552, 552, 785, 552, 613, 613, 613, 643, 673, 643, 643, 588, 588, 696, 552, 786, 787, 673, 788, 673, 613, 613, 696, 789, 696, 791, 792, 793, 794, 795, 796, 799, 800, 801, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 833, 834, 835, 836, 839, 840, 841, 843, 844, 845, 847, 848, 849, 852, 853, 854, 855, 856, 857, 858, 859, 860, 862, 863, 864, 865, 866, 867, 868, 869, 870, 872, 873, 874, 875, 877, 881, 885, 886, 887, 889, 890, 891, 893, 896, 897, 898, 899, 902, 902, 759, 758, 757, 902, 903, 903, 903, 903, 903, 904, 904, 904, 904, 904, 905, 756, 905, 906, 755, 906, 907, 907, 907, 754, 752, 751, 750, 749, 748, 747, 746, 745, 744, 742, 741, 740, 739, 738, 737, 736, 735, 734, 733, 732, 731, 730, 729, 728, 727, 726, 725, 724, 723, 722, 721, 720, 719, 718, 717, 716, 715, 714, 713, 712, 711, 709, 708, 707, 706, 705, 704, 703, 701, 700, 699, 698, 695, 693, 692, 691, 689, 688, 687, 686, 685, 684, 683, 682, 681, 680, 679, 678, 677, 676, 675, 672, 671, 670, 669, 668, 667, 665, 664, 663, 662, 661, 660, 658, 657, 656, 655, 654, 653, 652, 651, 650, 649, 648, 647, 646, 645, 644, 639, 637, 636, 635, 634, 633, 632, 628, 627, 626, 625, 624, 623, 622, 621, 620, 618, 617, 616, 615, 611, 610, 608, 607, 605, 604, 603, 602, 601, 600, 599, 598, 594, 593, 592, 590, 589, 587, 586, 585, 584, 583, 582, 581, 580, 579, 578, 576, 575, 570, 569, 568, 567, 566, 565, 563, 562, 560, 559, 558, 557, 556, 554, 553, 551, 550, 549, 548, 546, 545, 544, 543, 540, 539, 538, 537, 536, 535, 531, 530, 529, 528, 527, 526, 523, 522, 521, 520, 519, 518, 517, 516, 515, 514, 513, 512, 511, 509, 508, 505, 499, 497, 496, 495, 492, 489, 488, 487, 486, 475, 474, 473, 472, 471, 469, 468, 467, 466, 465, 462, 460, 459, 458, 456, 455, 453, 452, 450, 449, 448, 446, 445, 440, 439, 437, 436, 435, 434, 433, 432, 431, 430, 429, 428, 427, 425, 424, 423, 422, 421, 420, 419, 418, 416, 415, 414, 413, 412, 411, 410, 406, 402, 401, 400, 399, 398, 395, 393, 383, 381, 377, 376, 375, 374, 372, 371, 369, 365, 363, 362, 361, 360, 359, 358, 357, 356, 351, 349, 348, 347, 346, 345, 343, 342, 339, 338, 337, 336, 335, 334, 333, 332, 331, 330, 329, 328, 327, 326, 325, 324, 323, 322, 321, 320, 319, 318, 317, 316, 315, 314, 313, 312, 309, 306, 305, 304, 303, 302, 301, 300, 299, 297, 293, 291, 290, 289, 288, 284, 283, 282, 281, 280, 279, 278, 277, 276, 272, 271, 269, 268, 267, 266, 259, 258, 257, 256, 255, 253, 252, 251, 250, 249, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 229, 228, 227, 226, 225, 224, 223, 222, 221, 220, 219, 217, 216, 215, 214, 213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202, 201, 200, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 185, 184, 183, 182, 180, 179, 178, 177, 176, 175, 173, 172, 157, 156, 155, 153, 152, 151, 147, 146, 145, 144, 143, 140, 139, 137, 135, 134, 132, 130, 129, 128, 126, 125, 124, 123, 121, 120, 118, 117, 116, 115, 114, 113, 110, 109, 108, 107, 106, 105, 104, 103, 101, 100, 99, 98, 97, 96, 95, 93, 92, 91, 87, 83, 53, 47, 45, 39, 32, 25, 22, 19, 14, 9, 5, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901, 901}; /* Table of booleans, true if rule could match eol. */ static const flex_int32_t yy_rule_can_match_eol[250] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET /* // // Copyright 2002 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file contains the Lex specification for GLSL ES. Based on ANSI C grammar, Lex specification: http://www.lysator.liu.se/c/ANSI-C-grammar-l.html IF YOU MODIFY THIS FILE YOU ALSO NEED TO RUN scripts/run_code_generation.py WHICH GENERATES THE GLSL ES LEXER (glslang_lex_autogen.cpp). */ #include "compiler/preprocessor/Token.h" #include "compiler/translator/ParseContext.h" #include "compiler/translator/glslang.h" #include "compiler/translator/length_limits.h" #include "compiler/translator/util.h" using namespace sh; #include "glslang_tab_autogen.h" /* windows only pragma */ #ifdef _MSC_VER # pragma warning(disable : 4102) #endif // Workaround for flex using the register keyword, deprecated in C++11. #ifdef __cplusplus # if __cplusplus > 199711L # define register # endif #endif #define YY_NO_INPUT #define YY_USER_ACTION \ yylloc->first_file = yylloc->last_file = yycolumn; \ yylloc->first_line = yylloc->last_line = yylineno; #define YY_INPUT(buf, result, max_size) result = string_input(buf, max_size, yyscanner); static yy_size_t string_input(char *buf, yy_size_t max_size, yyscan_t yyscanner); static int check_type(yyscan_t yyscanner); static int reserved_word(yyscan_t yyscanner); // Tests if an extension is enabled. If the extension is promoted to core, this function returns // true. static bool is_extension_enabled_or_is_core(TParseContext *context, int extension_version, TExtension extension, int promotion_version); // Helpers to determine if a symbol is reserved, keyword in extension or core, or identifier. // Formatted as: // // [V1_reserved_][V2_extension_][V3_keyword] // // which means in version V1, the symbol is reserved, and remains reserved until V3. From versions // V2 until V3, it's a keyword if the extension is enabled. From version V3 on, it's a keyword in // the spec itself. Prior to V1, the symbol can be used as identifier. static int ES2_reserved_ES3_keyword(TParseContext *context, int token); static int ES2_keyword_ES3_reserved(TParseContext *context, int token); static int ES3_keyword(TParseContext *context, int token); static int ES3_reserved_ES3_1_keyword(TParseContext *context, int token); static int ES2_reserved_ES3_1_keyword(TParseContext *context, int token); static int ES3_1_keyword(TParseContext *context, int token); static int ES2_reserved_ES2_extension_ES3_keyword(TParseContext *context, TExtension extension, int token); static int ES3_extension(TParseContext *context, TExtension extension, int token); static int ES3_reserved_ES3_1_extension_ES3_2_keyword(TParseContext *context, TExtension extension, int token); static int ES3_reserved_ES3_extension(TParseContext *context, TExtension extension, int token); static int ES3_reserved_ES3_extension_ES3_1_keyword(TParseContext *context, TExtension extension, int token); static int ES3_1_reserved_ES3_1_extension_ES3_2_keyword(TParseContext *context, TExtension extension, int token); static int WEBGL_video_texture_extension(TParseContext *context, int token); static int uint_constant(TParseContext *context); static int int_constant(TParseContext *context); static int float_constant(yyscan_t yyscanner); static int floatsuffix_check(TParseContext *context); static int yuvcscstandardext_constant(TParseContext *context); #define INITIAL 0 #define FIELDS 1 #define YY_EXTRA_TYPE TParseContext * /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE *yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; int yy_n_chars; int yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char *yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE *yylval_r; YYLTYPE *yylloc_r; }; /* end struct yyguts_t */ static int yy_init_globals(yyscan_t yyscanner); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ #define yylval yyg->yylval_r #define yylloc yyg->yylloc_r int yylex_init(yyscan_t *scanner); int yylex_init_extra(YY_EXTRA_TYPE user_defined, yyscan_t *scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy(yyscan_t yyscanner); int yyget_debug(yyscan_t yyscanner); void yyset_debug(int debug_flag, yyscan_t yyscanner); YY_EXTRA_TYPE yyget_extra(yyscan_t yyscanner); void yyset_extra(YY_EXTRA_TYPE user_defined, yyscan_t yyscanner); FILE *yyget_in(yyscan_t yyscanner); void yyset_in(FILE *_in_str, yyscan_t yyscanner); FILE *yyget_out(yyscan_t yyscanner); void yyset_out(FILE *_out_str, yyscan_t yyscanner); int yyget_leng(yyscan_t yyscanner); char *yyget_text(yyscan_t yyscanner); int yyget_lineno(yyscan_t yyscanner); void yyset_lineno(int _line_number, yyscan_t yyscanner); int yyget_column(yyscan_t yyscanner); void yyset_column(int _column_no, yyscan_t yyscanner); YYSTYPE *yyget_lval(yyscan_t yyscanner); void yyset_lval(YYSTYPE *yylval_param, yyscan_t yyscanner); YYLTYPE *yyget_lloc(yyscan_t yyscanner); void yyset_lloc(YYLTYPE *yylloc_param, yyscan_t yyscanner); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP # ifdef __cplusplus extern "C" int yywrap(yyscan_t yyscanner); # else extern int yywrap(yyscan_t yyscanner); # endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy(char *, const char *, int, yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen(const char *, yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT # ifdef __cplusplus static int yyinput(yyscan_t yyscanner); # else static int input(yyscan_t yyscanner); # endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE # ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ # define YY_READ_BUF_SIZE 16384 # else # define YY_READ_BUF_SIZE 8192 # endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ # define ECHO \ do \ { \ if (fwrite(yytext, (size_t)yyleng, 1, yyout)) \ { \ } \ } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT # define YY_INPUT(buf, result, max_size) \ if (YY_CURRENT_BUFFER_LVALUE->yy_is_interactive) \ { \ int c = '*'; \ int n; \ for (n = 0; n < max_size && (c = getc(yyin)) != EOF && c != '\n'; ++n) \ buf[n] = (char)c; \ if (c == '\n') \ buf[n++] = (char)c; \ if (c == EOF && ferror(yyin)) \ YY_FATAL_ERROR("input in flex scanner failed"); \ result = n; \ } \ else \ { \ errno = 0; \ while ((result = (int)fread(buf, 1, (yy_size_t)max_size, yyin)) == 0 && ferror(yyin)) \ { \ if (errno != EINTR) \ { \ YY_FATAL_ERROR("input in flex scanner failed"); \ break; \ } \ errno = 0; \ clearerr(yyin); \ } \ } #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate # define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR # define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR # define YY_FATAL_ERROR(msg) yy_fatal_error(msg, yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL # define YY_DECL_IS_OURS 1 extern int yylex(YYSTYPE *yylval_param, YYLTYPE *yylloc_param, yyscan_t yyscanner); # define YY_DECL int yylex(YYSTYPE *yylval_param, YYLTYPE *yylloc_param, yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION # define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK # define YY_BREAK /*LINTED*/ break; #endif #define YY_RULE_SETUP YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; yylval = yylval_param; yylloc = yylloc_param; if (!yyg->yy_init) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if (!yyg->yy_start) yyg->yy_start = 1; /* first start state */ if (!yyin) yyin = stdin; if (!yyout) yyout = stdout; if (!YY_CURRENT_BUFFER) { yyensure_buffer_stack(yyscanner); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin, YY_BUF_SIZE, yyscanner); } yy_load_buffer_state(yyscanner); } { TParseContext *context = yyextra; while (/*CONSTCOND*/ 1) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if (yy_accept[yy_current_state]) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while (yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state) { yy_current_state = (int)yy_def[yy_current_state]; if (yy_current_state >= 902) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; ++yy_cp; } while (yy_current_state != 901); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if (yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act]) { int yyl; for (yyl = 0; yyl < yyleng; ++yyl) if (yytext[yyl] == '\n') do { yylineno++; yycolumn = 0; } while (0); } do_action: /* This label is used only to access EOF actions. */ switch (yy_act) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP { return INVARIANT; } YY_BREAK case 2: YY_RULE_SETUP { return HIGH_PRECISION; } YY_BREAK case 3: YY_RULE_SETUP { return MEDIUM_PRECISION; } YY_BREAK case 4: YY_RULE_SETUP { return LOW_PRECISION; } YY_BREAK case 5: YY_RULE_SETUP { return PRECISION; } YY_BREAK case 6: YY_RULE_SETUP { return ES2_keyword_ES3_reserved(context, ATTRIBUTE); } YY_BREAK case 7: YY_RULE_SETUP { return CONST_QUAL; } YY_BREAK case 8: YY_RULE_SETUP { return UNIFORM; } YY_BREAK case 9: YY_RULE_SETUP { return ES3_1_keyword(context, BUFFER); } YY_BREAK case 10: YY_RULE_SETUP { return ES2_keyword_ES3_reserved(context, VARYING); } YY_BREAK case 11: YY_RULE_SETUP { return BREAK; } YY_BREAK case 12: YY_RULE_SETUP { return CONTINUE; } YY_BREAK case 13: YY_RULE_SETUP { return DO; } YY_BREAK case 14: YY_RULE_SETUP { return FOR; } YY_BREAK case 15: YY_RULE_SETUP { return WHILE; } YY_BREAK case 16: YY_RULE_SETUP { return IF; } YY_BREAK case 17: YY_RULE_SETUP { return ELSE; } YY_BREAK case 18: YY_RULE_SETUP { return ES2_reserved_ES3_keyword(context, SWITCH); } YY_BREAK case 19: YY_RULE_SETUP { return ES3_keyword(context, CASE); } YY_BREAK case 20: YY_RULE_SETUP { return ES2_reserved_ES3_keyword(context, DEFAULT); } YY_BREAK case 21: YY_RULE_SETUP { return ES3_keyword(context, CENTROID); } YY_BREAK case 22: YY_RULE_SETUP { return ES2_reserved_ES3_keyword(context, FLAT); } YY_BREAK case 23: YY_RULE_SETUP { return ES3_keyword(context, SMOOTH); } YY_BREAK case 24: YY_RULE_SETUP { return ES3_reserved_ES3_extension( context, TExtension::NV_shader_noperspective_interpolation, NOPERSPECTIVE); } YY_BREAK case 25: YY_RULE_SETUP { return IN_QUAL; } YY_BREAK case 26: YY_RULE_SETUP { return OUT_QUAL; } YY_BREAK case 27: YY_RULE_SETUP { return INOUT_QUAL; } YY_BREAK case 28: YY_RULE_SETUP { return ES3_1_keyword(context, SHARED); } YY_BREAK case 29: YY_RULE_SETUP { return FLOAT_TYPE; } YY_BREAK case 30: YY_RULE_SETUP { return INT_TYPE; } YY_BREAK case 31: YY_RULE_SETUP { return ES3_keyword(context, UINT_TYPE); } YY_BREAK case 32: YY_RULE_SETUP { return VOID_TYPE; } YY_BREAK case 33: YY_RULE_SETUP { return BOOL_TYPE; } YY_BREAK case 34: YY_RULE_SETUP { yylval->lex.b = true; return BOOLCONSTANT; } YY_BREAK case 35: YY_RULE_SETUP { yylval->lex.b = false; return BOOLCONSTANT; } YY_BREAK case 36: YY_RULE_SETUP { return DISCARD; } YY_BREAK case 37: YY_RULE_SETUP { return RETURN; } YY_BREAK case 38: YY_RULE_SETUP { return MATRIX2; } YY_BREAK case 39: YY_RULE_SETUP { return MATRIX3; } YY_BREAK case 40: YY_RULE_SETUP { return MATRIX4; } YY_BREAK case 41: YY_RULE_SETUP { return ES3_keyword(context, MATRIX2); } YY_BREAK case 42: YY_RULE_SETUP { return ES3_keyword(context, MATRIX3); } YY_BREAK case 43: YY_RULE_SETUP { return ES3_keyword(context, MATRIX4); } YY_BREAK case 44: YY_RULE_SETUP { return ES3_keyword(context, MATRIX2x3); } YY_BREAK case 45: YY_RULE_SETUP { return ES3_keyword(context, MATRIX3x2); } YY_BREAK case 46: YY_RULE_SETUP { return ES3_keyword(context, MATRIX2x4); } YY_BREAK case 47: YY_RULE_SETUP { return ES3_keyword(context, MATRIX4x2); } YY_BREAK case 48: YY_RULE_SETUP { return ES3_keyword(context, MATRIX3x4); } YY_BREAK case 49: YY_RULE_SETUP { return ES3_keyword(context, MATRIX4x3); } YY_BREAK case 50: YY_RULE_SETUP { return VEC2; } YY_BREAK case 51: YY_RULE_SETUP { return VEC3; } YY_BREAK case 52: YY_RULE_SETUP { return VEC4; } YY_BREAK case 53: YY_RULE_SETUP { return IVEC2; } YY_BREAK case 54: YY_RULE_SETUP { return IVEC3; } YY_BREAK case 55: YY_RULE_SETUP { return IVEC4; } YY_BREAK case 56: YY_RULE_SETUP { return BVEC2; } YY_BREAK case 57: YY_RULE_SETUP { return BVEC3; } YY_BREAK case 58: YY_RULE_SETUP { return BVEC4; } YY_BREAK case 59: YY_RULE_SETUP { return ES3_keyword(context, UVEC2); } YY_BREAK case 60: YY_RULE_SETUP { return ES3_keyword(context, UVEC3); } YY_BREAK case 61: YY_RULE_SETUP { return ES3_keyword(context, UVEC4); } YY_BREAK case 62: YY_RULE_SETUP { return SAMPLER2D; } YY_BREAK case 63: YY_RULE_SETUP { return SAMPLERCUBE; } YY_BREAK case 64: YY_RULE_SETUP { return SAMPLER_EXTERNAL_OES; } YY_BREAK case 65: YY_RULE_SETUP { return ES2_reserved_ES2_extension_ES3_keyword( context, TExtension::OES_texture_3D, SAMPLER3D); } YY_BREAK case 66: YY_RULE_SETUP { return ES2_reserved_ES3_keyword(context, SAMPLER3DRECT); } YY_BREAK case 67: YY_RULE_SETUP { return SAMPLER2DRECT; } YY_BREAK case 68: YY_RULE_SETUP { return ES3_keyword(context, SAMPLER2DARRAY); } YY_BREAK case 69: YY_RULE_SETUP { return ES3_reserved_ES3_extension_ES3_1_keyword( context, TExtension::ANGLE_texture_multisample, SAMPLER2DMS); } YY_BREAK case 70: YY_RULE_SETUP { return ES3_keyword(context, ISAMPLER2D); } YY_BREAK case 71: YY_RULE_SETUP { return ES3_keyword(context, ISAMPLER3D); } YY_BREAK case 72: YY_RULE_SETUP { return ES3_keyword(context, ISAMPLERCUBE); } YY_BREAK case 73: YY_RULE_SETUP { return ES3_keyword(context, ISAMPLER2DARRAY); } YY_BREAK case 74: YY_RULE_SETUP { return ES3_reserved_ES3_extension_ES3_1_keyword( context, TExtension::ANGLE_texture_multisample, ISAMPLER2DMS); } YY_BREAK case 75: YY_RULE_SETUP { return ES3_keyword(context, USAMPLER2D); } YY_BREAK case 76: YY_RULE_SETUP { return ES3_keyword(context, USAMPLER3D); } YY_BREAK case 77: YY_RULE_SETUP { return ES3_keyword(context, USAMPLERCUBE); } YY_BREAK case 78: YY_RULE_SETUP { return ES3_keyword(context, USAMPLER2DARRAY); } YY_BREAK case 79: YY_RULE_SETUP { return ES3_reserved_ES3_extension_ES3_1_keyword( context, TExtension::ANGLE_texture_multisample, USAMPLER2DMS); } YY_BREAK case 80: YY_RULE_SETUP { return ES2_reserved_ES3_keyword(context, SAMPLER2DSHADOW); } YY_BREAK case 81: YY_RULE_SETUP { return ES3_keyword(context, SAMPLERCUBESHADOW); } YY_BREAK case 82: YY_RULE_SETUP { return ES3_keyword(context, SAMPLER2DARRAYSHADOW); } YY_BREAK case 83: YY_RULE_SETUP { return ES3_extension(context, TExtension::EXT_YUV_target, SAMPLEREXTERNAL2DY2YEXT); } YY_BREAK case 84: YY_RULE_SETUP { return ES3_reserved_ES3_1_extension_ES3_2_keyword( context, TExtension::OES_texture_storage_multisample_2d_array, SAMPLER2DMSARRAY); } YY_BREAK case 85: YY_RULE_SETUP { return ES3_reserved_ES3_1_extension_ES3_2_keyword( context, TExtension::OES_texture_storage_multisample_2d_array, ISAMPLER2DMSARRAY); } YY_BREAK case 86: YY_RULE_SETUP { return ES3_reserved_ES3_1_extension_ES3_2_keyword( context, TExtension::OES_texture_storage_multisample_2d_array, USAMPLER2DMSARRAY); } YY_BREAK case 87: YY_RULE_SETUP { return WEBGL_video_texture_extension(context, SAMPLERVIDEOWEBGL); } YY_BREAK case 88: YY_RULE_SETUP { return STRUCT; } YY_BREAK case 89: YY_RULE_SETUP { return ES3_keyword(context, LAYOUT); } YY_BREAK case 90: YY_RULE_SETUP { return ES3_extension(context, TExtension::EXT_YUV_target, YUVCSCSTANDARDEXT); } YY_BREAK case 91: YY_RULE_SETUP { return yuvcscstandardext_constant(context); } YY_BREAK case 92: YY_RULE_SETUP { return yuvcscstandardext_constant(context); } YY_BREAK case 93: YY_RULE_SETUP { return yuvcscstandardext_constant(context); } YY_BREAK case 94: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, IMAGE2D); } YY_BREAK case 95: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, IIMAGE2D); } YY_BREAK case 96: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, UIMAGE2D); } YY_BREAK case 97: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, IMAGE2DARRAY); } YY_BREAK case 98: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, IIMAGE2DARRAY); } YY_BREAK case 99: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, UIMAGE2DARRAY); } YY_BREAK case 100: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, IMAGE3D); } YY_BREAK case 101: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, UIMAGE3D); } YY_BREAK case 102: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, IIMAGE3D); } YY_BREAK case 103: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, IIMAGECUBE); } YY_BREAK case 104: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, UIMAGECUBE); } YY_BREAK case 105: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, IMAGECUBE); } YY_BREAK case 106: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, READONLY); } YY_BREAK case 107: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, WRITEONLY); } YY_BREAK case 108: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, COHERENT); } YY_BREAK case 109: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, RESTRICT); } YY_BREAK case 110: YY_RULE_SETUP { return ES2_reserved_ES3_1_keyword(context, VOLATILE); } YY_BREAK case 111: YY_RULE_SETUP { return ES3_reserved_ES3_1_keyword(context, ATOMICUINT); } YY_BREAK case 112: YY_RULE_SETUP { return ES3_1_reserved_ES3_1_extension_ES3_2_keyword( context, TExtension::EXT_gpu_shader5, PRECISE); } YY_BREAK /* Reserved keywords for GLSL ES 3.00 that are not reserved for GLSL ES 1.00 */ case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: case 124: case 125: case 126: case 127: case 128: case 129: case 130: case 131: case 132: case 133: case 134: case 135: case 136: case 137: case 138: case 139: case 140: case 141: case 142: case 143: case 144: YY_RULE_SETUP { if (context->getShaderVersion() < 300) { yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return check_type(yyscanner); } return reserved_word(yyscanner); } YY_BREAK /* Reserved keywords in GLSL ES 1.00 that are not reserved in GLSL ES 3.00 */ case 145: YY_RULE_SETUP { if (context->getShaderVersion() >= 300) { yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return check_type(yyscanner); } return reserved_word(yyscanner); } YY_BREAK /* Reserved keywords */ case 146: case 147: case 148: case 149: case 150: case 151: case 152: case 153: case 154: case 155: case 156: case 157: case 158: case 159: case 160: case 161: case 162: case 163: case 164: case 165: case 166: case 167: case 168: case 169: case 170: case 171: case 172: case 173: case 174: case 175: case 176: case 177: case 178: case 179: case 180: case 181: case 182: case 183: case 184: case 185: YY_RULE_SETUP { return reserved_word(yyscanner); } YY_BREAK case 186: YY_RULE_SETUP { yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return check_type(yyscanner); } YY_BREAK case 187: YY_RULE_SETUP { return int_constant(context); } YY_BREAK case 188: YY_RULE_SETUP { return int_constant(context); } YY_BREAK case 189: YY_RULE_SETUP { return int_constant(context); } YY_BREAK case 190: YY_RULE_SETUP { return uint_constant(context); } YY_BREAK case 191: YY_RULE_SETUP { return uint_constant(context); } YY_BREAK case 192: YY_RULE_SETUP { return uint_constant(context); } YY_BREAK case 193: YY_RULE_SETUP { return float_constant(yyscanner); } YY_BREAK case 194: YY_RULE_SETUP { return float_constant(yyscanner); } YY_BREAK case 195: YY_RULE_SETUP { return float_constant(yyscanner); } YY_BREAK case 196: YY_RULE_SETUP { return floatsuffix_check(context); } YY_BREAK case 197: YY_RULE_SETUP { return floatsuffix_check(context); } YY_BREAK case 198: YY_RULE_SETUP { return floatsuffix_check(context); } YY_BREAK case 199: YY_RULE_SETUP { return ADD_ASSIGN; } YY_BREAK case 200: YY_RULE_SETUP { return SUB_ASSIGN; } YY_BREAK case 201: YY_RULE_SETUP { return MUL_ASSIGN; } YY_BREAK case 202: YY_RULE_SETUP { return DIV_ASSIGN; } YY_BREAK case 203: YY_RULE_SETUP { return MOD_ASSIGN; } YY_BREAK case 204: YY_RULE_SETUP { return LEFT_ASSIGN; } YY_BREAK case 205: YY_RULE_SETUP { return RIGHT_ASSIGN; } YY_BREAK case 206: YY_RULE_SETUP { return AND_ASSIGN; } YY_BREAK case 207: YY_RULE_SETUP { return XOR_ASSIGN; } YY_BREAK case 208: YY_RULE_SETUP { return OR_ASSIGN; } YY_BREAK case 209: YY_RULE_SETUP { return INC_OP; } YY_BREAK case 210: YY_RULE_SETUP { return DEC_OP; } YY_BREAK case 211: YY_RULE_SETUP { return AND_OP; } YY_BREAK case 212: YY_RULE_SETUP { return OR_OP; } YY_BREAK case 213: YY_RULE_SETUP { return XOR_OP; } YY_BREAK case 214: YY_RULE_SETUP { return LE_OP; } YY_BREAK case 215: YY_RULE_SETUP { return GE_OP; } YY_BREAK case 216: YY_RULE_SETUP { return EQ_OP; } YY_BREAK case 217: YY_RULE_SETUP { return NE_OP; } YY_BREAK case 218: YY_RULE_SETUP { return LEFT_OP; } YY_BREAK case 219: YY_RULE_SETUP { return RIGHT_OP; } YY_BREAK case 220: YY_RULE_SETUP { return SEMICOLON; } YY_BREAK case 221: YY_RULE_SETUP { return LEFT_BRACE; } YY_BREAK case 222: YY_RULE_SETUP { return RIGHT_BRACE; } YY_BREAK case 223: YY_RULE_SETUP { return COMMA; } YY_BREAK case 224: YY_RULE_SETUP { return COLON; } YY_BREAK case 225: YY_RULE_SETUP { return EQUAL; } YY_BREAK case 226: YY_RULE_SETUP { return LEFT_PAREN; } YY_BREAK case 227: YY_RULE_SETUP { return RIGHT_PAREN; } YY_BREAK case 228: YY_RULE_SETUP { return LEFT_BRACKET; } YY_BREAK case 229: YY_RULE_SETUP { return RIGHT_BRACKET; } YY_BREAK case 230: YY_RULE_SETUP { BEGIN(FIELDS); return DOT; } YY_BREAK case 231: YY_RULE_SETUP { return BANG; } YY_BREAK case 232: YY_RULE_SETUP { return DASH; } YY_BREAK case 233: YY_RULE_SETUP { return TILDE; } YY_BREAK case 234: YY_RULE_SETUP { return PLUS; } YY_BREAK case 235: YY_RULE_SETUP { return STAR; } YY_BREAK case 236: YY_RULE_SETUP { return SLASH; } YY_BREAK case 237: YY_RULE_SETUP { return PERCENT; } YY_BREAK case 238: YY_RULE_SETUP { return LEFT_ANGLE; } YY_BREAK case 239: YY_RULE_SETUP { return RIGHT_ANGLE; } YY_BREAK case 240: YY_RULE_SETUP { return VERTICAL_BAR; } YY_BREAK case 241: YY_RULE_SETUP { return CARET; } YY_BREAK case 242: YY_RULE_SETUP { return AMPERSAND; } YY_BREAK case 243: YY_RULE_SETUP { return QUESTION; } YY_BREAK case 244: YY_RULE_SETUP { BEGIN(INITIAL); yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return FIELD_SELECTION; } YY_BREAK case 245: YY_RULE_SETUP {} YY_BREAK case 246: YY_RULE_SETUP { yyextra->error(*yylloc, "Illegal character at fieldname start", yytext); return 0; } YY_BREAK case 247: /* rule 247 can match eol */ YY_RULE_SETUP {} YY_BREAK case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(FIELDS): { yyterminate(); } YY_BREAK case 248: YY_RULE_SETUP { assert(false); return 0; } YY_BREAK case 249: YY_RULE_SETUP ECHO; YY_BREAK case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int)(yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if (YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if (yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state(yyscanner); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans(yy_current_state, yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if (yy_next_state) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch (yy_get_next_buffer(yyscanner)) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if (yywrap(yyscanner)) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if (!yyg->yy_did_buffer_switch_on_eof) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state(yyscanner); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state(yyscanner); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR("fatal flex scanner internal error--no action found"); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; int number_to_move, i; int ret_val; if (yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1]) YY_FATAL_ERROR("fatal flex scanner internal error--end of buffer missed"); if (YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0) { /* Don't try to fill the buffer, so this is an EOF. */ if (yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int)(yyg->yy_c_buf_p - yyg->yytext_ptr - 1); for (i = 0; i < number_to_move; ++i) *(dest++) = *(source++); if (YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while (num_to_read <= 0) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int)(yyg->yy_c_buf_p - b->yy_ch_buf); if (b->yy_is_our_buffer) { int new_size = b->yy_buf_size * 2; if (new_size <= 0) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc((void *)b->yy_ch_buf, (yy_size_t)(b->yy_buf_size + 2), yyscanner); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = NULL; if (!b->yy_ch_buf) YY_FATAL_ERROR("fatal error - scanner input buffer overflow"); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if (num_to_read > YY_READ_BUF_SIZE) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ yy_size_t ret = 0; YY_INPUT((&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), ret, num_to_read); yyg->yy_n_chars = static_cast<int>(ret); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if (yyg->yy_n_chars == 0) { if (number_to_move == YY_MORE_ADJ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart(yyin, yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *)yyrealloc( (void *)YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t)new_size, yyscanner); if (!YY_CURRENT_BUFFER_LVALUE->yy_ch_buf) YY_FATAL_ERROR("out of dynamic memory in yy_get_next_buffer()"); /* "- 2" to take care of EOB's */ YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int)(new_size - 2); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state(yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; yy_current_state = yyg->yy_start; for (yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if (yy_accept[yy_current_state]) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while (yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state) { yy_current_state = (int)yy_def[yy_current_state]; if (yy_current_state >= 902) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans(yy_state_type yy_current_state, yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if (yy_accept[yy_current_state]) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while (yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state) { yy_current_state = (int)yy_def[yy_current_state]; if (yy_current_state >= 902) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; yy_is_jam = (yy_current_state == 901); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT # ifdef __cplusplus static int yyinput(yyscan_t yyscanner) # else static int input(yyscan_t yyscanner) # endif { int c; struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if (*yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if (yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ int offset = (int)(yyg->yy_c_buf_p - yyg->yytext_ptr); ++yyg->yy_c_buf_p; switch (yy_get_next_buffer(yyscanner)) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart(yyin, yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if (yywrap(yyscanner)) return 0; if (!yyg->yy_did_buffer_switch_on_eof) YY_NEW_FILE; # ifdef __cplusplus return yyinput(yyscanner); # else return input(yyscanner); # endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *)yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if (c == '\n') do { yylineno++; yycolumn = 0; } while (0); return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart(FILE *input_file, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; if (!YY_CURRENT_BUFFER) { yyensure_buffer_stack(yyscanner); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin, YY_BUF_SIZE, yyscanner); } yy_init_buffer(YY_CURRENT_BUFFER, input_file, yyscanner); yy_load_buffer_state(yyscanner); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void yy_switch_to_buffer(YY_BUFFER_STATE new_buffer, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack(yyscanner); if (YY_CURRENT_BUFFER == new_buffer) return; if (YY_CURRENT_BUFFER) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state(yyscanner); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void yy_load_buffer_state(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer(FILE *file, int size, yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE)yyalloc(sizeof(struct yy_buffer_state), yyscanner); if (!b) YY_FATAL_ERROR("out of dynamic memory in yy_create_buffer()"); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *)yyalloc((yy_size_t)(b->yy_buf_size + 2), yyscanner); if (!b->yy_ch_buf) YY_FATAL_ERROR("out of dynamic memory in yy_create_buffer()"); b->yy_is_our_buffer = 1; yy_init_buffer(b, file, yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * @param yyscanner The scanner object. */ void yy_delete_buffer(YY_BUFFER_STATE b, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; if (!b) return; if (b == YY_CURRENT_BUFFER) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE)0; if (b->yy_is_our_buffer) yyfree((void *)b->yy_ch_buf, yyscanner); yyfree((void *)b, yyscanner); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer(YY_BUFFER_STATE b, FILE *file, yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; yy_flush_buffer(b, yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER) { b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void yy_flush_buffer(YY_BUFFER_STATE b, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; if (!b) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if (b == YY_CURRENT_BUFFER) yy_load_buffer_state(yyscanner); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void yypush_buffer_state(YY_BUFFER_STATE new_buffer, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; if (new_buffer == NULL) return; yyensure_buffer_stack(yyscanner); /* This block is copied from yy_switch_to_buffer. */ if (YY_CURRENT_BUFFER) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state(yyscanner); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void yypop_buffer_state(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER, yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { yy_load_buffer_state(yyscanner); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack(yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */ yyg->yy_buffer_stack = (struct yy_buffer_state **)yyalloc( num_to_alloc * sizeof(struct yy_buffer_state *), yyscanner); if (!yyg->yy_buffer_stack) YY_FATAL_ERROR("out of dynamic memory in yyensure_buffer_stack()"); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state *)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1) { /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state **)yyrealloc( yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state *), yyscanner); if (!yyg->yy_buffer_stack) YY_FATAL_ERROR("out of dynamic memory in yyensure_buffer_stack()"); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state *)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer(char *base, yy_size_t size, yyscan_t yyscanner) { YY_BUFFER_STATE b; if (size < 2 || base[size - 2] != YY_END_OF_BUFFER_CHAR || base[size - 1] != YY_END_OF_BUFFER_CHAR) /* They forgot to leave room for the EOB's. */ return NULL; b = (YY_BUFFER_STATE)yyalloc(sizeof(struct yy_buffer_state), yyscanner); if (!b) YY_FATAL_ERROR("out of dynamic memory in yy_scan_buffer()"); b->yy_buf_size = (int)(size - 2); /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = NULL; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer(b, yyscanner); return b; } /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string(const char *yystr, yyscan_t yyscanner) { return yy_scan_bytes(yystr, (int)strlen(yystr), yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes(const char *yybytes, int _yybytes_len, yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = (yy_size_t)(_yybytes_len + 2); buf = (char *)yyalloc(n, yyscanner); if (!buf) YY_FATAL_ERROR("out of dynamic memory in yy_scan_bytes()"); for (i = 0; i < _yybytes_len; ++i) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len + 1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer(buf, n, yyscanner); if (!b) YY_FATAL_ERROR("bad buffer in yy_scan_bytes()"); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE # define YY_EXIT_FAILURE 2 #endif static void yynoreturn yy_fatal_error(const char *msg, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; (void)yyg; fprintf(stderr, "%s\n", msg); exit(YY_EXIT_FAILURE); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg); \ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } while (0) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE yyget_extra(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int yyget_lineno(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; if (!YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int yyget_column(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; if (!YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *yyget_in(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *yyget_out(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ int yyget_leng(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *yyget_text(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void yyset_extra(YY_EXTRA_TYPE user_defined, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; yyextra = user_defined; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void yyset_lineno(int _line_number, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; /* lineno is only valid if an input buffer exists. */ if (!YY_CURRENT_BUFFER) YY_FATAL_ERROR("yyset_lineno called with no buffer"); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void yyset_column(int _column_no, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; /* column is only valid if an input buffer exists. */ if (!YY_CURRENT_BUFFER) YY_FATAL_ERROR("yyset_column called with no buffer"); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see yy_switch_to_buffer */ void yyset_in(FILE *_in_str, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; yyin = _in_str; } void yyset_out(FILE *_out_str, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; yyout = _out_str; } int yyget_debug(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; return yy_flex_debug; } void yyset_debug(int _bdebug, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; yy_flex_debug = _bdebug; } /* Accessor methods for yylval and yylloc */ YYSTYPE *yyget_lval(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; return yylval; } void yyset_lval(YYSTYPE *yylval_param, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; yylval = yylval_param; } YYLTYPE *yyget_lloc(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; return yylloc; } void yyset_lloc(YYLTYPE *yylloc_param, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; yylloc = yylloc_param; } /* User-visible API */ /* yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int yylex_init(yyscan_t *ptr_yy_globals) { if (ptr_yy_globals == NULL) { errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t)yyalloc(sizeof(struct yyguts_t), NULL); if (*ptr_yy_globals == NULL) { errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals, 0x00, sizeof(struct yyguts_t)); return yy_init_globals(*ptr_yy_globals); } /* yylex_init_extra has the same functionality as yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to yyalloc in * the yyextra field. */ int yylex_init_extra(YY_EXTRA_TYPE yy_user_defined, yyscan_t *ptr_yy_globals) { struct yyguts_t dummy_yyguts; yyset_extra(yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL) { errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t)yyalloc(sizeof(struct yyguts_t), &dummy_yyguts); if (*ptr_yy_globals == NULL) { errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals, 0x00, sizeof(struct yyguts_t)); yyset_extra(yy_user_defined, *ptr_yy_globals); return yy_init_globals(*ptr_yy_globals); } static int yy_init_globals(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = NULL; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = NULL; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = NULL; yyout = NULL; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; /* Pop the buffer stack, destroying each element. */ while (YY_CURRENT_BUFFER) { yy_delete_buffer(YY_CURRENT_BUFFER, yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ yyfree(yyg->yy_buffer_stack, yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ yyfree(yyg->yy_start_stack, yyscanner); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals(yyscanner); /* Destroy the main struct (reentrant only). */ yyfree(yyscanner, yyscanner); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy(char *s1, const char *s2, int n, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; (void)yyg; int i; for (i = 0; i < n; ++i) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen(const char *s, yyscan_t yyscanner) { int n; for (n = 0; s[n]; ++n) ; return n; } #endif void *yyalloc(yy_size_t size, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; (void)yyg; return malloc(size); } void *yyrealloc(void *ptr, yy_size_t size, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return realloc(ptr, size); } void yyfree(void *ptr, yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; (void)yyg; free((char *)ptr); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" yy_size_t string_input(char *buf, yy_size_t max_size, yyscan_t yyscanner) { angle::pp::Token token; yyget_extra(yyscanner)->getPreprocessor().lex(&token); yy_size_t len = token.type == angle::pp::Token::LAST ? 0 : token.text.size(); if (len < max_size) memcpy(buf, token.text.c_str(), len); yyset_column(token.location.file, yyscanner); yyset_lineno(token.location.line, yyscanner); if (len >= max_size) YY_FATAL_ERROR("Input buffer overflow"); else if (len > 0) buf[len++] = ' '; return len; } int check_type(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; int token = IDENTIFIER; // Note that the ImmutableString used here isn't static or pool allocated - but it's fine since // yytext is valid for the duration of its use. const TSymbol *symbol = yyextra->symbolTable.find(ImmutableString(yytext, yyleng), yyextra->getShaderVersion()); if (symbol && symbol->isStruct()) { token = TYPE_NAME; } yylval->lex.symbol = symbol; return token; } int reserved_word(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; yyextra->error(*yylloc, "Illegal use of reserved word", yytext); return 0; } static bool is_extension_enabled_or_is_core(TParseContext *context, int extension_version, TExtension extension, int promotion_version) { int version = context->getShaderVersion(); // If version is at least promotion_version, symbol is definitely keyword. Otherwise it's a // keyword if version is at least extension_version (where the extension was introduced) and // the extension is enabled. return version >= promotion_version || (version >= extension_version && context->isExtensionEnabled(extension)); } int ES2_reserved_ES3_keyword(TParseContext *context, int token) { yyscan_t yyscanner = (yyscan_t)context->getScanner(); if (context->getShaderVersion() < 300) { return reserved_word(yyscanner); } return token; } int ES2_keyword_ES3_reserved(TParseContext *context, int token) { yyscan_t yyscanner = (yyscan_t)context->getScanner(); if (context->getShaderVersion() >= 300) { return reserved_word(yyscanner); } return token; } int ES3_reserved_ES3_1_keyword(TParseContext *context, int token) { struct yyguts_t *yyg = (struct yyguts_t *)context->getScanner(); yyscan_t yyscanner = (yyscan_t)context->getScanner(); if (context->getShaderVersion() < 300) { yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return check_type(yyscanner); } else if (context->getShaderVersion() == 300) { return reserved_word(yyscanner); } return token; } int ES3_keyword(TParseContext *context, int token) { struct yyguts_t *yyg = (struct yyguts_t *)context->getScanner(); yyscan_t yyscanner = (yyscan_t)context->getScanner(); // not a reserved word in GLSL ES 1.00, so could be used as an identifier/type name if (context->getShaderVersion() < 300) { yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return check_type(yyscanner); } return token; } int ES2_reserved_ES3_1_keyword(TParseContext *context, int token) { yyscan_t yyscanner = (yyscan_t)context->getScanner(); if (context->getShaderVersion() < 310) { return reserved_word(yyscanner); } return token; } int ES3_1_keyword(TParseContext *context, int token) { struct yyguts_t *yyg = (struct yyguts_t *)context->getScanner(); yyscan_t yyscanner = (yyscan_t)context->getScanner(); // A keyword in GLSL ES 3.10. if (context->getShaderVersion() >= 310) { return token; } // Otherwise can be used as an identifier/type name yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return check_type(yyscanner); } int WEBGL_video_texture_extension(TParseContext *context, int token) { // Available with WEBGL_video_texture_extension if (context->isExtensionEnabled(TExtension::WEBGL_video_texture)) { return token; } // Otherwise can be used as an identifier/type name struct yyguts_t *yyg = (struct yyguts_t *)context->getScanner(); yyscan_t yyscanner = (yyscan_t)context->getScanner(); yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return check_type(yyscanner); } int ES2_reserved_ES2_extension_ES3_keyword(TParseContext *context, TExtension extension, int token) { yyscan_t yyscanner = (yyscan_t)context->getScanner(); // A keyword in GLSL ES 3.00 or GLSL ES 1.00 with enabled extension. if (is_extension_enabled_or_is_core(context, 100, extension, 300)) { return token; } // Reserved otherwise. return reserved_word(yyscanner); } int ES3_extension(TParseContext *context, TExtension extension, int token) { struct yyguts_t *yyg = (struct yyguts_t *)context->getScanner(); yyscan_t yyscanner = (yyscan_t)context->getScanner(); // a keyword word in GLSL ES 3.00 with enabled extension. if (context->getShaderVersion() >= 300 && context->isExtensionEnabled(extension)) { return token; } // Otherwise can be used as an identifier/type name yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return check_type(yyscanner); } int ES3_reserved_ES3_1_extension_ES3_2_keyword(TParseContext *context, TExtension extension, int token) { struct yyguts_t *yyg = (struct yyguts_t *)context->getScanner(); yyscan_t yyscanner = (yyscan_t)context->getScanner(); // a keyword in GLSL ES 3.10 with enabled extension if (is_extension_enabled_or_is_core(context, 310, extension, 320)) { return token; } // a reserved word in GLSL ES 3.00+ if (context->getShaderVersion() >= 300) { return reserved_word(yyscanner); } // Otherwise can be used as an identifier/type name yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return check_type(yyscanner); } int ES3_reserved_ES3_extension(TParseContext *context, TExtension extension, int token) { struct yyguts_t *yyg = (struct yyguts_t *)context->getScanner(); yyscan_t yyscanner = (yyscan_t)context->getScanner(); if (context->getShaderVersion() >= 300) { if (context->isExtensionEnabled(extension)) { return token; } else { return reserved_word(yyscanner); } } yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return check_type(yyscanner); } int ES3_reserved_ES3_extension_ES3_1_keyword(TParseContext *context, TExtension extension, int token) { struct yyguts_t *yyg = (struct yyguts_t *)context->getScanner(); yyscan_t yyscanner = (yyscan_t)context->getScanner(); // A keyword in GLSL ES 3.00 with enabled extension or in GLSL ES 3.10 if (is_extension_enabled_or_is_core(context, 300, extension, 310)) { return token; } if (context->getShaderVersion() == 300) { return reserved_word(yyscanner); } yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return check_type(yyscanner); } static int ES3_1_reserved_ES3_1_extension_ES3_2_keyword(TParseContext *context, TExtension extension, int token) { struct yyguts_t *yyg = (struct yyguts_t *)context->getScanner(); yyscan_t yyscanner = (yyscan_t)context->getScanner(); // A keyword in GLSL ES 3.20 or GLSL ES 3.10 with enabled extension. if (is_extension_enabled_or_is_core(context, 310, extension, 320)) { return token; } // A reserved word in GLSL ES 3.10 if (context->getShaderVersion() == 310) { return reserved_word(yyscanner); } yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return check_type(yyscanner); } int uint_constant(TParseContext *context) { struct yyguts_t *yyg = (struct yyguts_t *)context->getScanner(); if (context->getShaderVersion() < 300) { context->error(*yylloc, "Unsigned integers are unsupported prior to GLSL ES 3.00", yytext); return 0; } if (!atoi_clamp(yytext, &(yylval->lex.u))) yyextra->error(*yylloc, "Integer overflow", yytext); return UINTCONSTANT; } int floatsuffix_check(TParseContext *context) { struct yyguts_t *yyg = (struct yyguts_t *)context->getScanner(); if (context->getShaderVersion() < 300) { context->error(*yylloc, "Floating-point suffix unsupported prior to GLSL ES 3.00", yytext); return 0; } std::string text = yytext; text.resize(text.size() - 1); if (!strtof_clamp(text, &(yylval->lex.f))) yyextra->warning(*yylloc, "Float overflow", yytext); return (FLOATCONSTANT); } void yyerror(YYLTYPE *lloc, TParseContext *context, void *scanner, const char *reason) { context->error(*lloc, reason, yyget_text(scanner)); } int int_constant(TParseContext *context) { struct yyguts_t *yyg = (struct yyguts_t *)context->getScanner(); unsigned int u; if (!atoi_clamp(yytext, &u)) { if (context->getShaderVersion() >= 300) yyextra->error(*yylloc, "Integer overflow", yytext); else yyextra->warning(*yylloc, "Integer overflow", yytext); } yylval->lex.i = static_cast<int>(u); return INTCONSTANT; } int float_constant(yyscan_t yyscanner) { struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; if (!strtof_clamp(yytext, &(yylval->lex.f))) yyextra->warning(*yylloc, "Float overflow", yytext); return FLOATCONSTANT; } int yuvcscstandardext_constant(TParseContext *context) { struct yyguts_t *yyg = (struct yyguts_t *)context->getScanner(); yyscan_t yyscanner = (yyscan_t)context->getScanner(); // a reserved word in GLSL ES 3.00 with enabled extension, otherwise could be used as an // identifier/type name if (context->getShaderVersion() >= 300 && context->isExtensionEnabled(TExtension::EXT_YUV_target)) { yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return YUVCSCSTANDARDEXTCONSTANT; } yylval->lex.string = AllocatePoolCharArray(yytext, yyleng); return check_type(yyscanner); } int glslang_initialize(TParseContext *context) { yyscan_t scanner = NULL; if (yylex_init_extra(context, &scanner)) return 1; context->setScanner(scanner); return 0; } int glslang_finalize(TParseContext *context) { yyscan_t scanner = context->getScanner(); if (scanner == NULL) return 0; context->setScanner(NULL); yylex_destroy(scanner); return 0; } int glslang_scan(size_t count, const char *const string[], const int length[], TParseContext *context) { yyrestart(NULL, context->getScanner()); yyset_column(0, context->getScanner()); yyset_lineno(1, context->getScanner()); // Initialize preprocessor. angle::pp::Preprocessor *preprocessor = &context->getPreprocessor(); if (!preprocessor->init(count, string, length)) return 1; // Define extension macros. const TExtensionBehavior &extBehavior = context->extensionBehavior(); for (TExtensionBehavior::const_iterator iter = extBehavior.begin(); iter != extBehavior.end(); ++iter) { // OVR_multiview should not be defined for WebGL spec'ed shaders. if (sh::IsWebGLBasedSpec(context->getShaderSpec()) && iter->first == TExtension::OVR_multiview) { continue; } preprocessor->predefineMacro(GetExtensionNameString(iter->first), 1); } if (context->getFragmentPrecisionHigh()) preprocessor->predefineMacro("GL_FRAGMENT_PRECISION_HIGH", 1); preprocessor->setMaxTokenSize(sh::GetGlobalMaxTokenSize(context->getShaderSpec())); return 0; }
38.590017
99
0.540825
[ "object" ]
c6efe89383bb5cbc7c0415f2bd1d06f4f8bbbfb5
16,488
cpp
C++
wireshark-2.0.13/ui/qt/import_text_dialog.cpp
mahrukhfida/mi
7187765aa225e71983969ef5285771ac77c8309a
[ "Apache-2.0" ]
null
null
null
wireshark-2.0.13/ui/qt/import_text_dialog.cpp
mahrukhfida/mi
7187765aa225e71983969ef5285771ac77c8309a
[ "Apache-2.0" ]
null
null
null
wireshark-2.0.13/ui/qt/import_text_dialog.cpp
mahrukhfida/mi
7187765aa225e71983969ef5285771ac77c8309a
[ "Apache-2.0" ]
null
null
null
/* import_text_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <time.h> #include "import_text_dialog.h" #include "wiretap/wtap.h" #include "wiretap/pcap-encap.h" #include <epan/prefs.h> #include "ui/text_import_scanner.h" #include "ui/last_open_dir.h" #include "ui/alert_box.h" #include "ui/help_url.h" #include "file.h" #include "wsutil/file_util.h" #include "wsutil/tempfile.h" #include <ui_import_text_dialog.h> #include "wireshark_application.h" #include "qt_ui_utils.h" #include <QFileDialog> #include <QDebug> #include <QFile> ImportTextDialog::ImportTextDialog(QWidget *parent) : QDialog(parent), ti_ui_(new Ui::ImportTextDialog), import_info_(), file_ok_(false), time_format_ok_(true), ether_type_ok_(true), proto_ok_(true), source_port_ok_(true), dest_port_ok_(true), tag_ok_(true), ppi_ok_(true), max_len_ok_(true) { int encap; int i; ti_ui_->setupUi(this); setWindowTitle(wsApp->windowTitleString(tr("Import From Hex Dump"))); memset(&import_info_, 0, sizeof(import_info_)); import_button_ = ti_ui_->buttonBox->button(QDialogButtonBox::Open); import_button_->setText(tr("Import")); import_button_->setEnabled(false); #ifdef Q_OS_MAC // The grid layout squishes each line edit otherwise. int le_height = ti_ui_->textFileLineEdit->sizeHint().height(); ti_ui_->ethertypeLineEdit->setMinimumHeight(le_height); ti_ui_->protocolLineEdit->setMinimumHeight(le_height); ti_ui_->sourcePortLineEdit->setMinimumHeight(le_height); ti_ui_->destinationPortLineEdit->setMinimumHeight(le_height); ti_ui_->tagLineEdit->setMinimumHeight(le_height); ti_ui_->ppiLineEdit->setMinimumHeight(le_height); #endif on_dateTimeLineEdit_textChanged(ti_ui_->dateTimeLineEdit->text()); for (i = 0; i < ti_ui_->headerGridLayout->count(); i++) { QRadioButton *rb = qobject_cast<QRadioButton *>(ti_ui_->headerGridLayout->itemAt(i)->widget()); if (rb) encap_buttons_.append(rb); } /* Scan all Wiretap encapsulation types */ import_info_.encapsulation = WTAP_ENCAP_ETHERNET; for (encap = import_info_.encapsulation; encap < wtap_get_num_encap_types(); encap++) { /* Check if we can write to a PCAP file * * Exclude wtap encapsulations that require a pseudo header, * because we won't setup one from the text we import and * wiretap doesn't allow us to write 'raw' frames */ if ((wtap_wtap_encap_to_pcap_encap(encap) > 0) && !wtap_encap_requires_phdr(encap)) { const char *name; /* If it has got a name */ if ((name = wtap_encap_string(encap))) { ti_ui_->encapComboBox->addItem(name, QVariant(encap)); } } } ti_ui_->encapComboBox->model()->sort(0); } ImportTextDialog::~ImportTextDialog() { g_free (import_info_.import_text_filename); g_free (import_info_.date_timestamp_format); delete ti_ui_; } QString &ImportTextDialog::capfileName() { return capfile_name_; } void ImportTextDialog::convertTextFile() { char *tmpname; int err; capfile_name_.clear(); /* Use a random name for the temporary import buffer */ import_info_.wdh = wtap_dump_open_tempfile(&tmpname, "import", WTAP_FILE_TYPE_SUBTYPE_PCAP, import_info_.encapsulation, import_info_.max_frame_length, FALSE, &err); capfile_name_.append(tmpname ? tmpname : "temporary file"); qDebug() << capfile_name_ << ":" << import_info_.wdh << import_info_.encapsulation << import_info_.max_frame_length; if (import_info_.wdh == NULL) { open_failure_alert_box(capfile_name_.toUtf8().constData(), err, TRUE); fclose(import_info_.import_text_file); setResult(QDialog::Rejected); return; } text_import_setup(&import_info_); text_importin = import_info_.import_text_file; text_importlex(); text_import_cleanup(); if (fclose(import_info_.import_text_file)) { read_failure_alert_box(import_info_.import_text_filename, errno); } if (!wtap_dump_close(import_info_.wdh, &err)) { write_failure_alert_box(capfile_name_.toUtf8().constData(), err); } } void ImportTextDialog::enableHeaderWidgets(bool enable_buttons) { bool ethertype = false; bool ipv4_proto = false; bool port = false; bool sctp_tag = false; bool sctp_ppi = false; if (enable_buttons) { if (ti_ui_->ethernetButton->isChecked()) { ethertype = true; on_ethertypeLineEdit_textChanged(ti_ui_->ethertypeLineEdit->text()); } else if (ti_ui_->ipv4Button->isChecked()) { ipv4_proto = true; on_protocolLineEdit_textChanged(ti_ui_->protocolLineEdit->text()); } else if (ti_ui_->udpButton->isChecked() || ti_ui_->tcpButton->isChecked()) { port = true; on_sourcePortLineEdit_textChanged(ti_ui_->sourcePortLineEdit->text()); on_destinationPortLineEdit_textChanged(ti_ui_->destinationPortLineEdit->text()); } else if (ti_ui_->sctpButton->isChecked()) { port = true; sctp_tag = true; on_sourcePortLineEdit_textChanged(ti_ui_->sourcePortLineEdit->text()); on_destinationPortLineEdit_textChanged(ti_ui_->destinationPortLineEdit->text()); on_tagLineEdit_textChanged(ti_ui_->tagLineEdit->text()); } if (ti_ui_->sctpDataButton->isChecked()) { port = true; sctp_ppi = true; on_sourcePortLineEdit_textChanged(ti_ui_->sourcePortLineEdit->text()); on_destinationPortLineEdit_textChanged(ti_ui_->destinationPortLineEdit->text()); on_ppiLineEdit_textChanged(ti_ui_->ppiLineEdit->text()); } } foreach (QRadioButton *rb, encap_buttons_) { rb->setEnabled(enable_buttons); } ti_ui_->ethertypeLabel->setEnabled(ethertype); ti_ui_->ethertypeLineEdit->setEnabled(ethertype); ti_ui_->protocolLabel->setEnabled(ipv4_proto); ti_ui_->protocolLineEdit->setEnabled(ipv4_proto); ti_ui_->sourcePortLabel->setEnabled(port); ti_ui_->sourcePortLineEdit->setEnabled(port); ti_ui_->destinationPortLabel->setEnabled(port); ti_ui_->destinationPortLineEdit->setEnabled(port); ti_ui_->tagLabel->setEnabled(sctp_tag); ti_ui_->tagLineEdit->setEnabled(sctp_tag); ti_ui_->ppiLabel->setEnabled(sctp_ppi); ti_ui_->ppiLineEdit->setEnabled(sctp_ppi); } int ImportTextDialog::exec() { QVariant encap_val; QDialog::exec(); if (result() != QDialog::Accepted) { return result(); } import_info_.import_text_filename = qstring_strdup(ti_ui_->textFileLineEdit->text()); import_info_.import_text_file = ws_fopen(import_info_.import_text_filename, "rb"); if (!import_info_.import_text_file) { open_failure_alert_box(import_info_.import_text_filename, errno, FALSE); setResult(QDialog::Rejected); return QDialog::Rejected; } import_info_.offset_type = ti_ui_->hexOffsetButton->isChecked() ? OFFSET_HEX : ti_ui_->decimalOffsetButton->isChecked() ? OFFSET_DEC : ti_ui_->octalOffsetButton->isChecked() ? OFFSET_OCT : OFFSET_NONE; import_info_.date_timestamp = ti_ui_->dateTimeLineEdit->text().length() > 0; import_info_.date_timestamp_format = qstring_strdup(ti_ui_->dateTimeLineEdit->text()); encap_val = ti_ui_->encapComboBox->itemData(ti_ui_->encapComboBox->currentIndex()); import_info_.dummy_header_type = HEADER_NONE; if (encap_val.isValid() && encap_val.toUInt() == WTAP_ENCAP_ETHERNET && !ti_ui_->noDummyButton->isChecked()) { // Inputs were validated in the on_xxx_textChanged slots. if (ti_ui_->ethernetButton->isChecked()) { import_info_.dummy_header_type = HEADER_ETH; } else if (ti_ui_->ipv4Button->isChecked()) { import_info_.dummy_header_type = HEADER_IPV4; } else if(ti_ui_->udpButton->isChecked()) { import_info_.dummy_header_type = HEADER_UDP; } else if(ti_ui_->tcpButton->isChecked()) { import_info_.dummy_header_type = HEADER_TCP; } else if(ti_ui_->sctpButton->isChecked()) { import_info_.dummy_header_type = HEADER_SCTP; } else if(ti_ui_->sctpDataButton->isChecked()) { import_info_.dummy_header_type = HEADER_SCTP_DATA; } } if (import_info_.max_frame_length == 0) { import_info_.max_frame_length = IMPORT_MAX_PACKET; } convertTextFile(); return QDialog::Accepted; } void ImportTextDialog::on_textFileBrowseButton_clicked() { char *open_dir = NULL; switch (prefs.gui_fileopen_style) { case FO_STYLE_LAST_OPENED: /* The user has specified that we should start out in the last directory we looked in. If we've already opened a file, use its containing directory, if we could determine it, as the directory, otherwise use the "last opened" directory saved in the preferences file if there was one. */ /* This is now the default behaviour in file_selection_new() */ open_dir = get_last_open_dir(); break; case FO_STYLE_SPECIFIED: /* The user has specified that we should always start out in a specified directory; if they've specified that directory, start out by showing the files in that dir. */ if (prefs.gui_fileopen_dir[0] != '\0') open_dir = prefs.gui_fileopen_dir; break; } QString file_name = QFileDialog::getOpenFileName(this, wsApp->windowTitleString(tr("Import Text File")), open_dir); ti_ui_->textFileLineEdit->setText(file_name); } void ImportTextDialog::updateImportButtonState() { if (file_ok_ && time_format_ok_ && ether_type_ok_ && proto_ok_ && source_port_ok_ && dest_port_ok_ && tag_ok_ && ppi_ok_ && max_len_ok_) { import_button_->setEnabled(true); } else { import_button_->setEnabled(false); } } void ImportTextDialog::on_textFileLineEdit_textChanged(const QString &file_name) { QFile *text_file; text_file = new QFile(file_name); if (text_file->open(QIODevice::ReadOnly)) { file_ok_ = true; text_file->close(); } else { file_ok_ = false; } updateImportButtonState(); } void ImportTextDialog::on_encapComboBox_currentIndexChanged(int index) { QVariant val = ti_ui_->encapComboBox->itemData(index); bool enabled = false; if (val != QVariant::Invalid) { import_info_.encapsulation = val.toUInt(); if (import_info_.encapsulation == WTAP_ENCAP_ETHERNET) enabled = true; } enableHeaderWidgets(enabled); } bool ImportTextDialog::checkDateTimeFormat(const QString &time_format) { const QString valid_code = "aAbBcdHIjmMpSUwWxXyYzZ%"; int idx = 0; while ((idx = time_format.indexOf("%", idx)) != -1) { idx++; if ((idx == time_format.size()) || !valid_code.contains(time_format[idx])) { return false; } idx++; } return true; } void ImportTextDialog::on_dateTimeLineEdit_textChanged(const QString &time_format) { if (time_format.length() > 0) { if (checkDateTimeFormat(time_format)) { time_t cur_time; struct tm *cur_tm; char time_str[100]; time(&cur_time); cur_tm = localtime(&cur_time); if (cur_tm != NULL) strftime(time_str, sizeof time_str, ti_ui_->dateTimeLineEdit->text().toUtf8().constData(), cur_tm); else g_strlcpy(time_str, "Not representable", sizeof time_str); ti_ui_->timestampExampleLabel->setText(QString(tr("Example: %1")).arg(time_str)); time_format_ok_ = true; } else { ti_ui_->timestampExampleLabel->setText(tr("<i>(Wrong date format)</i>")); time_format_ok_ = false; } } else { ti_ui_->timestampExampleLabel->setText(tr("<i>(No format will be applied)</i>")); time_format_ok_ = true; } updateImportButtonState(); } void ImportTextDialog::on_directionIndicationCheckBox_toggled(bool checked) { import_info_.has_direction = checked; } void ImportTextDialog::on_noDummyButton_toggled(bool checked) { if (checked) enableHeaderWidgets(); } void ImportTextDialog::on_ethernetButton_toggled(bool checked) { on_noDummyButton_toggled(checked); } void ImportTextDialog::on_ipv4Button_toggled(bool checked) { on_noDummyButton_toggled(checked); } void ImportTextDialog::on_udpButton_toggled(bool checked) { on_noDummyButton_toggled(checked); } void ImportTextDialog::on_tcpButton_toggled(bool checked) { on_noDummyButton_toggled(checked); } void ImportTextDialog::on_sctpButton_toggled(bool checked) { on_noDummyButton_toggled(checked); } void ImportTextDialog::on_sctpDataButton_toggled(bool checked) { on_noDummyButton_toggled(checked); } void ImportTextDialog::check_line_edit(SyntaxLineEdit *le, bool &ok_enabled, const QString &num_str, int base, guint max_val, bool is_short, guint *val_ptr) { bool conv_ok; SyntaxLineEdit::SyntaxState syntax_state = SyntaxLineEdit::Empty; if (!le || !val_ptr) return; ok_enabled = true; if (num_str.length() < 1) { *val_ptr = 0; } else { if (is_short) { *val_ptr = num_str.toUShort(&conv_ok, base); } else { *val_ptr = num_str.toULong(&conv_ok, base); } if (conv_ok && *val_ptr <= max_val) { syntax_state = SyntaxLineEdit::Valid; } else { syntax_state = SyntaxLineEdit::Invalid; ok_enabled = false; } } le->setSyntaxState(syntax_state); updateImportButtonState(); } void ImportTextDialog::on_ethertypeLineEdit_textChanged(const QString &ethertype_str) { check_line_edit(ti_ui_->ethertypeLineEdit, ether_type_ok_, ethertype_str, 16, 0xffff, true, &import_info_.pid); } void ImportTextDialog::on_protocolLineEdit_textChanged(const QString &protocol_str) { check_line_edit(ti_ui_->protocolLineEdit, proto_ok_, protocol_str, 10, 0xff, true, &import_info_.protocol); } void ImportTextDialog::on_sourcePortLineEdit_textChanged(const QString &source_port_str) { check_line_edit(ti_ui_->sourcePortLineEdit, source_port_ok_, source_port_str, 10, 0xffff, true, &import_info_.src_port); } void ImportTextDialog::on_destinationPortLineEdit_textChanged(const QString &destination_port_str) { check_line_edit(ti_ui_->destinationPortLineEdit, dest_port_ok_, destination_port_str, 10, 0xffff, true, &import_info_.dst_port); } void ImportTextDialog::on_tagLineEdit_textChanged(const QString &tag_str) { check_line_edit(ti_ui_->tagLineEdit, tag_ok_, tag_str, 10, 0xffffffff, false, &import_info_.tag); } void ImportTextDialog::on_ppiLineEdit_textChanged(const QString &ppi_str) { check_line_edit(ti_ui_->ppiLineEdit, ppi_ok_, ppi_str, 10, 0xffffffff, false, &import_info_.ppi); } void ImportTextDialog::on_maxLengthLineEdit_textChanged(const QString &max_frame_len_str) { check_line_edit(ti_ui_->maxLengthLineEdit, max_len_ok_, max_frame_len_str, 10, IMPORT_MAX_PACKET, true, &import_info_.max_frame_length); } void ImportTextDialog::on_buttonBox_helpRequested() { wsApp->helpTopicAction(HELP_IMPORT_DIALOG); } /* * Editor modelines * * Local Variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * ex: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
33.241935
168
0.689774
[ "model" ]
c6effb331abcdd5e85e54eb729e32aa0432911df
9,072
cxx
C++
main/connectivity/source/drivers/file/FStringFunctions.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/connectivity/source/drivers/file/FStringFunctions.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/connectivity/source/drivers/file/FStringFunctions.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "file/FStringFunctions.hxx" #include <rtl/ustrbuf.hxx> #include <rtl/logfile.hxx> using namespace connectivity; using namespace connectivity::file; //------------------------------------------------------------------ ORowSetValue OOp_Upper::operate(const ORowSetValue& lhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_Upper::operate" ); if ( lhs.isNull() ) return lhs; return lhs.getString().toAsciiUpperCase(); } //------------------------------------------------------------------ ORowSetValue OOp_Lower::operate(const ORowSetValue& lhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_Lower::operate" ); if ( lhs.isNull() ) return lhs; return lhs.getString().toAsciiLowerCase(); } //------------------------------------------------------------------ ORowSetValue OOp_Ascii::operate(const ORowSetValue& lhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_Ascii::operate" ); if ( lhs.isNull() ) return lhs; ::rtl::OString sStr(::rtl::OUStringToOString(lhs,RTL_TEXTENCODING_ASCII_US)); sal_Int32 nAscii = sStr.toChar(); return nAscii; } //------------------------------------------------------------------ ORowSetValue OOp_CharLength::operate(const ORowSetValue& lhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_CharLength::operate" ); if ( lhs.isNull() ) return lhs; return lhs.getString().getLength(); } //------------------------------------------------------------------ ORowSetValue OOp_Char::operate(const ::std::vector<ORowSetValue>& lhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_Char::operate" ); if ( lhs.empty() ) return ORowSetValue(); ::rtl::OUString sRet; ::std::vector<ORowSetValue>::const_reverse_iterator aIter = lhs.rbegin(); ::std::vector<ORowSetValue>::const_reverse_iterator aEnd = lhs.rend(); for (; aIter != aEnd; ++aIter) { if ( !aIter->isNull() ) { sal_Char c = static_cast<sal_Char>(static_cast<sal_Int32>(*aIter)); sRet += ::rtl::OUString(&c,1,RTL_TEXTENCODING_ASCII_US); } } return sRet; } //------------------------------------------------------------------ ORowSetValue OOp_Concat::operate(const ::std::vector<ORowSetValue>& lhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_Concat::operate" ); if ( lhs.empty() ) return ORowSetValue(); ::rtl::OUStringBuffer sRet; ::std::vector<ORowSetValue>::const_reverse_iterator aIter = lhs.rbegin(); ::std::vector<ORowSetValue>::const_reverse_iterator aEnd = lhs.rend(); for (; aIter != aEnd; ++aIter) { if ( aIter->isNull() ) return ORowSetValue(); sRet.append(aIter->operator ::rtl::OUString()); } return sRet.makeStringAndClear(); } //------------------------------------------------------------------ ORowSetValue OOp_Locate::operate(const ::std::vector<ORowSetValue>& lhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_Locate::operate" ); ::std::vector<ORowSetValue>::const_iterator aIter = lhs.begin(); ::std::vector<ORowSetValue>::const_iterator aEnd = lhs.end(); for (; aIter != aEnd; ++aIter) { if ( aIter->isNull() ) return ORowSetValue(); } if ( lhs.size() == 2 ) return ::rtl::OUString::valueOf(lhs[0].getString().indexOf(lhs[1].getString())+1); else if ( lhs.size() != 3 ) return ORowSetValue(); return lhs[1].getString().indexOf(lhs[2].getString(),lhs[0]) + 1; } //------------------------------------------------------------------ ORowSetValue OOp_SubString::operate(const ::std::vector<ORowSetValue>& lhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_SubString::operate" ); ::std::vector<ORowSetValue>::const_iterator aIter = lhs.begin(); ::std::vector<ORowSetValue>::const_iterator aEnd = lhs.end(); for (; aIter != aEnd; ++aIter) { if ( aIter->isNull() ) return ORowSetValue(); } if ( lhs.size() == 2 && static_cast<sal_Int32>(lhs[0]) >= sal_Int32(0) ) return lhs[1].getString().copy(static_cast<sal_Int32>(lhs[0])-1); else if ( lhs.size() != 3 || static_cast<sal_Int32>(lhs[1]) < sal_Int32(0)) return ORowSetValue(); return lhs[2].getString().copy(static_cast<sal_Int32>(lhs[1])-1,lhs[0]); } //------------------------------------------------------------------ ORowSetValue OOp_LTrim::operate(const ORowSetValue& lhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_LTrim::operate" ); if ( lhs.isNull() ) return lhs; ::rtl::OUString sRet = lhs; ::rtl::OUString sNew = sRet.trim(); return sRet.copy(sRet.indexOf(sNew)); } //------------------------------------------------------------------ ORowSetValue OOp_RTrim::operate(const ORowSetValue& lhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_RTrim::operate" ); if ( lhs.isNull() ) return lhs; ::rtl::OUString sRet = lhs; ::rtl::OUString sNew = sRet.trim(); return sRet.copy(0,sRet.lastIndexOf(sNew.getStr()[sNew.getLength()-1])+1); } //------------------------------------------------------------------ ORowSetValue OOp_Space::operate(const ORowSetValue& lhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_Space::operate" ); if ( lhs.isNull() ) return lhs; const sal_Char c = ' '; ::rtl::OUStringBuffer sRet; sal_Int32 nCount = lhs; for (sal_Int32 i=0; i < nCount; ++i) { sRet.appendAscii(&c,1); } return sRet.makeStringAndClear(); } //------------------------------------------------------------------ ORowSetValue OOp_Replace::operate(const ::std::vector<ORowSetValue>& lhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_Replace::operate" ); if ( lhs.size() != 3 ) return ORowSetValue(); ::rtl::OUString sStr = lhs[2]; ::rtl::OUString sFrom = lhs[1]; ::rtl::OUString sTo = lhs[0]; sal_Int32 nIndexOf = sStr.indexOf(sFrom); while( nIndexOf != -1 ) { sStr = sStr.replaceAt(nIndexOf,sFrom.getLength(),sTo); nIndexOf = sStr.indexOf(sFrom,nIndexOf + sTo.getLength()); } return sStr; } //------------------------------------------------------------------ ORowSetValue OOp_Repeat::operate(const ORowSetValue& lhs,const ORowSetValue& rhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_Repeat::operate" ); if ( lhs.isNull() || rhs.isNull() ) return lhs; ::rtl::OUString sRet; sal_Int32 nCount = rhs; for (sal_Int32 i=0; i < nCount; ++i) { sRet += lhs; } return sRet; } //------------------------------------------------------------------ ORowSetValue OOp_Insert::operate(const ::std::vector<ORowSetValue>& lhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_Insert::operate" ); if ( lhs.size() != 4 ) return ORowSetValue(); ::rtl::OUString sStr = lhs[3]; sal_Int32 nStart = static_cast<sal_Int32>(lhs[2]); if ( nStart < 1 ) nStart = 1; return sStr.replaceAt(nStart-1,static_cast<sal_Int32>(lhs[1]),lhs[0]); } //------------------------------------------------------------------ ORowSetValue OOp_Left::operate(const ORowSetValue& lhs,const ORowSetValue& rhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_Left::operate" ); if ( lhs.isNull() || rhs.isNull() ) return lhs; ::rtl::OUString sRet = lhs; sal_Int32 nCount = rhs; if ( nCount < 0 ) return ORowSetValue(); return sRet.copy(0,nCount); } //------------------------------------------------------------------ ORowSetValue OOp_Right::operate(const ORowSetValue& lhs,const ORowSetValue& rhs) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OOp_Right::operate" ); if ( lhs.isNull() || rhs.isNull() ) return lhs; sal_Int32 nCount = rhs; ::rtl::OUString sRet = lhs; if ( nCount < 0 || nCount >= sRet.getLength() ) return ORowSetValue(); return sRet.copy(sRet.getLength()-nCount,nCount); }
34.363636
101
0.6056
[ "vector" ]
c6f8388de8831f7e5de7550cac385d367998d1a7
7,035
cpp
C++
example/oglplus/glut_main.cpp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
example/oglplus/glut_main.cpp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
example/oglplus/glut_main.cpp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
/* * .file example/oglplus/glut_main.cpp * Implements GLUT-based program main function for running examples * * Copyright 2008-2015 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include <oglplus/gl.hpp> #include <oglplus/config/fix_gl_version.hpp> #include <oglplus/config/fix_gl_extension.hpp> #if OGLPLUS_FREEGLUT_FOUND # include <GL/freeglut.h> #elif defined(__APPLE__) && __APPLE__ # include <GLUT/glut.h> #else # include <GL/glut.h> #endif #include <cstddef> #include <cstring> #include <cassert> #include <fstream> #include <iostream> #include <iomanip> #include <vector> #include <oglplus/error/basic.hpp> #include <oglplus/query.hpp> #include <oglplus/os/steady_clock.hpp> #include "example.hpp" #include "example_main.hpp" namespace oglplus { class SingleExample { private: static SingleExample*& SingleInstance(void) { static SingleExample* wrapper = nullptr; return wrapper; } os::steady_clock _os_clock; ExampleClock _clock; double _fps_time, _prim_count; unsigned long _frame_no; GLuint _width, _height; std::unique_ptr<Example> _example; std::unique_ptr<Query> _primitive_query; const char* _screenshot_path; SingleExample(const SingleExample&); public: Example* operator ->(void) { assert(SingleInstance()); return SingleInstance()->_example.get(); } SingleExample( GLuint width, GLuint height, const ExampleParams& params, const char* screenshot_path ): _fps_time(0.0) , _prim_count(0.0) , _frame_no(0) , _width(width) , _height(height) , _example(makeExample(params)) , _primitive_query(new Query()) , _screenshot_path(screenshot_path) { assert(!SingleInstance()); SingleInstance() = this; assert(_example); _example->Reshape(width, height); _example->MouseMove(width/2, height/2, width, height); _os_clock.reset(); if(_screenshot_path) _clock.Update(_example->HeatUpTime()); } ~SingleExample(void) { assert(SingleInstance()); SingleInstance() = nullptr; } void Quit(void) { #if OGLPLUS_FREEGLUT_FOUND glutLeaveMainLoop(); #else exit(0); #endif } void Close(void) { _primitive_query.reset(); _example.reset(); } static void CloseFunc(void) { assert(SingleInstance()); SingleInstance()->Close(); } void Display(void) { _clock.Update(ExampleTimePeriod::Seconds(_os_clock.seconds())); double frame_time = _clock.Now().Seconds(); _frame_no++; GLuint primitives_per_frame = 0; if(_primitive_query) { try { auto query_exec = _primitive_query->Execute( Query::Target::PrimitivesGenerated, primitives_per_frame ); _example->Render(_clock); glutSwapBuffers(); } catch(Error&) { _primitive_query.reset(); } } else { _example->Render(_clock); glutSwapBuffers(); } _prim_count += double(primitives_per_frame); const double fps_interval = 10.0; const double this_interval = frame_time - _fps_time; if(this_interval >= fps_interval) { _fps_time = frame_time; std::cout.width(5); std::cout.precision(3); std::cout << _frame_no << " frames in " << std::fixed << this_interval << " seconds = " << std::fixed << _frame_no/this_interval << " FPS; " << std::scientific << _prim_count/this_interval << " PPS; " << std::scientific << _prim_count/_frame_no << " PPF; " << std::endl; _frame_no = 0; _prim_count = 0.0; } if(!_example->Continue(_clock)) { Quit(); } } static void DisplayFunc(void) { assert(SingleInstance()); SingleInstance()->Display(); } void Screenshot(void) { _example->Render(_clock); if(_clock.Now() >= _example->ScreenshotTime()) { glFinish(); std::vector<char> pixels(_width * _height * 3); glReadPixels( 0, 0, _width, _height, GL_RGB, GL_UNSIGNED_BYTE, pixels.data() ); std::ofstream output(_screenshot_path); output.write(pixels.data(), pixels.size()); Quit(); } glutSwapBuffers(); _clock.Advance(_example->FrameTime()); } static void ScreenshotFunc(void) { assert(SingleInstance()); SingleInstance()->Screenshot(); } void Reshape(int width, int height) { _width = width; _height= height; _example->Reshape(width, height); } static void ReshapeFunc(int width, int height) { assert(SingleInstance()); SingleInstance()->Reshape(width, height); } void Motion(int x, int y) { _example->MouseMove(x, _height-y, _width, _height); } static void MotionFunc(int x, int y) { assert(SingleInstance()); SingleInstance()->Motion(x, y); } void KeyPress(unsigned char /*k*/) { // TODO } static void KeyboardFunc(unsigned char k, int, int) { if(k == 0x1B) // Escape { assert(SingleInstance()); SingleInstance()->Quit(); } else { assert(SingleInstance()); SingleInstance()->KeyPress(k); } } }; } // namespace oglplus int glut_example_main(int argc, char ** argv) { GLuint width = 800, height = 600; glutInit(&argc, argv); glutInitDisplayMode( #if defined(__APPLE__) && __APPLE__ GLUT_3_2_CORE_PROFILE | #endif GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL ); #if OGLPLUS_FREEGLUT_FOUND glutInitContextVersion( OGLPLUS_GL_VERSION_MAJOR, OGLPLUS_GL_VERSION_MINOR ); #endif glutInitWindowSize(width, height); glutInitWindowPosition(100,100); glutCreateWindow("OGLplus example"); const char* screenshot_path = nullptr; for(int a=1; a!=argc;) { int aoffs = 0; if(std::strcmp(argv[a], "--fullscreen") == 0) { glutFullScreen(); aoffs = 1; } if(std::strcmp(argv[a], "--screenshot") == 0) { if((a+1) < argc) { screenshot_path = argv[a+1]; aoffs = 2; } else { screenshot_path = "screenshot.rgb"; aoffs = 1; } } if(aoffs > 0) { for(int ao=a+aoffs; ao!=argc; ++ao) { argv[ao-aoffs] = argv[ao]; } argc -= aoffs; } else ++a; } oglplus::GLAPIInitializer api_init; // The parameters for this example oglplus::ExampleParams params(argc, argv); setupExample(params); params.Check(); using oglplus::SingleExample; // The main window/rendering context if(screenshot_path) { glutDisplayFunc(&SingleExample::ScreenshotFunc); glutIdleFunc(&SingleExample::ScreenshotFunc); } else { glutDisplayFunc(&SingleExample::DisplayFunc); glutIdleFunc(&SingleExample::DisplayFunc); } glutReshapeFunc(&SingleExample::ReshapeFunc); glutMotionFunc(&SingleExample::MotionFunc); glutPassiveMotionFunc(&SingleExample::MotionFunc); glutKeyboardFunc(&SingleExample::KeyboardFunc); #if OGLPLUS_FREEGLUT_FOUND glutSetOption( GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS ); glutCloseFunc(&SingleExample::CloseFunc); #endif // create the example SingleExample example(width, height, params, screenshot_path); // start the example main loop glutMainLoop(); return 0; } int main(int argc, char* argv[]) { return oglplus::example_main(glut_example_main, argc, argv); }
19.487535
68
0.687136
[ "render", "vector" ]
c6fd15a63532b87687395fffb230d53c6d968ad9
947
cpp
C++
oi/joi/2018/b.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
oi/joi/2018/b.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
oi/joi/2018/b.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll=long long; // by a sort, note if fix l,r, mid obvious take all // split, consider one end contribution, e.g. left, ai+bi + ..+ b +.. void solve() { int n; cin >> n; vector<pair<ll,ll>> c(n); vector<ll> a(n), b(n); for (int i = 0; i < n; i++) { cin >> c[i].first >> c[i].second; } sort(c.begin(), c.end()); for (int i = 0; i < n; i++) { tie(a[i],b[i]) = c[i]; } ll res = *max_element(b.begin(), b.end()); vector<ll> pref(n); pref[0] = a[0] + b[0]; for (int i = 1; i < n; i++) { pref[i] = max(pref[i-1] + b[i], a[i] + b[i]); } ll suff = -a[n-1] + b[n-1]; for (int i = n-2; i >= 0; i--) { res = max(res, pref[i] + suff); suff = max(suff + b[i], -a[i] + b[i]); } cout << res << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
24.282051
69
0.460401
[ "vector" ]
c6ff17ad184d524c32252f8ab0724ec5957b4ba4
9,819
cc
C++
mindspore/ccsrc/utils/convert_utils.cc
dongkcs/mindspore
cd7df6dbf463ff3128e9181e9d0c779cecb81320
[ "Apache-2.0" ]
2
2020-11-23T13:46:37.000Z
2020-12-20T02:02:38.000Z
mindspore/ccsrc/utils/convert_utils.cc
dongkcs/mindspore
cd7df6dbf463ff3128e9181e9d0c779cecb81320
[ "Apache-2.0" ]
1
2020-12-29T06:46:38.000Z
2020-12-29T06:46:38.000Z
mindspore/ccsrc/utils/convert_utils.cc
dongkcs/mindspore
cd7df6dbf463ff3128e9181e9d0c779cecb81320
[ "Apache-2.0" ]
1
2021-05-10T03:30:36.000Z
2021-05-10T03:30:36.000Z
/** * Copyright 2019-2020 Huawei Technologies 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 "utils/convert_utils.h" #include <vector> #include <string> #include <memory> #include <algorithm> #include <list> #include <utility> #include <cfloat> #include "abstract/abstract_value.h" #include "ir/value.h" #include "ir/tensor.h" #include "ir/param_info.h" #include "utils/ms_context.h" #include "utils/shape_utils.h" namespace mindspore { bool ValueToBool(const ValuePtr &v, bool *value) { MS_EXCEPTION_IF_NULL(v); if (v->isa<BoolImm>()) { *value = v->cast<BoolImmPtr>()->value(); } else if (v->isa<Int32Imm>()) { *value = v->cast<Int32ImmPtr>()->value() == 0 ? false : true; } else if (v->isa<UInt32Imm>()) { *value = v->cast<UInt32ImmPtr>()->value() == 0 ? false : true; } else if (v->isa<FP32Imm>()) { *value = v->cast<FP32ImmPtr>()->value() == 0 ? false : true; } else if (v->isa<FP64Imm>()) { *value = v->cast<FP64ImmPtr>()->value() == 0 ? false : true; } else if (v->isa<tensor::Tensor>()) { auto tensor = v->cast<tensor::TensorPtr>(); MS_EXCEPTION_IF_NULL(tensor); (void)tensor->data_sync(); bool *tensor_data = static_cast<bool *>(tensor->data_c()); // maybe need to support if tensor is a bool array auto vb = tensor_data[0]; *value = vb; } else { MS_LOG(WARNING) << "value is not supported to cast to be bool"; return false; } return true; } bool BaseRefToInt(const ValuePtr &v, int *value) { MS_EXCEPTION_IF_NULL(v); if (v->isa<tensor::Tensor>()) { auto tensor = v->cast<tensor::TensorPtr>(); (void)tensor->data_sync(); int *tensor_data = static_cast<int *>(tensor->data_c()); auto vb = tensor_data[0]; *value = vb; return true; } MS_LOG(ERROR) << "Index must be tensor type."; return false; } bool BaseRefToBool(const BaseRef &v, bool *value) { if (utils::isa<ValuePtr>(v)) { return ValueToBool(utils::cast<ValuePtr>(v), value); } else if (utils::isa<bool>(v)) { auto vb = utils::cast<bool>(v); if (vb == true) { *value = true; } else { *value = false; } } else if (utils::isa<int>(v)) { auto vb = utils::cast<int>(v); if (vb == 0) { *value = false; } else { *value = true; } } else if (utils::isa<unsigned int>(v)) { auto vb = utils::cast<unsigned int>(v); if (vb == 0) { *value = false; } else { *value = true; } } else if (utils::isa<float>(v)) { auto vb = utils::cast<float>(v); if (vb >= -FLT_EPSILON && vb <= FLT_EPSILON) { *value = false; } else { *value = true; } } else if (utils::isa<double>(v)) { auto vb = utils::cast<double>(v); if (vb >= -DBL_EPSILON && vb <= DBL_EPSILON) { *value = false; } else { *value = true; } } else { MS_LOG(DEBUG) << "value is not supported to cast to be bool"; return false; } return true; } namespace { // Isomorphism bool SameNode(const AnfNodePtr &node1, const AnfNodePtr &node2, FuncGraphPairMapEquiv *equiv_func_graph, NodeMapEquiv *const equiv_node); bool SameNodeShallow(const AnfNodePtr &node1, const AnfNodePtr &node2, FuncGraphPairMapEquiv *equiv_func_graph, NodeMapEquiv *const equiv_node) { if (equiv_node == nullptr) { MS_LOG(ERROR) << "Invalid equiv_node"; return false; } if (equiv_node->count(node1) > 0 && (*equiv_node)[node1] == node2) { return true; } if (IsValueNode<FuncGraph>(node1) && IsValueNode<FuncGraph>(node2)) { return Isomorphic(GetValueNode<FuncGraphPtr>(node1), GetValueNode<FuncGraphPtr>(node2), equiv_func_graph, equiv_node); } if (node1->isa<ValueNode>() && node2->isa<ValueNode>()) { auto a1 = GetValueNode(node1); auto a2 = GetValueNode(node2); if (a1->isa<Primitive>() && a2->isa<Primitive>()) { return a1->cast<PrimitivePtr>()->name() == a2->cast<PrimitivePtr>()->name(); } else if (a1->isa<tensor::Tensor>() && a2->isa<tensor::Tensor>()) { return a1->cast<tensor::TensorPtr>()->ValueEqual(*(a2->cast<tensor::TensorPtr>())); } else { return *a1 == *a2; } } if (node1->isa<Parameter>() && node2->isa<Parameter>()) { auto para1 = node1->cast<ParameterPtr>(); auto para2 = node2->cast<ParameterPtr>(); if (para1->name() == para2->name()) { return true; } MS_LOG(DEBUG) << "two parameters are not equal."; return false; } if (node1->isa<CNode>() && node2->isa<CNode>()) { return SameNode(node1, node2, equiv_func_graph, equiv_node); } MS_LOG(ERROR) << "type error"; return false; } bool SameNode(const AnfNodePtr &node1, const AnfNodePtr &node2, FuncGraphPairMapEquiv *equiv_func_graph, NodeMapEquiv *const equiv_node) { MS_EXCEPTION_IF_NULL(node1); MS_EXCEPTION_IF_NULL(node2); if (node1->isa<CNode>() && node2->isa<CNode>()) { auto &inputs1 = node1->cast<CNodePtr>()->inputs(); auto &inputs2 = node2->cast<CNodePtr>()->inputs(); for (std::size_t i = 0; i < inputs1.size(); ++i) { if (!SameNodeShallow(inputs1[i], inputs2[i], equiv_func_graph, equiv_node)) { return false; } } return true; } return SameNodeShallow(node1, node2, equiv_func_graph, equiv_node); } bool SameSubgraph(AnfNodePtr root1, AnfNodePtr root2, FuncGraphPairMapEquiv *equiv_func_graph, NodeMapEquiv *const equiv_node) { std::unordered_set<AnfNodePtr> done; std::stack<std::pair<AnfNodePtr, AnfNodePtr>> todo; todo.push(std::make_pair(root1, root2)); while (todo.size() > 0) { AnfNodePtr node1 = todo.top().first; if (done.count(node1) > 0) { todo.pop(); continue; } AnfNodePtr node2 = todo.top().second; bool condition = false; std::vector<AnfNodePtr> s1 = SuccIncoming(node1); std::vector<AnfNodePtr> s2 = SuccIncoming(node2); if (s1.size() != s2.size()) { return false; } for (std::size_t i = 0; i < s1.size(); ++i) { if (done.count(s1[i]) == 0) { todo.push(std::make_pair(s1[i], s2[i])); condition = true; } } if (condition) { continue; } (void)done.insert(node1); auto res = SameNode(node1, node2, equiv_func_graph, equiv_node); if (res) { (*equiv_node)[node1] = node2; } else { return false; } todo.pop(); } return true; } } // namespace bool Isomorphic(FuncGraphPtr fg1, FuncGraphPtr fg2, FuncGraphPairMapEquiv *equiv_func_graph, NodeMapEquiv *const equiv_node) { auto fg1_fg2 = std::make_pair(fg1, fg2); if (equiv_func_graph == nullptr) { MS_LOG(ERROR) << "equiv_func_graph not init"; return false; } if (equiv_func_graph->find(fg1_fg2) != equiv_func_graph->end()) { return (*equiv_func_graph)[fg1_fg2] != kNotEquiv; } if (fg1 == nullptr || fg2 == nullptr) { MS_LOG(ERROR) << "Invalid function graph"; return false; } if (fg1->parameters().size() != fg2->parameters().size()) { MS_LOG(DEBUG) << "parameters size not match"; return false; } if (equiv_node != nullptr) { for (std::size_t i = 0; i < fg1->parameters().size(); ++i) { (*equiv_node)[fg1->parameters()[i]] = fg2->parameters()[i]; } (*equiv_func_graph)[fg1_fg2] = kPending; auto result = SameSubgraph(fg1->get_return(), fg2->get_return(), equiv_func_graph, equiv_node); (*equiv_func_graph)[fg1_fg2] = EquivState(result); return result; } MS_LOG(ERROR) << "equiv_node not init"; return false; } tensor::TensorPtr ScalarToTensor(const ScalarPtr &scalar) { if (scalar == nullptr) { MS_EXCEPTION(ArgumentError) << "Nullptr Error!"; } tensor::TensorPtr tensor = nullptr; if (scalar->isa<FloatImm>()) { tensor = std::make_shared<tensor::Tensor>(static_cast<double>(GetValue<float>(scalar)), kFloat32); } else if (scalar->isa<Int32Imm>()) { tensor = std::make_shared<tensor::Tensor>(static_cast<int64_t>(GetValue<int>(scalar)), kInt32); } else if (scalar->isa<Int64Imm>()) { tensor = std::make_shared<tensor::Tensor>(GetValue<int64_t>(scalar), kInt64); } else if (scalar->isa<BoolImm>()) { const int64_t bool_value = GetValue<bool>(scalar) ? 1 : 0; tensor = std::make_shared<tensor::Tensor>(bool_value, kBool); } else { auto type = scalar->type(); auto type_str = (type == nullptr) ? "nullptr" : type->ToString(); MS_LOG(EXCEPTION) << "Invalid scalar type: " << type_str; } MS_EXCEPTION_IF_NULL(tensor); return tensor; } void TensorValueToTensor(const ValuePtr &value, std::vector<tensor::TensorPtr> *tensors) { MS_EXCEPTION_IF_NULL(value); MS_EXCEPTION_IF_NULL(tensors); if (value->isa<ValueTuple>()) { auto value_tuple = value->cast<ValueTuplePtr>(); MS_EXCEPTION_IF_NULL(value_tuple); for (size_t i = 0; i < value_tuple->size(); ++i) { ValuePtr element = value_tuple->value()[i]; if (element->isa<tensor::Tensor>()) { auto tensor = element->cast<tensor::TensorPtr>(); MS_EXCEPTION_IF_NULL(tensor); tensors->push_back(tensor); } } } else if (value->isa<tensor::Tensor>()) { tensor::TensorPtr tensor = value->cast<tensor::TensorPtr>(); MS_EXCEPTION_IF_NULL(tensor); tensors->push_back(tensor); } } } // namespace mindspore
32.513245
111
0.628883
[ "vector" ]
c6ffc5e8a7e1e9f01acba6b222cb6a10f5c8e5c0
4,339
hpp
C++
amgcl/relaxation/damped_jacobi.hpp
tkoziara/parmec
fefe0586798cd65744334f9abeab183159bd3d7a
[ "MIT" ]
null
null
null
amgcl/relaxation/damped_jacobi.hpp
tkoziara/parmec
fefe0586798cd65744334f9abeab183159bd3d7a
[ "MIT" ]
15
2017-06-09T12:05:27.000Z
2018-10-25T13:59:58.000Z
amgcl/relaxation/damped_jacobi.hpp
parmes/parmec
fefe0586798cd65744334f9abeab183159bd3d7a
[ "MIT" ]
null
null
null
#ifndef AMGCL_RELAXATION_DAMPED_JACOBI_HPP #define AMGCL_RELAXATION_DAMPED_JACOBI_HPP /* The MIT License Copyright (c) 2012-2018 Denis Demidov <dennis.demidov@gmail.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. */ /** * \file amgcl/relaxation/damped_jacobi.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief Damped Jacobi relaxation scheme. */ #include <memory> #include <amgcl/backend/interface.hpp> #include <amgcl/util.hpp> namespace amgcl { /// Smoothers namespace relaxation { /** * \defgroup relaxation * \brief Relaxation schemes */ /// Damped Jacobi relaxation. /** * \param Backend Backend for temporary structures allocation. * \ingroup relaxation */ template <class Backend> struct damped_jacobi { typedef typename Backend::value_type value_type; typedef typename math::scalar_of<value_type>::type scalar_type; /// Relaxation parameters. struct params { /// Damping factor. scalar_type damping; params(scalar_type damping = 0.72) : damping(damping) {} #ifdef BOOST_VERSION params(const boost::property_tree::ptree &p) : AMGCL_PARAMS_IMPORT_VALUE(p, damping) { check_params(p, {"damping"}); } void get(boost::property_tree::ptree &p, const std::string &path) const { AMGCL_PARAMS_EXPORT_VALUE(p, path, damping); } #endif } prm; std::shared_ptr<typename Backend::matrix_diagonal> dia; /// Constructs smoother for the system matrix. /** * \param A The system matrix. * \param prm Relaxation parameters. * \param backend_prm Backend parameters. */ template <class Matrix> damped_jacobi( const Matrix &A, const params &prm, const typename Backend::params &backend_prm ) : prm(prm), dia( Backend::copy_vector( diagonal(A, true), backend_prm ) ) { } /// Apply pre-relaxation /** * \param A System matrix. * \param rhs Right-hand side. * \param x Solution vector. * \param tmp Scratch vector. * \param prm Relaxation parameters. */ template <class Matrix, class VectorRHS, class VectorX, class VectorTMP> void apply_pre( const Matrix &A, const VectorRHS &rhs, VectorX &x, VectorTMP &tmp ) const { backend::residual(rhs, A, x, tmp); backend::vmul(prm.damping, *dia, tmp, math::identity<scalar_type>(), x); } /// Apply post-relaxation /** * \param A System matrix. * \param rhs Right-hand side. * \param x Solution vector. * \param tmp Scratch vector. * \param prm Relaxation parameters. */ template <class Matrix, class VectorRHS, class VectorX, class VectorTMP> void apply_post( const Matrix &A, const VectorRHS &rhs, VectorX &x, VectorTMP &tmp ) const { backend::residual(rhs, A, x, tmp); backend::vmul(prm.damping, *dia, tmp, math::identity<scalar_type>(), x); } template <class Matrix, class VectorRHS, class VectorX> void apply(const Matrix&, const VectorRHS &rhs, VectorX &x) const { backend::vmul(math::identity<scalar_type>(), *dia, rhs, math::zero<scalar_type>(), x); } }; } // namespace relaxation } // namespace amgcl #endif
30.992857
94
0.671122
[ "vector" ]
050dac111e85ce0428ecf6e477cc78e4ef0654ff
51,824
cc
C++
net/instaweb/rewriter/rewrite_query_test.cc
PeterDaveHello/incubator-pagespeed-mod
885f4653e204e1152cb3928f0755d93ec5fdceae
[ "Apache-2.0" ]
null
null
null
net/instaweb/rewriter/rewrite_query_test.cc
PeterDaveHello/incubator-pagespeed-mod
885f4653e204e1152cb3928f0755d93ec5fdceae
[ "Apache-2.0" ]
null
null
null
net/instaweb/rewriter/rewrite_query_test.cc
PeterDaveHello/incubator-pagespeed-mod
885f4653e204e1152cb3928f0755d93ec5fdceae
[ "Apache-2.0" ]
1
2020-05-20T07:09:05.000Z
2020-05-20T07:09:05.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. */ #include "net/instaweb/rewriter/public/rewrite_query.h" #include "base/logging.h" #include "net/instaweb/http/public/request_context.h" #include "net/instaweb/rewriter/public/rewrite_options.h" #include "net/instaweb/rewriter/public/rewrite_test_base.h" #include "net/instaweb/rewriter/public/test_rewrite_driver_factory.h" #include "pagespeed/kernel/base/google_message_handler.h" #include "pagespeed/kernel/base/gtest.h" #include "pagespeed/kernel/base/mock_message_handler.h" #include "pagespeed/kernel/base/ref_counted_ptr.h" #include "pagespeed/kernel/base/string_util.h" #include "pagespeed/kernel/html/html_parse_test_base.h" #include "pagespeed/kernel/http/google_url.h" #include "pagespeed/kernel/http/http_names.h" #include "pagespeed/kernel/http/response_headers.h" namespace net_instaweb { const char kHtmlUrl[] = "http://www.test.com/index.jsp"; class RewriteQueryTest : public RewriteTestBase { protected: virtual void SetUp() { RewriteTestBase::SetUp(); allow_related_options_ = false; allow_options_to_be_set_by_cookies_ = false; request_option_override_ = ""; image_url_ = Encode(kTestDomain, "ic", "0", "image.jpg", "jpg"); } const RewriteOptions* ParseAndScan(const StringPiece request_url, const StringPiece& in_query, const StringPiece& in_req_string) { return ParseAndScan(request_url, in_query, in_req_string, NULL, NULL); } // Parses query-params &/or HTTP headers. The HTTP headers are specified // as a string, with semi-colons separating attr:value pairs. const RewriteOptions* ParseAndScan(const StringPiece request_url, const StringPiece& in_query, const StringPiece& in_req_string, GoogleString* out_query, GoogleString* out_req_string) { GoogleString out_resp_string; RequestHeaders request_headers; StringPieceVector components; SplitStringPieceToVector(in_req_string, ";", &components, true); for (int i = 0, n = components.size(); i < n; ++i) { StringPieceVector attr_value; SplitStringPieceToVector(components[i], ":", &attr_value, false); CHECK_EQ(2, attr_value.size()); request_headers.Add(attr_value[0], attr_value[1]); } return ParseAndScan(request_url, in_query, StringPiece(), &request_headers, NULL, out_query, out_req_string, &out_resp_string); } const RewriteOptions* ParseAndScan(const StringPiece request_url, const StringPiece& in_query, const StringPiece& in_cookies, RequestHeaders* request_headers, ResponseHeaders* response_headers, GoogleString* out_query, GoogleString* out_req_string, GoogleString* out_resp_string) { Parse(request_url, in_query, in_cookies, request_headers, response_headers, out_query, out_req_string, out_resp_string); return rewrite_query_.options(); } RewriteQuery::Status Parse(const StringPiece request_url, const StringPiece& in_query, const StringPiece& in_cookies, RequestHeaders* request_headers, ResponseHeaders* response_headers, GoogleString* out_query, GoogleString* out_req_string, GoogleString* out_resp_string) { GoogleUrl url(StrCat(request_url, "?", in_query)); if (!in_cookies.empty()) { // For fidelity we can put multiple cookies per header line. We limit // the line length to an arbitrary value to implement this. const int kMaxLineLength = 128; GoogleString header_value; StringPieceVector cookie_vector; SplitStringPieceToVector(in_cookies, ";", &cookie_vector, true); for (int i = 0, nc = cookie_vector.size(); i < nc; ++i) { if (header_value.empty() || (header_value.size() + cookie_vector[i].size()) < kMaxLineLength) { if (!header_value.empty()) { StrAppend(&header_value, ";"); } StrAppend(&header_value, cookie_vector[i]); } else { request_headers->Add(HttpAttributes::kCookie, header_value); cookie_vector[i].CopyToString(&header_value); } } if (!header_value.empty()) { request_headers->Add(HttpAttributes::kCookie, header_value); } } RequestContextPtr null_request_context; RewriteQuery::Status status = rewrite_query_.Scan( allow_related_options_, allow_options_to_be_set_by_cookies_, request_option_override_, null_request_context, factory(), server_context(), &url, request_headers, response_headers, &handler_); if (out_query != NULL) { out_query->assign(url.Query().data(), url.Query().size()); } if (out_req_string != NULL && request_headers != NULL) { out_req_string->assign(request_headers->ToString()); } if (out_resp_string != NULL && response_headers != NULL) { out_resp_string->assign(response_headers->ToString()); } return status; } // Starts with image_, applies the specified image-options, and any // query-params and request-headers. const RewriteOptions* ParseAndScanImageOptions(StringPiece image_options, StringPiece query_params, StringPiece request_headers) { allow_related_options_ = true; GoogleString query; GoogleString req_string; GoogleString image = AddOptionsToEncodedUrl(image_url_, image_options); const RewriteOptions* options = ParseAndScan(image, query_params, request_headers, &query, &req_string); EXPECT_STREQ("", query); return options; } void CheckExtendCache(const RewriteOptions& options, bool x) { EXPECT_EQ(x, options.Enabled(RewriteOptions::kExtendCacheCss)); EXPECT_EQ(x, options.Enabled(RewriteOptions::kExtendCacheImages)); EXPECT_EQ(x, options.Enabled(RewriteOptions::kExtendCacheScripts)); } // In a fashion patterned after the usage in mod_instaweb.cc, establish // a base configuration, and update it based on the passed-in query string. void Incremental(const StringPiece& query, RewriteOptions* options) { GoogleUrl gurl(StrCat("http://example.com/?ModPagespeedFilters=", query)); RequestContextPtr null_request_context; ASSERT_EQ(RewriteQuery::kSuccess, rewrite_query_.Scan( allow_related_options_, allow_options_to_be_set_by_cookies_, request_option_override_, null_request_context, factory(), server_context(), &gurl, NULL, NULL, message_handler())); options->Merge(*rewrite_query_.options()); } void TestParseClientOptions( RequestHeaders* request_headers, bool expected_parsing_result, RewriteQuery::ProxyMode expected_proxy_mode, DeviceProperties::ImageQualityPreference expected_quality_preference) { RewriteQuery::ProxyMode proxy_mode; DeviceProperties::ImageQualityPreference quality_preference; const StringPiece header_value( request_headers->Lookup1(HttpAttributes::kXPsaClientOptions)); bool parsing_result = RewriteQuery::ParseClientOptions( header_value, &proxy_mode, &quality_preference); EXPECT_EQ(expected_parsing_result, parsing_result); if (parsing_result) { EXPECT_EQ(expected_proxy_mode, proxy_mode); EXPECT_EQ(expected_quality_preference, quality_preference); } } void TestClientOptions( RequestHeaders* request_headers, bool expected_parsing_result, RewriteQuery::ProxyMode expected_proxy_mode, DeviceProperties::ImageQualityPreference expected_quality_preference) { ResponseHeaders response_headers; GoogleString in_query, out_query, out_req_string, out_resp_string; TestParseClientOptions( request_headers, expected_parsing_result, expected_proxy_mode, expected_quality_preference); const RewriteOptions* options = ParseAndScan( kHtmlUrl, in_query, StringPiece(), request_headers, &response_headers, &out_query, &out_req_string, &out_resp_string); if (!expected_parsing_result) { EXPECT_TRUE(options == NULL); return; } if (expected_proxy_mode == RewriteQuery::kProxyModeNoTransform) { EXPECT_EQ(RewriteOptions::kPassThrough, options->level()); // Not a complete list. Only checks the important ones. EXPECT_FALSE(options->Enabled(RewriteOptions::kRewriteCss)); EXPECT_FALSE(options->Enabled( RewriteOptions::kRewriteJavascriptExternal)); EXPECT_FALSE(options->Enabled(RewriteOptions::kRewriteJavascriptInline)); } if (expected_proxy_mode == RewriteQuery::kProxyModeNoTransform || expected_proxy_mode == RewriteQuery::kProxyModeNoImageTransform) { // Not a complete list. Only checks the important ones. EXPECT_FALSE(options->Enabled(RewriteOptions::kConvertGifToPng)); EXPECT_FALSE(options->Enabled(RewriteOptions::kConvertPngToJpeg)); EXPECT_FALSE(options->Enabled(RewriteOptions::kConvertJpegToProgressive)); EXPECT_FALSE(options->Enabled(RewriteOptions::kConvertJpegToWebp)); EXPECT_FALSE(options->Enabled(RewriteOptions::kConvertToWebpLossless)); EXPECT_FALSE(options->Enabled(RewriteOptions::kResizeImages)); EXPECT_FALSE(options->Enabled(RewriteOptions::kResizeMobileImages)); } else { EXPECT_EQ(RewriteQuery::kProxyModeDefault, expected_proxy_mode); if (expected_quality_preference == DeviceProperties::kImageQualityDefault) { EXPECT_TRUE(options == NULL); } } EXPECT_TRUE( request_headers->Lookup1(HttpAttributes::kXPsaClientOptions) == NULL); } GoogleMessageHandler handler_; RewriteQuery rewrite_query_; bool allow_related_options_; bool allow_options_to_be_set_by_cookies_; GoogleString request_option_override_; GoogleString image_url_; }; TEST_F(RewriteQueryTest, Empty) { EXPECT_TRUE(ParseAndScan(kHtmlUrl, "", "") == NULL); } TEST_F(RewriteQueryTest, OffQuery) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "ModPagespeed=off", ""); ASSERT_TRUE(options != NULL); EXPECT_FALSE(options->enabled()); } TEST_F(RewriteQueryTest, OffHeaders) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "", "ModPagespeed:off"); ASSERT_TRUE(options != NULL); EXPECT_FALSE(options->enabled()); } TEST_F(RewriteQueryTest, OffResponseHeader) { RequestHeaders request_headers; ResponseHeaders response_headers; GoogleString in_query, out_query, out_req_string, out_resp_string; response_headers.Add("ModPagespeed", "off"); const RewriteOptions* options = ParseAndScan( kHtmlUrl, in_query, StringPiece(), &request_headers, &response_headers, &out_query, &out_req_string, &out_resp_string); ASSERT_TRUE(options != NULL); EXPECT_FALSE(options->enabled()); } TEST_F(RewriteQueryTest, OffQueryPageSpeed) { const RewriteOptions* options = ParseAndScan(kHtmlUrl, "PageSpeed=off", ""); ASSERT_TRUE(options != NULL); EXPECT_FALSE(options->enabled()); } TEST_F(RewriteQueryTest, OffHeadersPageSpeed) { const RewriteOptions* options = ParseAndScan(kHtmlUrl, "", "PageSpeed:off"); ASSERT_TRUE(options != NULL); EXPECT_FALSE(options->enabled()); } TEST_F(RewriteQueryTest, OffResponseHeaderPageSpeed) { RequestHeaders request_headers; ResponseHeaders response_headers; GoogleString in_query, out_query, out_req_string, out_resp_string; response_headers.Add("PageSpeed", "off"); const RewriteOptions* options = ParseAndScan( kHtmlUrl, in_query, StringPiece(), &request_headers, &response_headers, &out_query, &out_req_string, &out_resp_string); ASSERT_TRUE(options != NULL); EXPECT_FALSE(options->enabled()); } TEST_F(RewriteQueryTest, OnWithDefaultFiltersQuery) { const RewriteOptions* options = ParseAndScan(kHtmlUrl, "ModPagespeed=on", ""); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); CheckExtendCache(*options, true); EXPECT_FALSE(options->Enabled(RewriteOptions::kExtendCachePdfs)); EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kResizeImages)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteJavascriptExternal)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteJavascriptInline)); } TEST_F(RewriteQueryTest, OnWithDefaultFiltersHeaders) { const RewriteOptions* options = ParseAndScan(kHtmlUrl, "", "ModPagespeed:on"); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); CheckExtendCache(*options, true); EXPECT_FALSE(options->Enabled(RewriteOptions::kExtendCachePdfs)); EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kResizeImages)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteJavascriptExternal)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteJavascriptInline)); } TEST_F(RewriteQueryTest, OnWithDefaultFiltersQueryPageSpeed) { const RewriteOptions* options = ParseAndScan(kHtmlUrl, "PageSpeed=on", ""); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); CheckExtendCache(*options, true); EXPECT_FALSE(options->Enabled(RewriteOptions::kExtendCachePdfs)); EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kResizeImages)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteJavascriptExternal)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteJavascriptInline)); } TEST_F(RewriteQueryTest, OnWithDefaultFiltersHeadersPageSpeed) { const RewriteOptions* options = ParseAndScan(kHtmlUrl, "", "PageSpeed:on"); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); CheckExtendCache(*options, true); EXPECT_FALSE(options->Enabled(RewriteOptions::kExtendCachePdfs)); EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kResizeImages)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteJavascriptExternal)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteJavascriptInline)); } TEST_F(RewriteQueryTest, SetFiltersQuery) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "ModPagespeedFilters=remove_quotes", ""); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); EXPECT_TRUE(options->Enabled(RewriteOptions::kRemoveQuotes)); CheckExtendCache(*options, false); EXPECT_FALSE(options->Enabled(RewriteOptions::kExtendCachePdfs)); EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_FALSE(options->Enabled(RewriteOptions::kResizeImages)); EXPECT_FALSE(options->Enabled(RewriteOptions::kRewriteCss)); EXPECT_FALSE(options->Enabled(RewriteOptions::kRewriteJavascriptExternal)); EXPECT_FALSE(options->Enabled(RewriteOptions::kRewriteJavascriptInline)); } TEST_F(RewriteQueryTest, SetFiltersQueryCorePlusMinus) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "ModPagespeedFilters=core,+div_structure,-inline_css,+extend_cache_css", ""); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); CheckExtendCache(*options, true); EXPECT_TRUE(options->Enabled(RewriteOptions::kExtendCacheCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kExtendCacheImages)); EXPECT_TRUE(options->Enabled(RewriteOptions::kDivStructure)); EXPECT_FALSE(options->Enabled(RewriteOptions::kInlineCss)); // Unlike above, these are true because 'core' is in the filter list. EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kResizeImages)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteJavascriptExternal)); EXPECT_TRUE(options->Enabled(RewriteOptions::kRewriteJavascriptInline)); } TEST_F(RewriteQueryTest, SetFiltersRequestHeaders) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "", "ModPagespeedFilters:remove_quotes"); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); EXPECT_TRUE(options->Enabled(RewriteOptions::kRemoveQuotes)); CheckExtendCache(*options, false); EXPECT_FALSE(options->Enabled(RewriteOptions::kExtendCachePdfs)); EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_FALSE(options->Enabled(RewriteOptions::kResizeImages)); EXPECT_FALSE(options->Enabled(RewriteOptions::kRewriteCss)); EXPECT_FALSE(options->Enabled(RewriteOptions::kRewriteJavascriptExternal)); EXPECT_FALSE(options->Enabled(RewriteOptions::kRewriteJavascriptInline)); } TEST_F(RewriteQueryTest, SetFiltersResponseHeaders) { // Check that response headers are properly parsed. RequestHeaders request_headers; ResponseHeaders response_headers; GoogleString in_query, out_query, out_req_string, out_resp_string; response_headers.Add("ModPagespeedFilters", "remove_quotes"); const RewriteOptions* options = ParseAndScan( kHtmlUrl, in_query, StringPiece(), &request_headers, &response_headers, &out_query, &out_req_string, &out_resp_string); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); EXPECT_TRUE(options->Enabled(RewriteOptions::kRemoveQuotes)); CheckExtendCache(*options, false); EXPECT_FALSE(options->Enabled(RewriteOptions::kExtendCachePdfs)); EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_FALSE(options->Enabled(RewriteOptions::kResizeImages)); EXPECT_FALSE(options->Enabled(RewriteOptions::kRewriteCss)); EXPECT_FALSE(options->Enabled(RewriteOptions::kRewriteJavascriptExternal)); EXPECT_FALSE(options->Enabled(RewriteOptions::kRewriteJavascriptInline)); } TEST_F(RewriteQueryTest, QueryAndRequestAndResponseAndCookies) { RequestHeaders request_headers; ResponseHeaders response_headers; GoogleString in_query, in_cookies, out_query, out_req_string, out_resp_string; in_query = ("ModPagespeedFilters=-div_structure,+extend_cache_css"); in_cookies = (" PageSpeedCssFlattenMaxBytes = 12345 " ";ModPagespeedFilters=%2binline_images" // Needed for: ";ModPagespeedImageInlineMaxBytes=67890" ";SessionId=1234567890" // Not ours. ";PageSpeedImageRecompressionQuality=77" ";PageSpeedNoSuchOption=123" // No such. ";ModPagespeedImageLimitOptimizedPercent=55" // Bad scope. ";PageSpeedWebpRecompressionQuality" // No value. ";ModPagespeedImageJpegRecompressQuality=33oops" // Bad value. ";ModPagespeedCssInlineMaxBytes=19" // Conflicts. ";PageSpeedEnrollExperiment=\n1\r"); // Bad chars. request_headers.Add("ModPagespeedCssInlineMaxBytes", "10"); request_headers.Add("ModPagespeedJsInlineMaxBytes", "7"); request_headers.Add("ModPagespeedFilters", "+div_structure,-inline_css,+remove_quotes"); response_headers.Add("ModPagespeedFilters", "+inline_css,-remove_quotes"); response_headers.Add("ModPagespeedJsInlineMaxBytes", "13"); response_headers.Add("ModPagespeedFilters", ""); allow_options_to_be_set_by_cookies_ = true; const RewriteOptions* options = ParseAndScan( kHtmlUrl, in_query, in_cookies, &request_headers, &response_headers, &out_query, &out_req_string, &out_resp_string); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); EXPECT_TRUE(options->Enabled(RewriteOptions::kInlineImages)); EXPECT_EQ(12345, options->css_flatten_max_bytes()); EXPECT_EQ(67890, options->ImageInlineMaxBytes()); EXPECT_EQ(77, options->image_recompress_quality()); EXPECT_EQ(RewriteOptions::kDefaultImageLimitOptimizedPercent, options->image_limit_optimized_percent()); EXPECT_EQ(RewriteOptions::kDefaultImageWebpRecompressQuality, options->ImageWebpQuality()); EXPECT_EQ(RewriteOptions::kDefaultImageLimitResizeAreaPercent, options->image_limit_resize_area_percent()); // Request and cookies conflict, Request should win. EXPECT_EQ(10, options->css_inline_max_bytes()); // Request and Response conflict, Response should win. EXPECT_EQ(13, options->js_inline_max_bytes()); // Request/Response/Query conflicts, disabled should win over enabled EXPECT_FALSE(options->Enabled(RewriteOptions::kInlineCss)); EXPECT_FALSE(options->Enabled(RewriteOptions::kRemoveQuotes)); EXPECT_FALSE(options->Enabled(RewriteOptions::kDivStructure)); EXPECT_TRUE(options->Enabled(RewriteOptions::kExtendCacheCss)); // PageSpeed option cookies have been squirreled away. EXPECT_STREQ("ModPagespeedCssInlineMaxBytes=19" // Conflicts but still saved. "&ModPagespeedFilters=+inline_images" "&ModPagespeedImageInlineMaxBytes=67890" "&PageSpeedCssFlattenMaxBytes=12345" "&PageSpeedEnrollExperiment=1" // The bad chars are removed. "&PageSpeedImageRecompressionQuality=77", rewrite_query_.pagespeed_option_cookies().ToEscapedString()); } TEST_F(RewriteQueryTest, CannotSetOptionsByCookiesWhenDisabled) { RequestHeaders request_headers; ResponseHeaders response_headers; GoogleString in_query, in_cookies, out_query, out_req_string, out_resp_string; // We only do this to ensure that ParseAndScan returns non-NULL options. in_query = ("ModPagespeedFilters=-div_structure,+extend_cache_css"); in_cookies = (" PageSpeedCssFlattenMaxBytes = 12345 " ";ModPagespeedFilters=+inline_images" // Needed for: ";ModPagespeedImageInlineMaxBytes=67890" ";PageSpeedImageRecompressionQuality=77" ";ModPagespeedCssInlineMaxBytes=19"); allow_options_to_be_set_by_cookies_ = false; // Default, but let's be *sure*. const RewriteOptions* options = ParseAndScan( kHtmlUrl, in_query, in_cookies, &request_headers, &response_headers, &out_query, &out_req_string, &out_resp_string); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); // Everything should be default value. EXPECT_EQ(RewriteOptions::kDefaultCssFlattenMaxBytes, options->css_flatten_max_bytes()); EXPECT_EQ(RewriteOptions::kDefaultImageInlineMaxBytes, options->ImageInlineMaxBytes()); EXPECT_EQ(RewriteOptions::kDefaultImageRecompressQuality, options->image_recompress_quality()); EXPECT_EQ(RewriteOptions::kDefaultCssInlineMaxBytes, options->css_inline_max_bytes()); // The query parameter options should still have taken effect. EXPECT_FALSE(options->Enabled(RewriteOptions::kDivStructure)); EXPECT_TRUE(options->Enabled(RewriteOptions::kExtendCacheCss)); } // Note: In the next four tests we intentionally mix ModPagespeed* and // PageSpeed* query params to make sure all combinations work and are respected. TEST_F(RewriteQueryTest, MultipleQuery) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "PageSpeedFilters=inline_css&ModPagespeedCssInlineMaxBytes=10", ""); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); EXPECT_TRUE(options->Enabled(RewriteOptions::kInlineCss)); EXPECT_EQ(10, options->css_inline_max_bytes()); } TEST_F(RewriteQueryTest, MultipleHeaders) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "", "ModPagespeedFilters:inline_css;PageSpeedCssInlineMaxBytes:10"); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); EXPECT_TRUE(options->Enabled(RewriteOptions::kInlineCss)); EXPECT_EQ(10, options->css_inline_max_bytes()); } TEST_F(RewriteQueryTest, MultipleQueryAndHeaders) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "ModPagespeedFilters=inline_css", "ModPagespeedCssInlineMaxBytes:10"); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); EXPECT_TRUE(options->Enabled(RewriteOptions::kInlineCss)); EXPECT_EQ(10, options->css_inline_max_bytes()); } TEST_F(RewriteQueryTest, MultipleIgnoreUnrelated) { const RewriteOptions* options = ParseAndScan(kHtmlUrl, "PageSpeedFilters=inline_css" "&PageSpeedCssInlineMaxBytes=10" "&Unrelated1" "&Unrelated2=" "&Unrelated3=value", ""); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); EXPECT_TRUE(options->Enabled(RewriteOptions::kInlineCss)); EXPECT_EQ(10, options->css_inline_max_bytes()); } TEST_F(RewriteQueryTest, MultipleBroken) { const RewriteOptions* options = ParseAndScan(kHtmlUrl, "PageSpeedFilters=inline_css" "&PageSpeedCssInlineMaxBytes=10" "&PageSpeedFilters=bogus_filter", ""); EXPECT_TRUE(options == NULL); } TEST_F(RewriteQueryTest, MultipleInt64Params) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "PageSpeedCssInlineMaxBytes=3" "&PageSpeedImageInlineMaxBytes=5" "&PageSpeedCssImageInlineMaxBytes=7" "&PageSpeedJsInlineMaxBytes=11" "&PageSpeedDomainShardCount=2", ""); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->enabled()); EXPECT_EQ(3, options->css_inline_max_bytes()); EXPECT_EQ(5, options->ImageInlineMaxBytes()); EXPECT_EQ(7, options->CssImageInlineMaxBytes()); EXPECT_EQ(11, options->js_inline_max_bytes()); EXPECT_EQ(2, options->domain_shard_count()); } TEST_F(RewriteQueryTest, OptionsNotArbitrary) { // Security sanity check: trying to set beacon URL // externally should not succeed. const RewriteOptions* options = ParseAndScan(kHtmlUrl, StrCat("PageSpeed", RewriteOptions::kBeaconUrl, "=", "evil.com"), ""); EXPECT_TRUE(options == NULL); } TEST_F(RewriteQueryTest, OutputQueryandHeaders) { GoogleString output_query, output_headers; ParseAndScan(kHtmlUrl, "ModPagespeedCssInlineMaxBytes=3" "&ModPagespeedImageInlineMaxBytes=5" "&ModPagespeedCssImageInlineMaxBytes=7" "&ModPagespeedJsInlineMaxBytes=11" "&ModPagespeedDomainShardCount=100" "&ModPagespeedCssFlattenMaxBytes=13" "&abc=1" "&def", "ModPagespeedFilters:inline_css;" "xyz:6;" "ModPagespeedFilters:remove_quotes", &output_query, &output_headers); EXPECT_EQ(output_query, "abc=1&def"); EXPECT_EQ(output_headers, "GET HTTP/1.0\r\nxyz: 6\r\n\r\n"); ParseAndScan(kHtmlUrl, "ModPagespeedCssInlineMaxBytes=3", "", &output_query, &output_headers); EXPECT_EQ(output_query, ""); } TEST_F(RewriteQueryTest, OutputQueryandHeadersPageSpeed) { GoogleString output_query, output_headers; ParseAndScan(kHtmlUrl, "PageSpeedCssInlineMaxBytes=3" "&PageSpeedImageInlineMaxBytes=5" "&PageSpeedCssImageInlineMaxBytes=7" "&PageSpeedJsInlineMaxBytes=11" "&PageSpeedDomainShardCount=100" "&PageSpeedCssFlattenMaxBytes=13" "&abc=1" "&def", "PageSpeedFilters:inline_css;" "xyz:6;" "PageSpeedFilters:remove_quotes", &output_query, &output_headers); EXPECT_EQ(output_query, "abc=1&def"); EXPECT_EQ(output_headers, "GET HTTP/1.0\r\nxyz: 6\r\n\r\n"); ParseAndScan(kHtmlUrl, "PageSpeedCssInlineMaxBytes=3", "", &output_query, &output_headers); EXPECT_EQ(output_query, ""); } TEST_F(RewriteQueryTest, OutputQueryandHeadersPostRequest) { GoogleString output_query, output_req_headers, output_resp_headers; RequestHeaders request_headers; request_headers.set_method(RequestHeaders::kPost); request_headers.Add("ModPagespeedFilters", "inline_css"); request_headers.Add("xyz", "6"); request_headers.set_message_body("pqr"); ParseAndScan(kHtmlUrl, "ModPagespeedCssInlineMaxBytes=3" "&abc=1" "&def", StringPiece(), &request_headers, NULL, &output_query, &output_req_headers, &output_resp_headers); EXPECT_EQ(output_query, "abc=1&def"); EXPECT_EQ(output_req_headers, "POST HTTP/1.0\r\nxyz: 6\r\n\r\n"); EXPECT_EQ(request_headers.message_body(), "pqr"); } TEST_F(RewriteQueryTest, OutputQueryandHeadersPostRequestPageSpeed) { GoogleString output_query, output_req_headers, output_resp_headers; RequestHeaders request_headers; request_headers.set_method(RequestHeaders::kPost); request_headers.Add("PageSpeedFilters", "inline_css"); request_headers.Add("xyz", "6"); request_headers.set_message_body("pqr"); ParseAndScan(kHtmlUrl, "PageSpeedCssInlineMaxBytes=3" "&abc=1" "&def", StringPiece(), &request_headers, NULL, &output_query, &output_req_headers, &output_resp_headers); EXPECT_EQ(output_query, "abc=1&def"); EXPECT_EQ(output_req_headers, "POST HTTP/1.0\r\nxyz: 6\r\n\r\n"); EXPECT_EQ(request_headers.message_body(), "pqr"); } // Tests the ability to add an additional filter on the command-line based // on whatever set is already installed in the configuration. TEST_F(RewriteQueryTest, IncrementalAdd) { RewriteOptions options(factory()->thread_system()); options.SetDefaultRewriteLevel(RewriteOptions::kCoreFilters); options.EnableFilter(RewriteOptions::kStripScripts); Incremental("+debug", &options); EXPECT_TRUE(options.Enabled(RewriteOptions::kStripScripts)); EXPECT_TRUE(options.Enabled(RewriteOptions::kDebug)); EXPECT_TRUE(options.Enabled(RewriteOptions::kCombineCss)); EXPECT_FALSE(options.Enabled(RewriteOptions::kAddBaseTag)); EXPECT_TRUE(options.modified()); } // Same exact test as above, except that we omit the "+". This wipes out // the explicitly enabled filter in the configuration and also the core // level. TEST_F(RewriteQueryTest, NonIncrementalAdd) { RewriteOptions options(factory()->thread_system()); options.SetDefaultRewriteLevel(RewriteOptions::kCoreFilters); options.EnableFilter(RewriteOptions::kStripScripts); Incremental("debug", &options); EXPECT_FALSE(options.Enabled(RewriteOptions::kStripScripts)); EXPECT_TRUE(options.Enabled(RewriteOptions::kDebug)); EXPECT_FALSE(options.Enabled(RewriteOptions::kCombineCss)); EXPECT_TRUE(options.modified()); } // In this version we specify nothing, and that should erase the filters. TEST_F(RewriteQueryTest, IncrementalEmpty) { RewriteOptions options(factory()->thread_system()); options.SetDefaultRewriteLevel(RewriteOptions::kCoreFilters); options.EnableFilter(RewriteOptions::kStripScripts); Incremental("", &options); EXPECT_FALSE(options.Enabled(RewriteOptions::kStripScripts)); EXPECT_FALSE(options.Enabled(RewriteOptions::kCombineCss)); EXPECT_TRUE(options.modified()); } TEST_F(RewriteQueryTest, IncrementalRemoveExplicit) { RewriteOptions options(factory()->thread_system()); options.SetDefaultRewriteLevel(RewriteOptions::kCoreFilters); options.EnableFilter(RewriteOptions::kStripScripts); Incremental("-strip_scripts", &options); EXPECT_FALSE(options.Enabled(RewriteOptions::kStripScripts)); EXPECT_TRUE(options.Enabled(RewriteOptions::kCombineCss)); EXPECT_TRUE(options.modified()); } TEST_F(RewriteQueryTest, IncrementalRemoveFromCore) { RewriteOptions options(factory()->thread_system()); options.SetDefaultRewriteLevel(RewriteOptions::kCoreFilters); options.EnableFilter(RewriteOptions::kStripScripts); Incremental("-combine_css", &options); EXPECT_TRUE(options.Enabled(RewriteOptions::kStripScripts)); EXPECT_FALSE(options.Enabled(RewriteOptions::kCombineCss)); EXPECT_TRUE(options.modified()); } TEST_F(RewriteQueryTest, NoChangesShouldNotModify) { RewriteOptions options(factory()->thread_system()); options.SetDefaultRewriteLevel(RewriteOptions::kCoreFilters); Incremental("+combine_css", &options); EXPECT_FALSE(options.Enabled(RewriteOptions::kStripScripts)); EXPECT_TRUE(options.Enabled(RewriteOptions::kCombineCss)); // // TODO(jmarantz): We would like at this point to have options show up // as unmodified. However our implementation of query-params parsing // does not allow for this at this point, because it doesn't know // that it is working with the core filters. Right now this is not // that important as the only usage of RewriteOptions::modified() is // in apache/mod_instaweb.cc which is just checking to see if there are // any directory-specific options set. // // EXPECT_FALSE(options.modified()); } TEST_F(RewriteQueryTest, NoQueryValue) { const RewriteOptions* options = ParseAndScan(kHtmlUrl, "ModPagespeed=", ""); EXPECT_TRUE(options == NULL); } TEST_F(RewriteQueryTest, NoscriptQueryParamEmptyValue) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "PageSpeed=noscript", ""); ASSERT_TRUE(options != NULL); RewriteOptions::FilterVector filter_vector; options->GetEnabledFiltersRequiringScriptExecution(&filter_vector); EXPECT_TRUE(filter_vector.empty()); EXPECT_TRUE(options->Enabled(RewriteOptions::kHandleNoscriptRedirect)); } TEST_F(RewriteQueryTest, NoscriptHeader) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "", "PageSpeed:noscript"); ASSERT_TRUE(options != NULL); RewriteOptions::FilterVector filter_vector; options->GetEnabledFiltersRequiringScriptExecution(&filter_vector); EXPECT_TRUE(filter_vector.empty()); EXPECT_TRUE(options->Enabled(RewriteOptions::kHandleNoscriptRedirect)); } TEST_F(RewriteQueryTest, NoscriptWithTrailingQuoteQueryParamEmptyValue) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "PageSpeed=noscript'", ""); ASSERT_TRUE(options != NULL); RewriteOptions::FilterVector filter_vector; options->GetEnabledFiltersRequiringScriptExecution(&filter_vector); EXPECT_TRUE(filter_vector.empty()); EXPECT_FALSE(options->Enabled(RewriteOptions::kLazyloadImages)); EXPECT_TRUE(options->Enabled(RewriteOptions::kHandleNoscriptRedirect)); } TEST_F(RewriteQueryTest, NoscriptWithTrailingEscapedQuoteQueryParamEmptyValue) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "PageSpeed=noscript%5c%22", ""); ASSERT_TRUE(options != NULL); RewriteOptions::FilterVector filter_vector; options->GetEnabledFiltersRequiringScriptExecution(&filter_vector); EXPECT_TRUE(filter_vector.empty()); EXPECT_FALSE(options->Enabled(RewriteOptions::kLazyloadImages)); EXPECT_TRUE(options->Enabled(RewriteOptions::kHandleNoscriptRedirect)); } TEST_F(RewriteQueryTest, NoscripWithTrailingQuotetHeader) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "", "PageSpeed:noscript'"); ASSERT_TRUE(options != NULL); RewriteOptions::FilterVector filter_vector; options->GetEnabledFiltersRequiringScriptExecution(&filter_vector); EXPECT_TRUE(filter_vector.empty()); EXPECT_FALSE(options->Enabled(RewriteOptions::kLazyloadImages)); EXPECT_TRUE(options->Enabled(RewriteOptions::kHandleNoscriptRedirect)); } TEST_F(RewriteQueryTest, NoscripWithTrailingQuestionMarkHeader) { const RewriteOptions* options = ParseAndScan( kHtmlUrl, "", "PageSpeed:noscript?"); ASSERT_TRUE(options != NULL); RewriteOptions::FilterVector filter_vector; options->GetEnabledFiltersRequiringScriptExecution(&filter_vector); EXPECT_TRUE(filter_vector.empty()); EXPECT_FALSE(options->Enabled(RewriteOptions::kLazyloadImages)); EXPECT_TRUE(options->Enabled(RewriteOptions::kHandleNoscriptRedirect)); } TEST_F(RewriteQueryTest, JpegRecompressionQuality) { const char kQuery[] = "PageSpeedJpegRecompressionQuality=73"; GoogleString query, req; const RewriteOptions* options = ParseAndScan( image_url_, kQuery, "", &query, &req); EXPECT_TRUE(options != NULL); EXPECT_STREQ("", query); EXPECT_EQ(73, options->ImageJpegQuality()); } TEST_F(RewriteQueryTest, RequestOptionOverrideWithIncorrectToken) { const char kQuery[] = "PageSpeedJpegRecompressionQuality=88&PageSpeedRequestOptionOverride=def"; GoogleString query, req; request_option_override_ = "abc"; const RewriteOptions* options = ParseAndScan(image_url_, kQuery, "", &query, &req); EXPECT_TRUE(options == NULL); } TEST_F(RewriteQueryTest, RequestOptionOverride) { const char kQuery[] = "PageSpeedJpegRecompressionQuality=73&PageSpeedRequestOptionOverride=abc"; GoogleString query, req; request_option_override_ = "abc"; const RewriteOptions* options = ParseAndScan(image_url_, kQuery, "", &query, &req); EXPECT_EQ(73, options->ImageJpegQuality()); } TEST_F(RewriteQueryTest, RequestOptionOverrideProvidedWhenNotRequired) { const char kQuery[] = "PageSpeedJpegRecompressionQuality=73&PageSpeedRequestOptionOverride=abc"; GoogleString query, req; const RewriteOptions* options = ParseAndScan(image_url_, kQuery, "", &query, &req); EXPECT_EQ(73, options->ImageJpegQuality()); } TEST_F(RewriteQueryTest, RequestOptionOverrideNotProvidedWhenRequired) { const char kQuery[] = "PageSpeedJpegRecompressionQuality=73"; GoogleString query, req; request_option_override_ = "abc"; const RewriteOptions* options = ParseAndScan(image_url_, kQuery, "", &query, &req); EXPECT_TRUE(options == NULL); } TEST_F(RewriteQueryTest, GenerateEmptyResourceOption) { EXPECT_EQ("", RewriteQuery::GenerateResourceOption("ic", rewrite_driver())); } TEST_F(RewriteQueryTest, GenerateResourceOptionRecompressImages) { options()->EnableFilter(RewriteOptions::kRecompressJpeg); // relevant options()->EnableFilter(RewriteOptions::kCombineCss); // not relevant options()->set_image_jpeg_recompress_quality(70); EXPECT_EQ("rj+iq=70", RewriteQuery::GenerateResourceOption("ic", rewrite_driver())); EXPECT_EQ("", RewriteQuery::GenerateResourceOption("jm", rewrite_driver())); // TODO(jmarantz): add support for CSS/JS options & test. // TODO(jmarantz): test all relevant filter/option combinations. } TEST_F(RewriteQueryTest, DontAllowArbitraryOptionsForNonPagespeedResources) { allow_related_options_ = true; // The kHtmlUrl is a .jsp, which is not .pagespeed. const RewriteOptions* options = ParseAndScan( kHtmlUrl, "PsolOpt=rj,iq:70", ""); EXPECT_TRUE(options == NULL); } TEST_F(RewriteQueryTest, DontAllowArbitraryOptionsWhenDisabled) { GoogleString image = AddOptionsToEncodedUrl(image_url_, "rj+iq=70"); const RewriteOptions* options = ParseAndScan(image, "", ""); EXPECT_TRUE(options == NULL); } TEST_F(RewriteQueryTest, CanQueryRecompressImages) { const RewriteOptions* options = ParseAndScanImageOptions("rj+iq=70", "", ""); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->Enabled(RewriteOptions::kRecompressJpeg)); EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_EQ(70, options->ImageJpegQuality()); } TEST_F(RewriteQueryTest, CanOverrideRecompressImagesWithQuery) { const RewriteOptions* options = ParseAndScanImageOptions( "rj+iq=70", "PageSpeedJpegRecompressionQuality=71", ""); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->Enabled(RewriteOptions::kRecompressJpeg)); EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_EQ(71, options->ImageJpegQuality()); } TEST_F(RewriteQueryTest, CanOverrideRecompressImagesWithReqHeaders) { const RewriteOptions* options = ParseAndScanImageOptions( "rj+iq=70", "", "PageSpeedJpegRecompressionQuality:72"); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->Enabled(RewriteOptions::kRecompressJpeg)); EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_EQ(72, options->ImageJpegQuality()); } TEST_F(RewriteQueryTest, CanOverrideRecompressImagesWithBoth) { const RewriteOptions* options = ParseAndScanImageOptions( "rj+iq=70", "PageSpeedJpegRecompressionQuality=71", "PageSpeedJpegRecompressionQuality:72"); ASSERT_TRUE(options != NULL); EXPECT_TRUE(options->Enabled(RewriteOptions::kRecompressJpeg)); EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_EQ(72, options->ImageJpegQuality()) << "req-headers win."; } TEST_F(RewriteQueryTest, OnlyAllowWhitelistedResources) { allow_related_options_ = true; // whitelisted by "ic" GoogleString image = AddOptionsToEncodedUrl(image_url_, "rj"); EXPECT_TRUE(ParseAndScan(image, "", "") != NULL); image = AddOptionsToEncodedUrl(image_url_, "iq=70"); EXPECT_TRUE(ParseAndScan(image, "", "") != NULL); // not whitelisted by "ic" image = AddOptionsToEncodedUrl(image_url_, "cc"); EXPECT_TRUE(ParseAndScan(image_url_, "", "") == NULL); image = AddOptionsToEncodedUrl(image_url_, "rdm=10"); EXPECT_TRUE(ParseAndScan(image_url_, "", "") == NULL); } TEST_F(RewriteQueryTest, ClientOptionsEmptyHeader) { RequestHeaders request_headers; TestClientOptions(&request_headers, false, /* expected_parsing_result */ RewriteQuery::kProxyModeDefault, DeviceProperties::kImageQualityDefault); } TEST_F(RewriteQueryTest, ClientOptionsMultipleHeaders) { RequestHeaders request_headers; request_headers.Add(HttpAttributes::kXPsaClientOptions, "v=1,iqp=3,m=0"); request_headers.Add(HttpAttributes::kXPsaClientOptions, "v=1,iqp=3,m=0"); TestClientOptions(&request_headers, false, /* expected_parsing_result */ RewriteQuery::kProxyModeDefault, DeviceProperties::kImageQualityDefault); } TEST_F(RewriteQueryTest, ClientOptionsOrder1) { RequestHeaders request_headers; request_headers.Replace(HttpAttributes::kXPsaClientOptions, "v=1,iqp=2,m=0"); // Image quality is set. TestClientOptions(&request_headers, true, /* expected_parsing_result */ RewriteQuery::kProxyModeDefault, DeviceProperties::kImageQualityMedium); } TEST_F(RewriteQueryTest, ClientOptionsOrder2) { RequestHeaders request_headers; // The order of name-value pairs does not matter. // Not-supported parts are ignored. request_headers.Replace(HttpAttributes::kXPsaClientOptions, "m=0,iqp=3,v=1,xyz=100,zyx=,yzx"); TestClientOptions(&request_headers, true, /* expected_parsing_result */ RewriteQuery::kProxyModeDefault, DeviceProperties::kImageQualityHigh); } TEST_F(RewriteQueryTest, ClientOptionsCaseInsensitive) { RequestHeaders request_headers; GoogleString lower(HttpAttributes::kXPsaClientOptions); LowerString(&lower); request_headers.Replace(lower, "v=1,iqp=3,m=1"); // Image quality is set. TestClientOptions(&request_headers, true, /* expected_parsing_result */ RewriteQuery::kProxyModeNoImageTransform, DeviceProperties::kImageQualityDefault); } TEST_F(RewriteQueryTest, ClientOptionsNonDefaultProxyMode) { RequestHeaders request_headers; // Image quality is ignored if mode is not Default. request_headers.Replace(HttpAttributes::kXPsaClientOptions, "v=1,iqp=2,m=1"); TestClientOptions(&request_headers, true, /* expected_parsing_result */ RewriteQuery::kProxyModeNoImageTransform, DeviceProperties::kImageQualityDefault); } TEST_F(RewriteQueryTest, ClientOptionsValidVersionBadOptions) { RequestHeaders request_headers; // A valid version with bad options. request_headers.Replace(HttpAttributes::kXPsaClientOptions, "v=1,iqp=2m=1,iqp="); TestClientOptions(&request_headers, true, /* expected_parsing_result */ RewriteQuery::kProxyModeDefault, DeviceProperties::kImageQualityDefault); } TEST_F(RewriteQueryTest, ClientOptionsInvalidVersion) { RequestHeaders request_headers; request_headers.Replace(HttpAttributes::kXPsaClientOptions, "iqp=2,m=1,v=2"); TestClientOptions(&request_headers, false, /* expected_parsing_result */ RewriteQuery::kProxyModeDefault, DeviceProperties::kImageQualityDefault); } TEST_F(RewriteQueryTest, CacheControlNoTransform) { RequestHeaders request_headers; request_headers.Replace(HttpAttributes::kCacheControl, "no-transform"); ResponseHeaders response_headers; GoogleString in_query, out_query, out_req_string, out_resp_string; const RewriteOptions* options = ParseAndScan( kHtmlUrl, in_query, StringPiece(), &request_headers, &response_headers, &out_query, &out_req_string, &out_resp_string); ASSERT_TRUE(options != NULL); EXPECT_FALSE(options->enabled()); EXPECT_TRUE(request_headers.Lookup1(HttpAttributes::kCacheControl) != NULL); } TEST_F(RewriteQueryTest, DisableFiltersWithXHR) { RequestHeaders request_headers; request_headers.Replace(HttpAttributes::kXRequestedWith, HttpAttributes::kXmlHttpRequest); ResponseHeaders response_headers; GoogleString in_query, out_query, out_req_string, out_resp_string; EXPECT_EQ(RewriteQuery::kSuccess, Parse( kHtmlUrl, in_query, StringPiece(), &request_headers, &response_headers, &out_query, &out_req_string, &out_resp_string)); scoped_ptr<RewriteOptions> options(rewrite_query_.options()->Clone()); // Convert disabled -> forbidden for easier testing. options->set_forbid_all_disabled_filters(true); // defer_js, mobilize generaly require JS. EXPECT_TRUE(options->Forbidden(RewriteOptions::kDeferJavascript)); EXPECT_TRUE(options->Forbidden(RewriteOptions::kMobilize)); EXPECT_TRUE(options->Forbidden(RewriteOptions::kMoveCssToHead)); EXPECT_TRUE(options->Forbidden(RewriteOptions::kAddInstrumentation)); // rewrite_css doesn't, and shouldn't be defaulted on, either. EXPECT_FALSE(options->Forbidden(RewriteOptions::kRewriteCss)); EXPECT_FALSE(options->Enabled(RewriteOptions::kRewriteCss)); } TEST_F(RewriteQueryTest, CacheControlPrivateNoTransformResponse) { RequestHeaders request_headers; ResponseHeaders response_headers; response_headers.Replace(HttpAttributes::kCacheControl, "private, no-transform"); GoogleString in_query, out_query, out_req_string, out_resp_string; const RewriteOptions* options = ParseAndScan( kHtmlUrl, in_query, StringPiece(), &request_headers, &response_headers, &out_query, &out_req_string, &out_resp_string); ASSERT_TRUE(options != NULL); EXPECT_FALSE(options->enabled()); // Check that we don't strip either of the cache-control values. EXPECT_TRUE(response_headers.HasValue(HttpAttributes::kCacheControl, "private")); EXPECT_TRUE(response_headers.HasValue(HttpAttributes::kCacheControl, "no-transform")); } TEST_F(RewriteQueryTest, NoCustomOptionsWithCacheControlPrivate) { RequestHeaders request_headers; ResponseHeaders response_headers; response_headers.Replace(HttpAttributes::kCacheControl, "private"); GoogleString in_query, out_query, out_req_string, out_resp_string; const RewriteOptions* options = ParseAndScan( kHtmlUrl, in_query, StringPiece(), &request_headers, &response_headers, &out_query, &out_req_string, &out_resp_string); EXPECT_TRUE(options == NULL); } TEST_F(RewriteQueryTest, PageSpeedQueryParamsAreExtracted) { GoogleUrl gurl("http://test.com/?a=b&" "ModPagespeedFilters=debug&" "x=y&" "ModPagespeedCssFlattenMaxBytes=123"); RequestContextPtr null_request_context; EXPECT_EQ(RewriteQuery::kSuccess, rewrite_query_.Scan( allow_related_options_, allow_options_to_be_set_by_cookies_, request_option_override_, null_request_context, factory(), server_context(), &gurl, NULL, NULL, message_handler())); EXPECT_STREQ("http://test.com/?a=b&x=y", gurl.Spec()); EXPECT_EQ(2, rewrite_query_.pagespeed_query_params().size()); EXPECT_STREQ("ModPagespeedFilters=debug&" "ModPagespeedCssFlattenMaxBytes=123", rewrite_query_.pagespeed_query_params().ToEscapedString()); } TEST_F(RewriteQueryTest, PageSpeedStickyQueryParametersTokenIsExtracted) { // First test that no token is extracted if not specified. RequestContextPtr request_context(CreateRequestContext()); GoogleUrl gurl("http://test.com/?PageSpeedFilters=debug"); EXPECT_EQ(RewriteQuery::kSuccess, rewrite_query_.Scan( allow_related_options_, allow_options_to_be_set_by_cookies_, request_option_override_, request_context, factory(), server_context(), &gurl, NULL, NULL, message_handler())); EXPECT_STREQ("http://test.com/", gurl.Spec()); EXPECT_EQ(1, rewrite_query_.pagespeed_query_params().size()); EXPECT_STREQ("PageSpeedFilters=debug", rewrite_query_.pagespeed_query_params().ToEscapedString()); EXPECT_STREQ("", request_context->sticky_query_parameters_token()); // Then test that the token is extracted when specified. gurl.Reset("http://test.com/" "?PageSpeedFilters=debug" "&PageSpeedStickyQueryParameters=yadda"); EXPECT_EQ(RewriteQuery::kSuccess, rewrite_query_.Scan( allow_related_options_, allow_options_to_be_set_by_cookies_, request_option_override_, request_context, factory(), server_context(), &gurl, NULL, NULL, message_handler())); EXPECT_STREQ("http://test.com/", gurl.Spec()); EXPECT_EQ(2, rewrite_query_.pagespeed_query_params().size()); EXPECT_STREQ("PageSpeedFilters=debug&PageSpeedStickyQueryParameters=yadda", rewrite_query_.pagespeed_query_params().ToEscapedString()); EXPECT_STREQ("yadda", request_context->sticky_query_parameters_token()); } } // namespace net_instaweb
43.150708
80
0.72177
[ "transform" ]
0512d4eb726564815532c8952e9b08f84b7e45b4
5,643
cxx
C++
src/mlio/integ/dlpack.cxx
aws-patlin/ml-io
047e7d40609ced6f839d0b08d1917e9742a785af
[ "Apache-2.0" ]
null
null
null
src/mlio/integ/dlpack.cxx
aws-patlin/ml-io
047e7d40609ced6f839d0b08d1917e9742a785af
[ "Apache-2.0" ]
null
null
null
src/mlio/integ/dlpack.cxx
aws-patlin/ml-io
047e7d40609ced6f839d0b08d1917e9742a785af
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You * may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ #include "mlio/integ/dlpack.h" #include <cstdint> #include <memory> #include <stdexcept> #include <dlpack/dlpack.h> #include "mlio/data_type.h" #include "mlio/device_array.h" #include "mlio/device.h" #include "mlio/not_supported_error.h" #include "mlio/tensor.h" #include "mlio/tensor_visitor.h" namespace mlio { inline namespace v1 { namespace detail { namespace { inline ::DLDeviceType as_dl_device(device_kind knd) { if (knd == device_kind::cpu()) { return ::kDLCPU; } throw not_supported_error{"The device kind is not supported by DLPack."}; } inline ::DLContext as_dl_context(device dev) { return ::DLContext{as_dl_device(dev.kind()), static_cast<int>(dev.id())}; } template<data_type dt> inline ::DLDataType as_dl_data_type(::DLDataTypeCode code) { auto uint_code = static_cast<std::uint8_t>(code); return ::DLDataType{uint_code, 8 * sizeof(data_type_t<dt>), 1}; } DLDataType as_dl_data_type(data_type dt) { switch (dt) { case data_type::size: return as_dl_data_type<data_type::size> (::kDLUInt); case data_type::float16: return as_dl_data_type<data_type::float16>(::kDLFloat); case data_type::float32: return as_dl_data_type<data_type::float32>(::kDLFloat); case data_type::float64: return as_dl_data_type<data_type::float64>(::kDLFloat); case data_type::sint8: return as_dl_data_type<data_type::sint8> (::kDLInt); case data_type::sint16: return as_dl_data_type<data_type::sint16> (::kDLInt); case data_type::sint32: return as_dl_data_type<data_type::sint32> (::kDLInt); case data_type::sint64: return as_dl_data_type<data_type::sint64> (::kDLInt); case data_type::uint8: return as_dl_data_type<data_type::uint8> (::kDLUInt); case data_type::uint16: return as_dl_data_type<data_type::uint16> (::kDLUInt); case data_type::uint32: return as_dl_data_type<data_type::uint32> (::kDLUInt); case data_type::uint64: return as_dl_data_type<data_type::uint64> (::kDLUInt); case data_type::string: throw not_supported_error{ "The string data type is not supported by DLPack."}; } throw not_supported_error{"The tensor has an unknown data type."}; } std::int64_t * cast_shape(size_vector const &shape) noexcept { if (shape.empty()) { return nullptr; } // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<std::int64_t *>( reinterpret_cast<std::int64_t const *>(shape.data())); } std::int64_t * cast_strides(ssize_vector const &strides) noexcept { if (strides.empty()) { return nullptr; } #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wuseless-cast" #endif // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<std::int64_t *>( reinterpret_cast<std::int64_t const *>(strides.data())); #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic pop #endif } // This is the structure that has a cyclic reference to the // DLManagedTensor it holds. It keeps the associated tensor // alive until the DLManagedTensor gets deleted. struct dl_pack_context { intrusive_ptr<tensor> tsr{}; ::DLManagedTensor mt{}; }; struct as_dlpack_op : public tensor_visitor { using tensor_visitor::visit; void visit(tensor &) override { throw std::invalid_argument{ "DLPack is only supported for dense tensors."}; } void visit(dense_tensor &tsr) override; ::DLManagedTensor *mt{}; }; void as_dlpack_op:: visit(dense_tensor &tsr) { auto ctx = std::make_unique<dl_pack_context>(); ctx->tsr = wrap_intrusive(&tsr, true); ctx->mt.dl_tensor.data = tsr.data().data(); ctx->mt.dl_tensor.ctx = as_dl_context(tsr.data().get_device()); ctx->mt.dl_tensor.dtype = as_dl_data_type(tsr.dtype()); ctx->mt.dl_tensor.ndim = static_cast<int>(tsr.shape().size()); ctx->mt.dl_tensor.shape = cast_shape(tsr.shape()); ctx->mt.dl_tensor.strides = cast_strides(tsr.strides()); ctx->mt.dl_tensor.byte_offset = 0; ctx->mt.manager_ctx = ctx.get(); ctx->mt.deleter = [](::DLManagedTensor *self) { if (self->manager_ctx != nullptr) { delete static_cast<dl_pack_context *>(self->manager_ctx); } }; mt = &ctx.release()->mt; } } // namespace } // namespace detail ::DLManagedTensor * as_dlpack(tensor &tsr, std::size_t version) { #if SIZE_MAX != UINT64_MAX throw not_supported_error{"DLPack is only supported on 64-bit platforms."}; #else if (version != DLPACK_VERSION) { throw not_supported_error{ "The requested DLPack version is not supported."}; } detail::as_dlpack_op op{}; tsr.accept(op); return op.mt; #endif } intrusive_ptr<tensor> as_tensor(::DLManagedTensor *, std::size_t) { throw not_supported_error{"Importing DLPack is not supported yet!"}; } } // namespace v1 } // namespace mlio
26.617925
79
0.683147
[ "shape" ]
05162b36e120194fe38c858e716ffd2a3162f6ae
9,083
hxx
C++
win32/include/QUANTA/QUANTAnet_http_c.hxx
benyaboy/sage-graphics
090640167329ace4b6ad266d47db5bb2b0394232
[ "Unlicense" ]
null
null
null
win32/include/QUANTA/QUANTAnet_http_c.hxx
benyaboy/sage-graphics
090640167329ace4b6ad266d47db5bb2b0394232
[ "Unlicense" ]
null
null
null
win32/include/QUANTA/QUANTAnet_http_c.hxx
benyaboy/sage-graphics
090640167329ace4b6ad266d47db5bb2b0394232
[ "Unlicense" ]
1
2021-07-02T10:31:03.000Z
2021-07-02T10:31:03.000Z
/****************************************************************************** * QUANTA - A toolkit for High Performance Data Sharing * Copyright (C) 2003 Electronic Visualization Laboratory, * University of Illinois at Chicago * * 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 Public License along * with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Direct questions, comments etc about Quanta to cavern@evl.uic.edu *****************************************************************************/ #ifndef _QUANTAPLUS_HTTP #define _QUANTAPLUS_HTTP #include <QUANTA/QUANTAnet_tcp_c.hxx> #ifndef _WIN32_WCE #include <sys/types.h> #endif #ifndef __HAVE_STDIO_H #include <stdio.h> #define __HAVE_STDIO_H #endif #define INBUFFER_CONST 2048 #define BUFFER_CONST 1024 class QUANTAnet_perfMonitor_c; /** A class to load files from WEB servers. * * This is a class to grab a file off a WEB site depending on * whether the local cached version is older than the remote one. * Begin by creating a webget object. Using the accessor functions, * assign to it the remote WEB address, * path and file. Then assign the local path and file. * Call SetMode to choose the operation you wish. * Finally call GrabWEBFile and check the return status. * * @author (C) 1997 Jason Leigh. * @version 4/1/97. */ class QUANTAnet_http_c { public: /// SetMode flags. //@{ /// Autoload from WEB page checking local cached file. static const int AUTO_LOAD/* = 0*/; /// Check the status of WEB page. static const int CHECK_BUT_DONT_LOAD/* = 3*/; /// Force a load from the WEB page ignoring the cache. static const int FORCED_LOAD/* = 1*/; //@} /// Turn timeout off when loading from WEB page. static const int NO_TIME_OUT/* = -1*/; QUANTAnet_http_c(){ itsMode = AUTO_LOAD; timeOutPeriod =NO_TIME_OUT; } virtual ~QUANTAnet_http_c() {} /// Set the timeout period during WEB page loading. void setTimeOut(int timep) {timeOutPeriod = timep;} /// Accessor functions. //@{ /// Set the IP address of remote site. void setRemoteSite(char *site); /// Set the path from the remote site. void setRemotePath(char *path); /// Set the remote file to download. void setRemoteFile(char *file); /// Set the local path to store downloaded file. void setLocalPath(char *path); /// Set the local file to store downloaded file. void setLocalFile(char *file); /** Set download mode. @param mode Set to either AUTO LOAD, FORCED LOAD or CHECK BUT DONT LOAD. @see SetMode Flags. */ void setMode(int mode) {itsMode = mode;} /// Get timeout period. int getTimeOut() {return timeOutPeriod;} /// Counterpart of SetRemoteSite. char* getRemoteSite() {return remoteSite;} /// Counterpart of SetRemotePath. char* getRemotePath() {return remotePath;} /// Counterpart of SetRemoteFile. char* getRemoteFile() {return remoteFile;} /// Counterpart of SetLocalPath. char* getLocalPath() {return localPath;} /// Counterpart of GetLocalFile. char* getLocalFile() {return localFile;} /// Counterpart of SetMode. int getMode() { return itsMode;} //@} // site = WEB IP address // path = path to where to grab the file (no leading or trailing / needed) // filename = name of file to grab. // localPath = local path to store the file (no trailing / needed) // localFile = local filename // Set timeout to -1 for no timeout else timeout is in seconds /** Grab the WEB file. * Mode of grab is determined by SetMode method. * @return 200 if modified and downloaded ok. * -1 if timed out but cache file exists. * -11 if timed out but cache file DOES NOT exist. * -2 if cannot connect. * -3 if get of file successful but rename of tmpfile failed. * -4 if unable to write to local file. * -5 if modified : only for CHECK_BUT_DONT_LOAD mode. * -6 if unable to get the content length of the remote file. * else returns WEB status numbers. * e.g. 304 is file not modified. * 404 is file not found. */ int grabWEBFile(); //Functions added for performance monitoring interface /** Displays the resultant statistics instantaneously in the netlogger format - this should be typically done after a read/write is done a network. Also, it should be noted that a showStats call should be made at the end of atleast one send and receive for two-way information (the same applies for logStats and sendStats) @param streamInfo A label describing the stream that is being monitored. @param comment A comment on the event that marks the time at which the stream is being monitored */ void showStats(char* streamInfo, char* comment); /** This logs performance statistics in a file. The user opens a file and passes the file pointer with this function and results of monitoring are written into the logfile. @param streamInfo A label describing the stream that is being monitored. @param comment A comment on the event that marks the time at which the stream is being monitored @param filePtr File pointer to the file in which the results of monitoring are to be stored @return Either QUANTAnet_perfMonitor_c::OK or QUANTAnet_perfMonitor_c::FAILED */ int logStats(char* streamInfo, char* comment, FILE* filePtr); /** Sends the performance statistics to a remote perfdaemon -for further analysis of the monitored data - the initSendStats API should be called first, before calling a sendStats (In order to connect to the perfdaemon initially) @param streamInfo A label describing the stream that is being monitored. @param comment A comment on the event that marks the time at which the stream is being monitored @return Either QUANTAnet_perfMonitor_c::OK or QUANTAnet_perfMonitor_c::FAILED */ int sendStats(char* streamInfo, char* comment); /** Initialize sendStats - provide the IP of the perfDaemon and an optional port number to connect to. This should be done initially before using the sendStats API. @param monitorClientIP IP address of the perfDameon to connect to @param port Port number at which the perfDaemon is running -this is optional. The default port number for perfDaemon is 9500 -so a different port number has to be specified if the perfDaemon is running ona different port. @return Either QUANTAnet_perfMonitor_c::OK or QUANTAnet_perfMonitor_c::FAILED */ int initSendStats(char* monitorClientIP, int port = PERF_DAEMON_DEFAULT_PORT); /** Properly delete the perFDaemon Client after sendStats is done */ void exitSendStats(); private: // static const int OUTBUFFER = 512; static const int INBUFFER/* = 2048*/; #ifndef WIN32 // Windows provides a macro function min already... int min(int a, int b) { if (a < b) return a; else return b; } #endif int timeDateOfFile(char* filename, char *out, int *date, int *month, int *year, int *hour, int *minute, int *second); char sendBuffer[INBUFFER_CONST]; char receiveBuffer[INBUFFER_CONST]; static const int BUFFER/* = 1024*/; char remoteSite[BUFFER_CONST]; char remotePath[BUFFER_CONST]; char remoteFile[BUFFER_CONST]; char localPath[BUFFER_CONST]; char localFile[BUFFER_CONST]; int timeOutPeriod; int itsMode; //For performance monitoring calculations QUANTAnet_perfMonitor_c pmonitor; // Search for a string in an array of strings and return the index count. // Return -1 if not found. int indexIntoString(char **strlist, int len, char *searchstr); // If date 1 < date 2 return -1. // If date 1 > date 2 return 1. // If date 1 == date 2 return 0. int compareDate(int date1, int month1, int year1, int hour1, int minute1, int second1, int date2, int month2, int year2, int hour2, int minute2, int second2); // Given a HTTP 1.0 Date string convert it into component values. int webDateConvert(char *instring, int *date, int *month, int *year, int *hour, int *minute, int *second); }; #endif
31.538194
233
0.670593
[ "object" ]
0518753ad748e129f509e547ff5da309559d6618
2,631
hpp
C++
graphics/src/higanbana/graphics/common/allocators.hpp
jgavert/FazE
7cf63655869c285a7e5ca8f5a48f296d9548bd6c
[ "MIT" ]
15
2020-01-15T13:04:36.000Z
2022-02-18T17:08:25.000Z
graphics/src/higanbana/graphics/common/allocators.hpp
jgavert/FazE
7cf63655869c285a7e5ca8f5a48f296d9548bd6c
[ "MIT" ]
3
2015-09-09T08:16:30.000Z
2015-11-24T16:22:48.000Z
graphics/src/higanbana/graphics/common/allocators.hpp
jgavert/FazE
7cf63655869c285a7e5ca8f5a48f296d9548bd6c
[ "MIT" ]
1
2021-12-06T07:19:05.000Z
2021-12-06T07:19:05.000Z
#pragma once #include <higanbana/core/datastructures/vector.hpp> #include <higanbana/core/global_debug.hpp> #include <higanbana/core/math/utils.hpp> #include <memory> namespace higanbana { class LinearMemoryAllocator { private: std::unique_ptr<uint8_t[]> m_data; size_t m_current; size_t m_size; inline uintptr_t privateAlloc(size_t size) { int64_t alignedCurrent = static_cast<int64_t>(roundUpMultiplePowerOf2(m_current, 16ull)); HIGAN_ASSERT(alignedCurrent + size < m_size, "No space in allocator"); if (size == 0) return 0; m_current = alignedCurrent + size; return reinterpret_cast<uintptr_t>(&m_data[alignedCurrent]); } public: LinearMemoryAllocator(size_t size) : m_data(std::make_unique<uint8_t[]>(size)) , m_current(0) , m_size(size) {} template <typename T> inline T* alloc() { return reinterpret_cast<T*>(privateAlloc(sizeof(T))); } template <typename T> inline T* allocList(size_t count) { return reinterpret_cast<T*>(privateAlloc(sizeof(T)*count)); } inline void reset() { m_current = 0; } }; class LinearAllocator { private: int64_t m_current = -1; int64_t m_size = -1; public: LinearAllocator() {} LinearAllocator(size_t size) : m_current(0) , m_size(static_cast<int64_t>(size)) {} inline int64_t allocate(size_t size, size_t alignment = 1) { int64_t alignedCurrent = roundUpMultipleInt(m_current, alignment); if (alignedCurrent + static_cast<int64_t>(size) > m_size) { return -1; } m_current = alignedCurrent + static_cast<int64_t>(size); return alignedCurrent; } inline void resize(int64_t size) { m_size = size; } inline void reset() { m_current = 0; } size_t size() const noexcept { return m_current; } size_t max_size() const noexcept { return m_size; } }; class FreelistAllocator { vector<int> m_freelist; int m_size = 0; public: FreelistAllocator() {} inline void grow() { m_freelist.emplace_back(m_size++); } inline int allocate() { if (m_freelist.empty()) { return -1; } auto ret = m_freelist.back(); m_freelist.pop_back(); return ret; } inline void release(int val) { HIGAN_ASSERT(static_cast<int>(m_freelist.size()) != m_size && val >= 0 && val < m_size, "freelist already full, is this valid?"); m_freelist.push_back(val); } }; }
20.554688
94
0.612315
[ "vector" ]
051d74392bcd4f11c8c2bc9bdf205bdd363b226d
4,622
hpp
C++
worker/include/RTC/RTCP/SenderReport.hpp
liwf616/mediasoup
99d1c696bd4b985ea8bf5348b7f520998e165c32
[ "ISC" ]
2
2020-09-03T01:37:57.000Z
2020-09-03T01:38:15.000Z
worker/include/RTC/RTCP/SenderReport.hpp
liwf616/mediasoup
99d1c696bd4b985ea8bf5348b7f520998e165c32
[ "ISC" ]
1
2021-08-24T01:39:43.000Z
2021-08-24T01:39:43.000Z
worker/include/RTC/RTCP/SenderReport.hpp
baiyfcu/mediasoup
fede86766ad87b184ef139dfe631b30a82506451
[ "0BSD" ]
1
2019-05-14T06:50:04.000Z
2019-05-14T06:50:04.000Z
#ifndef MS_RTC_RTCP_SENDER_REPORT_HPP #define MS_RTC_RTCP_SENDER_REPORT_HPP #include "common.hpp" #include "RTC/RTCP/Packet.hpp" #include <vector> namespace RTC { namespace RTCP { class SenderReport { public: /* Struct for RTCP sender report. */ struct Header { uint32_t ssrc; uint32_t ntpSec; uint32_t ntpFrac; uint32_t rtpTs; uint32_t packetCount; uint32_t octetCount; }; public: static SenderReport* Parse(const uint8_t* data, size_t len); public: // Parsed Report. Points to an external data. explicit SenderReport(Header* header); explicit SenderReport(SenderReport* report); // Locally generated Report. Holds the data internally. SenderReport(); void Dump() const; size_t Serialize(uint8_t* buffer); size_t GetSize() const; uint32_t GetSsrc() const; void SetSsrc(uint32_t ssrc); uint32_t GetNtpSec() const; void SetNtpSec(uint32_t ntpSec); uint32_t GetNtpFrac() const; void SetNtpFrac(uint32_t ntpFrac); uint32_t GetRtpTs() const; void SetRtpTs(uint32_t rtpTs); uint32_t GetPacketCount() const; void SetPacketCount(uint32_t packetCount); uint32_t GetOctetCount() const; void SetOctetCount(uint32_t octetCount); private: Header* header{ nullptr }; uint8_t raw[sizeof(Header)]{ 0 }; }; class SenderReportPacket : public Packet { public: using Iterator = std::vector<SenderReport*>::iterator; public: static SenderReportPacket* Parse(const uint8_t* data, size_t len); public: SenderReportPacket(); ~SenderReportPacket() override; void AddReport(SenderReport* report); Iterator Begin(); Iterator End(); /* Pure virtual methods inherited from Packet. */ public: void Dump() const override; size_t Serialize(uint8_t* buffer) override; size_t GetCount() const override; size_t GetSize() const override; private: std::vector<SenderReport*> reports; }; /* Inline instance methods. */ inline SenderReport::SenderReport() { this->header = reinterpret_cast<Header*>(this->raw); } inline SenderReport::SenderReport(Header* header) : header(header) { } inline SenderReport::SenderReport(SenderReport* report) : header(report->header) { } inline size_t SenderReport::GetSize() const { return sizeof(Header); } inline uint32_t SenderReport::GetSsrc() const { return uint32_t{ ntohl(this->header->ssrc) }; } inline void SenderReport::SetSsrc(uint32_t ssrc) { this->header->ssrc = uint32_t{ htonl(ssrc) }; } inline uint32_t SenderReport::GetNtpSec() const { return uint32_t{ ntohl(this->header->ntpSec) }; } inline void SenderReport::SetNtpSec(uint32_t ntpSec) { this->header->ntpSec = uint32_t{ htonl(ntpSec) }; } inline uint32_t SenderReport::GetNtpFrac() const { return uint32_t{ ntohl(this->header->ntpFrac) }; } inline void SenderReport::SetNtpFrac(uint32_t ntpFrac) { this->header->ntpFrac = uint32_t{ htonl(ntpFrac) }; } inline uint32_t SenderReport::GetRtpTs() const { return uint32_t{ ntohl(this->header->rtpTs) }; } inline void SenderReport::SetRtpTs(uint32_t rtpTs) { this->header->rtpTs = uint32_t{ htonl(rtpTs) }; } inline uint32_t SenderReport::GetPacketCount() const { return uint32_t{ ntohl(this->header->packetCount) }; } inline void SenderReport::SetPacketCount(uint32_t packetCount) { this->header->packetCount = uint32_t{ htonl(packetCount) }; } inline uint32_t SenderReport::GetOctetCount() const { return uint32_t{ ntohl(this->header->octetCount) }; } inline void SenderReport::SetOctetCount(uint32_t octetCount) { this->header->octetCount = uint32_t{ htonl(octetCount) }; } /* Inline instance methods. */ inline SenderReportPacket::SenderReportPacket() : Packet(Type::SR) { } inline SenderReportPacket::~SenderReportPacket() { for (auto* report : this->reports) { delete report; } } inline size_t SenderReportPacket::GetCount() const { return 0; } inline size_t SenderReportPacket::GetSize() const { size_t size = sizeof(Packet::CommonHeader); for (auto* report : this->reports) { size += report->GetSize(); } return size; } inline void SenderReportPacket::AddReport(SenderReport* report) { this->reports.push_back(report); } inline SenderReportPacket::Iterator SenderReportPacket::Begin() { return this->reports.begin(); } inline SenderReportPacket::Iterator SenderReportPacket::End() { return this->reports.end(); } } // namespace RTCP } // namespace RTC #endif
21.598131
82
0.693206
[ "vector" ]
051e2e194b997719d2634baee2699af42bd4790e
382
cpp
C++
4. Алгоритмы на графах/66.1. Канонический вид (по списку дуг) #3563/[OK]227013.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
19
2018-05-19T16:37:14.000Z
2022-03-23T20:13:43.000Z
4. Алгоритмы на графах/66.1. Канонический вид (по списку дуг) #3563/[OK]227013.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
6
2020-05-07T21:06:48.000Z
2020-06-05T17:52:57.000Z
4. Алгоритмы на графах/66.1. Канонический вид (по списку дуг) #3563/[OK]227013.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
31
2019-03-01T21:41:38.000Z
2022-03-27T17:56:39.000Z
#include<iostream> #include<fstream> #include<vector> using namespace std; int main() { ifstream in("input.txt"); ofstream out("output.txt"); int n; in >> n; vector<int>tree(n,0); for (int i = 0; i < n-1; ++i) { int v1, v2; in >> v1 >> v2; tree[v2 - 1] = v1; } for (int i = 0; i < n; ++i) { out << tree[i] << ' '; } return 0; }
13.642857
33
0.486911
[ "vector" ]
05259a71df5f7738a1de4d24e467fd414aa7d531
5,712
cpp
C++
src/linux_parser.cpp
migzss/Solution-CppND-System-Monitor
e06e2baa815509c472600a9ccf3c7b938b24d2dc
[ "MIT" ]
null
null
null
src/linux_parser.cpp
migzss/Solution-CppND-System-Monitor
e06e2baa815509c472600a9ccf3c7b938b24d2dc
[ "MIT" ]
null
null
null
src/linux_parser.cpp
migzss/Solution-CppND-System-Monitor
e06e2baa815509c472600a9ccf3c7b938b24d2dc
[ "MIT" ]
null
null
null
#include <dirent.h> #include <unistd.h> #include <string> #include <vector> #include "../include/linux_parser.h" using std::stof; using std::string; using std::to_string; using std::vector; // DONE: An example of how to read data from the filesystem string LinuxParser::OperatingSystem() { string line; string key; string value; std::ifstream filestream(kOSPath); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), ' ', '_'); std::replace(line.begin(), line.end(), '=', ' '); std::replace(line.begin(), line.end(), '"', ' '); std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "PRETTY_NAME") { std::replace(value.begin(), value.end(), '_', ' '); return value; } } } } return value; } // DONE: An example of how to read data from the filesystem string LinuxParser::Kernel() { string os, versionText, kernel; string line; std::ifstream stream(kProcDirectory + kVersionFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> os >> versionText >> kernel; } return kernel; } // BONUS: Update this to use std::filesystem vector<int> LinuxParser::Pids() { vector<int> pids; DIR* directory = opendir(kProcDirectory.c_str()); struct dirent* file; while ((file = readdir(directory)) != nullptr) { // Is this a directory? if (file->d_type == DT_DIR) { // Is every character of the name a digit? string filename(file->d_name); if (std::all_of(filename.begin(), filename.end(), isdigit)) { int pid = stoi(filename); pids.push_back(pid); } } } closedir(directory); return pids; } // Read and return the system memory utilization float LinuxParser::MemoryUtilization() { string line; float memutil = 0.f; float memTotal = 0.f; float memFree = 0.f; string key; string value; std::ifstream filestream(kProcDirectory + kMeminfoFilename); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), ':', ' '); std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "MemTotal") { memTotal = stof(value); break; } else if (key == "MemFree") { memFree = stof(value); break; } } if (memTotal > 0 && memFree > 0) break; } // memory usage memutil = (memTotal - memFree) / memTotal; } return memutil; } // Read and return the system uptime long LinuxParser::UpTime() { std::string line, first, second; long uptime = 0; std::ifstream filestream(kProcDirectory + kUptimeFilename); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::istringstream linestream(line); while (linestream >> first >> second) { uptime = static_cast<long>(std::stof(first)); break; } } } return uptime; } // TODO: Read and return the number of jiffies for the system long LinuxParser::Jiffies() { return 0; } // TODO: Read and return the number of active jiffies for a PID // REMOVE: [[maybe_unused]] once you define the function long LinuxParser::ActiveJiffies(int pid[[maybe_unused]]) { return 0; } // TODO: Read and return the number of active jiffies for the system long LinuxParser::ActiveJiffies() { return 0; } // TODO: Read and return the number of idle jiffies for the system long LinuxParser::IdleJiffies() { return 0; } // TODO: Read and return CPU utilization vector<string> LinuxParser::CpuUtilization() { return {}; } // Read and return the total number of processes int LinuxParser::TotalProcesses() { string strProcessCount; string processes, line; int processCount = 0; std::ifstream stream(kProcDirectory + kStatFilename); if (stream.is_open()) { while (std::getline(stream, line)) { std::istringstream linestream(line); linestream >> processes >> strProcessCount; if (processes == "processes") { processCount = std::stoi(strProcessCount); break; } } } return processCount; } // Read and return the number of running processes int LinuxParser::RunningProcesses() { string strProcessCount; string procs_running, line; int processCount = 0; std::ifstream stream(kProcDirectory + kStatFilename); if (stream.is_open()) { while (std::getline(stream, line)) { std::istringstream linestream(line); linestream >> procs_running >> strProcessCount; if (procs_running == "procs_running") { processCount = std::stoi(strProcessCount); break; } } } return processCount; } // TODO: Read and return the command associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::Command(int pid[[maybe_unused]]) { return string(); } // TODO: Read and return the memory used by a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::Ram(int pid[[maybe_unused]]) { return string(); } // TODO: Read and return the user ID associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::Uid(int pid[[maybe_unused]]) { return string(); } // TODO: Read and return the user associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::User(int pid[[maybe_unused]]) { return string(); } // TODO: Read and return the uptime of a process // REMOVE: [[maybe_unused]] once you define the function long LinuxParser::UpTime(int pid[[maybe_unused]]) { return 0; }
29.75
73
0.655462
[ "vector" ]
052c41312acb8d01b312f6ddca33f2576eb36cca
1,454
cc
C++
libulti/rules.cc
gyorgy/ulti
de7d23663fbd9b1d80da27056531fe3d179d87bd
[ "MIT" ]
null
null
null
libulti/rules.cc
gyorgy/ulti
de7d23663fbd9b1d80da27056531fe3d179d87bd
[ "MIT" ]
null
null
null
libulti/rules.cc
gyorgy/ulti
de7d23663fbd9b1d80da27056531fe3d179d87bd
[ "MIT" ]
null
null
null
// Copyright (c) 2017 Gyorgy Abonyi. All rights reserved. #include <libulti/rules.h> #include <libulti/bids.h> namespace ulti { Rules::Rules() : bids_(Bids::PASS), trump_(Cards::Suit::TRUMPLESS) {} void Rules::SetBid(const Bids& bids, Cards::Suit trump) { bids_ = bids; trump_ = trump; } int Rules::GetTaker(int calling_player, const std::vector<Cards>& calls) const { const Cards::Suit called_suit = calls[0].GetSuit(); int taker = 0; Cards taking_card = calls[0]; for (int i = 1; i < 3; ++i) { if (IsBeating(called_suit, taking_card, calls[i])) { taker = i; taking_card = calls[i]; } } return (calling_player + taker) % 3; } Cards Rules::GetValidCalls(const Cards& hand, const std::vector<Cards>& calls) const { // TODO(gyorgy): Implement it. return hand; } bool Rules::IsBeating(Cards::Suit called_suit, const Cards &current_best, const Cards &card) const { const Cards::Suit suit = card.GetSuit(); if (suit != called_suit && suit != trump_) { return false; } const Cards::Suit best_suit = current_best.GetSuit(); if (best_suit == trump_ && suit != trump_) { return false; } if (called_suit != trump_ && best_suit != trump_ && suit == trump_) { return true; } if (best_suit == trump_ && suit == trump_) { return card.IsBeating(current_best); } return HasTrump() ? card.IsBeating(current_best) : card.IsBeatingTrumpless(current_best); } } // namespace ulti
25.964286
100
0.656809
[ "vector" ]
052c82e90a43fb2e6ca33a2b388a1d30aea15dbe
5,206
cpp
C++
thread_pool/best_version.cpp
skprpi/Habr
a0c63dc78d82fcb04c2b4c9fec57511104a1b41a
[ "MIT" ]
1
2022-03-28T23:46:20.000Z
2022-03-28T23:46:20.000Z
thread_pool/best_version.cpp
skprpi/Habr
a0c63dc78d82fcb04c2b4c9fec57511104a1b41a
[ "MIT" ]
null
null
null
thread_pool/best_version.cpp
skprpi/Habr
a0c63dc78d82fcb04c2b4c9fec57511104a1b41a
[ "MIT" ]
null
null
null
#include <iostream> #include <queue> #include <thread> #include <chrono> #include <mutex> #include <future> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <any> #include <atomic> #include <variant> #include <cassert> #include <map> #include <utility> enum class TaskStatus { in_q, completed }; // C++ 17 class Task { public: template <typename FuncRetType, typename ...Args, typename ...FuncTypes> Task(FuncRetType(*func)(FuncTypes...), Args&&... args) : is_void{ std::is_void_v<FuncRetType> } { if constexpr (std::is_void_v<FuncRetType>) { void_func = std::bind(func, args...); any_func = []()->int { return 0; }; } else { void_func = []()->void {}; any_func = std::bind(func, args...); } } void operator() () { void_func(); any_func_result = any_func(); } bool has_result() { return !is_void; } std::any get_result() const { assert(!is_void); assert(any_func_result.has_value()); return any_func_result; } private: std::function<void()> void_func; std::function<std::any()> any_func; std::any any_func_result; bool is_void; }; struct TaskInfo { TaskStatus status = TaskStatus::in_q; std::any result; }; class thread_pool { public: thread_pool(const uint32_t num_threads) { threads.reserve(num_threads); for (int i = 0; i < num_threads; ++i) { threads.emplace_back(&thread_pool::run, this); } } template <typename Func, typename ...Args, typename ...FuncTypes> uint64_t add_task(Func(*func)(FuncTypes...), Args&&... args) { const uint64_t task_id = last_idx++; std::unique_lock<std::mutex> lock(tasks_info_mtx); tasks_info[task_id] = TaskInfo(); lock.unlock(); std::lock_guard<std::mutex> q_lock(q_mtx); q.emplace(Task(func, std::forward<Args>(args)...), task_id); q_cv.notify_one(); return task_id; } void wait(const uint64_t task_id) { std::unique_lock<std::mutex> lock(tasks_info_mtx); tasks_info_cv.wait(lock, [this, task_id]()->bool { return task_id < last_idx&& tasks_info[task_id].status == TaskStatus::completed; }); } std::any wait_result(const uint64_t task_id) { wait(task_id); return tasks_info[task_id].result; } template<class T> void wait_result(const uint64_t task_id, T& value) { wait(task_id); value = std::any_cast<T>(tasks_info[task_id].result); } void wait_all() { std::unique_lock<std::mutex> lock(tasks_info_mtx); wait_all_cv.wait(lock, [this]()->bool { return cnt_completed_tasks == last_idx; }); } bool calculated(const uint64_t task_id) { std::lock_guard<std::mutex> lock(tasks_info_mtx); return task_id < last_idx&& tasks_info[task_id].status == TaskStatus::completed; } ~thread_pool() { quite = true; q_cv.notify_all(); for (int i = 0; i < threads.size(); ++i) { threads[i].join(); } } private: void run() { while (!quite) { std::unique_lock<std::mutex> lock(q_mtx); q_cv.wait(lock, [this]()->bool { return !q.empty() || quite; }); if (!q.empty() && !quite) { std::pair<Task, uint64_t> task = std::move(q.front()); q.pop(); lock.unlock(); task.first(); std::lock_guard<std::mutex> lock(tasks_info_mtx); if (task.first.has_result()) { tasks_info[task.second].result = task.first.get_result(); } tasks_info[task.second].status = TaskStatus::completed; ++cnt_completed_tasks; } wait_all_cv.notify_all(); tasks_info_cv.notify_all(); // notify for wait function } } std::vector<std::thread> threads; std::queue<std::pair<Task, uint64_t>> q; std::mutex q_mtx; std::condition_variable q_cv; std::unordered_map<uint64_t, TaskInfo> tasks_info; std::condition_variable tasks_info_cv; std::mutex tasks_info_mtx; std::condition_variable wait_all_cv; std::atomic<bool> quite{ false }; std::atomic<uint64_t> last_idx{ 0 }; std::atomic<uint64_t> cnt_completed_tasks{ 0 }; }; int int_sum(int a, int b) { return a + b; } void void_sum(int& c, int a, int b) { c = a + b; } void void_without_argument() { std::cout << "It's OK!" << std::endl; } int main() { thread_pool t(3); int c; t.add_task(int_sum, 2, 3); // id = 0 t.add_task(void_sum, std::ref(c), 4, 6); // id = 1 t.add_task(void_without_argument); // id = 2 { // variant 1 int res; t.wait_result(0, res); std::cout << res << std::endl; // variant 2 std::cout << std::any_cast<int>(t.wait_result(0)) << std::endl; } t.wait(1); std::cout << c << std::endl; t.wait_all(); // waiting for task with id 2 return 0; }
25.149758
92
0.568575
[ "vector" ]
05318ad8b9c23ab08b3dc3b8ab721020d3c9100a
7,018
cpp
C++
Odyssey/OdysseyVulkanCore/OdysseyVulkanCore/Initialize/BaseClasses/QueueFamily.cpp
paulburgess1357/Odyssey
ad351d1df7eeb1b4223ffbdf91ec7e3307b87983
[ "MIT" ]
1
2022-03-10T02:45:04.000Z
2022-03-10T02:45:04.000Z
Odyssey/OdysseyVulkanCore/OdysseyVulkanCore/Initialize/BaseClasses/QueueFamily.cpp
paulburgess1357/Odyssey
ad351d1df7eeb1b4223ffbdf91ec7e3307b87983
[ "MIT" ]
null
null
null
Odyssey/OdysseyVulkanCore/OdysseyVulkanCore/Initialize/BaseClasses/QueueFamily.cpp
paulburgess1357/Odyssey
ad351d1df7eeb1b4223ffbdf91ec7e3307b87983
[ "MIT" ]
null
null
null
#include "OdysseyVulkanCore/OdysseyVulkanCore/Initialize/BaseClasses/QueueFamily.h" #include "OdysseyVulkanCore/OdysseyVulkanCore/Initialize/Exceptions.h" #include "OdysseyUtility/OdysseyUtility/Logging/Logger.h" #include <unordered_set> #include <ranges> // ReSharper disable CppParameterMayBeConst namespace OdysseyVulkanCore::Initialize { QueueFamily::QueueFamily(VkPhysicalDevice vk_physical_device, VkSurfaceKHR vk_surface) { initialize(vk_physical_device, vk_surface); } void QueueFamily::initialize(VkPhysicalDevice vk_physical_device, VkSurfaceKHR vk_surface) { set_queue_families(vk_physical_device); fill_indices_map(vk_physical_device, vk_surface); check_map_indices(); } void QueueFamily::set_queue_families(VkPhysicalDevice vk_physical_device) { uint32_t queue_family_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(vk_physical_device, &queue_family_count, nullptr); std::vector<VkQueueFamilyProperties> vk_queue_families(queue_family_count); vkGetPhysicalDeviceQueueFamilyProperties(vk_physical_device, &queue_family_count, vk_queue_families.data()); m_vk_queue_families = vk_queue_families; } void QueueFamily::fill_indices_map(VkPhysicalDevice vk_physical_device, VkSurfaceKHR vk_surface) { // Iterate over all required criteria. If criteria is met, set the index // of the queue family that supports that criteria. It's not required for // a single queue to support all criteria. Multiple queues can be used. uint32_t queue_family_index{0}; for (const auto& family : m_vk_queue_families) { set_graphics_index(family, queue_family_index); set_presentation_index(vk_physical_device, vk_surface, queue_family_index); set_transfer_index(family, queue_family_index); ++queue_family_index; } } void QueueFamily::set_graphics_index(const VkQueueFamilyProperties& vk_family, const uint32_t index) { if (!m_queue_family_indices.contains(Enums::FamilyType::GRAPHICS)) { if (vk_family.queueFlags & VK_QUEUE_GRAPHICS_BIT) { m_queue_family_indices[Enums::FamilyType::GRAPHICS] = index; } } } void QueueFamily::set_presentation_index(VkPhysicalDevice vk_physical_device, VkSurfaceKHR vk_surface, const uint32_t index) { if (!m_queue_family_indices.contains(Enums::FamilyType::PRESENTATION)) { VkBool32 presentation_support{false}; vkGetPhysicalDeviceSurfaceSupportKHR(vk_physical_device, index, vk_surface, &presentation_support); if (presentation_support) { m_queue_family_indices[Enums::FamilyType::PRESENTATION] = index; } } } void QueueFamily::set_transfer_index(const VkQueueFamilyProperties& vk_family, const uint32_t index) { if (!m_queue_family_indices.contains(Enums::FamilyType::TRANSFER)) { if (!(vk_family.queueFlags & VK_QUEUE_GRAPHICS_BIT)) { if (vk_family.queueFlags & VK_QUEUE_TRANSFER_BIT) { ODYSSEY_TRACE("Dedicated transfer queue located") m_queue_family_indices[Enums::FamilyType::TRANSFER] = index; } } } } void QueueFamily::check_map_indices() const { if (!m_queue_family_indices.contains(Enums::FamilyType::GRAPHICS) || !m_queue_family_indices.contains(Enums::FamilyType::PRESENTATION)) { ODYSSEY_ERROR("The requested queue criteria was not all met") throw Exceptions::QueueSupportException(); } } std::vector<VkDeviceQueueCreateInfo> QueueFamily::vk_infos() const { std::vector<VkDeviceQueueCreateInfo> vk_device_queue_create_infos{}; // Each queue family index must be stored in the queue_create_info. However, // it is possible that a queue family shares multiple requirements: // [Graphics Capability] : Family Index: 0 // [Presentation Capability] : Family Index: 0 // The Vulkan spec requires us to submit the unique queue indices only! const std::vector<uint32_t> unique_indices = unique_unordered_indices(); // Iterate over the unique queue family indices and create 'queue create vk_infos' // for each index for (const auto& queue_family_index : unique_indices) { VkDeviceQueueCreateInfo queue_create_info = {}; queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queue_create_info.queueFamilyIndex = queue_family_index; // # of queues to create within a queue family (This is NOT the size // of the vector we are returning!. This is PER queue family) // For now, only a single queue is created for each family. Since // there is only a single queue for each family the priority is one. queue_create_info.queueCount = static_cast<uint32_t>(m_queue_priority.size()); queue_create_info.pQueuePriorities = m_queue_priority.data(); vk_device_queue_create_infos.emplace_back(queue_create_info); } return vk_device_queue_create_infos; } void QueueFamily::set_handles(VkDevice vk_device) { const auto queue_family_indices = indices(); for (const auto& [family_type, queue_index] : queue_family_indices) { m_vk_queue_handles[family_type] = VkQueue{}; // The '0' refers to the queue within the queue family to retrieve. For now, // each queue family only has one queue (so the index is 0). // See: QueueFamily::vk_infos() for additional information // on the single queue per family vkGetDeviceQueue(vk_device, queue_index, 0, &m_vk_queue_handles[family_type]); } } std::unordered_map<Enums::FamilyType, uint32_t> QueueFamily::indices() const { return m_queue_family_indices; } std::unordered_map<Enums::FamilyType, VkQueue> QueueFamily::vk_handles() const { return m_vk_queue_handles; } uint32_t QueueFamily::index(Enums::FamilyType queue_family_type) const { return m_queue_family_indices.at(queue_family_type); } VkQueue QueueFamily::vk_handle(Enums::FamilyType queue_family_type) const { return m_vk_queue_handles.at(queue_family_type); } std::vector<uint32_t> QueueFamily::unique_unordered_indices() const { // Return vector of unique queue indices. Keep in mind // that a set is being used so the result is not ordered!! std::unordered_set<uint32_t> unique_indices_set; for (const auto& queue_index : m_queue_family_indices | std::views::values) { unique_indices_set.insert(queue_index); } std::vector<uint32_t> unique_indices_vec; unique_indices_vec.reserve(unique_indices_set.size()); for (const auto& index : unique_indices_set) { unique_indices_vec.push_back(index); } return unique_indices_vec; } std::vector<uint32_t> QueueFamily::unique_unordered_indices(const std::vector<Enums::FamilyType>& family_types) const { std::unordered_set<uint32_t> unique_indices_set; for (const auto& type : family_types) { if (m_queue_family_indices.contains(type)) { unique_indices_set.insert(m_queue_family_indices.at(type)); } } std::vector<uint32_t> unique_indices_vec; unique_indices_vec.reserve(unique_indices_set.size()); for (const auto& index : unique_indices_set) { unique_indices_vec.push_back(index); } return unique_indices_vec; } } // namespace OdysseyVulkanCore::Initialize
41.282353
119
0.77173
[ "vector" ]
0531c440cf9db2777f3eba51ddca6916d3b3dba3
82
cpp
C++
vm/mterp/c/OP_SGET_OBJECT_JUMBO.cpp
ThirdProject/android_dalvik
6a9739380c73a0256f2484f2bcd0b8f908a2db52
[ "Apache-2.0" ]
null
null
null
vm/mterp/c/OP_SGET_OBJECT_JUMBO.cpp
ThirdProject/android_dalvik
6a9739380c73a0256f2484f2bcd0b8f908a2db52
[ "Apache-2.0" ]
null
null
null
vm/mterp/c/OP_SGET_OBJECT_JUMBO.cpp
ThirdProject/android_dalvik
6a9739380c73a0256f2484f2bcd0b8f908a2db52
[ "Apache-2.0" ]
null
null
null
HANDLE_SGET_X_JUMBO(OP_SGET_OBJECT_JUMBO, "-object", Object, _AS_OBJECT) OP_END
27.333333
74
0.817073
[ "object" ]
05358b410465fd8fb1fbbf8259b7e65274d79d8d
4,379
cpp
C++
src/mongo/db/storage/mmap_v1/extent.cpp
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
4
2018-02-06T01:53:12.000Z
2018-02-20T01:47:36.000Z
src/mongo/db/storage/mmap_v1/extent.cpp
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
null
null
null
src/mongo/db/storage/mmap_v1/extent.cpp
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
3
2018-02-06T01:53:18.000Z
2021-07-28T09:48:15.000Z
// extent.cpp /** * Copyright (C) 2013 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/db/storage/mmap_v1/extent.h" #include "mongo/base/static_assert.h" #include "mongo/db/storage/mmap_v1/extent_manager.h" #include "mongo/util/hex.h" #include "mongo/util/mongoutils/str.h" namespace mongo { using std::iostream; using std::string; using std::vector; MONGO_STATIC_ASSERT(sizeof(Extent) - 4 == 48 + 128); BSONObj Extent::dump() const { return BSON("loc" << myLoc.toString() << "xnext" << xnext.toString() << "xprev" << xprev.toString() << "nsdiag" << nsDiagnostic.toString() << "size" << length << "firstRecord" << firstRecord.toString() << "lastRecord" << lastRecord.toString()); } void Extent::dump(iostream& s) const { s << " loc:" << myLoc.toString() << " xnext:" << xnext.toString() << " xprev:" << xprev.toString() << '\n'; s << " nsdiag:" << nsDiagnostic.toString() << '\n'; s << " size:" << length << " firstRecord:" << firstRecord.toString() << " lastRecord:" << lastRecord.toString() << '\n'; } bool Extent::validates(const DiskLoc diskLoc, vector<string>* errors) const { bool extentOk = true; if (magic != extentSignature) { if (errors) { StringBuilder sb; sb << "bad extent signature " << integerToHex(magic) << " in extent " << diskLoc.toString(); errors->push_back(sb.str()); } extentOk = false; } if (myLoc != diskLoc) { if (errors) { StringBuilder sb; sb << "extent " << diskLoc.toString() << " self-pointer is " << myLoc.toString(); errors->push_back(sb.str()); } extentOk = false; } if (firstRecord.isNull() != lastRecord.isNull()) { if (errors) { StringBuilder sb; if (firstRecord.isNull()) { sb << "in extent " << diskLoc.toString() << ", firstRecord is null but lastRecord is " << lastRecord.toString(); } else { sb << "in extent " << diskLoc.toString() << ", firstRecord is " << firstRecord.toString() << " but lastRecord is null"; } errors->push_back(sb.str()); } extentOk = false; } static const int minSize = 0x1000; if (length < minSize) { if (errors) { StringBuilder sb; sb << "length of extent " << diskLoc.toString() << " is " << length << ", which is less than minimum length of " << minSize; errors->push_back(sb.str()); } extentOk = false; } return extentOk; } }
38.752212
94
0.57045
[ "vector" ]
05373c426acf2d6ef127184d24ef2f70bd21f6b2
8,589
cc
C++
arc/data-snapshotd/dbus_adaptor.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
arc/data-snapshotd/dbus_adaptor.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
arc/data-snapshotd/dbus_adaptor.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Chromium OS 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 "arc/data-snapshotd/dbus_adaptor.h" #include <utility> #include <vector> #include <base/bind.h> #include <base/callback_helpers.h> #include <base/check.h> #include <base/files/file_util.h> #include <base/logging.h> #include <base/macros.h> #include <base/memory/ptr_util.h> #include <base/strings/string_number_conversions.h> #include <brillo/data_encoding.h> #include <brillo/cryptohome.h> #include <brillo/secure_blob.h> #include <crypto/scoped_openssl_types.h> #include <crypto/rsa_private_key.h> #include "arc/data-snapshotd/file_utils.h" #include "bootlockbox-client/bootlockbox/boot_lockbox_client.h" namespace arc { namespace data_snapshotd { namespace { // Snapshot paths: constexpr char kCommonSnapshotPath[] = "/var/cache/arc-data-snapshot"; constexpr char kLastSnapshotPath[] = "last"; constexpr char kPreviousSnapshotPath[] = "previous"; } // namespace // BootLockbox snapshot keys: const char kLastSnapshotPublicKey[] = "snapshot_public_key_last"; const char kPreviousSnapshotPublicKey[] = "snapshot_public_key_previous"; DBusAdaptor::DBusAdaptor() : DBusAdaptor(base::FilePath(kCommonSnapshotPath), cryptohome::BootLockboxClient::CreateBootLockboxClient(), nullptr) {} DBusAdaptor::~DBusAdaptor() = default; // static std::unique_ptr<DBusAdaptor> DBusAdaptor::CreateForTesting( const base::FilePath& snapshot_directory, std::unique_ptr<cryptohome::BootLockboxClient> boot_lockbox_client, std::unique_ptr<BlockUiController> block_ui_controller) { return base::WrapUnique(new DBusAdaptor(snapshot_directory, std::move(boot_lockbox_client), std::move(block_ui_controller))); } void DBusAdaptor::RegisterAsync( const scoped_refptr<dbus::Bus>& bus, brillo::dbus_utils::AsyncEventSequencer* sequencer) { bus_ = bus; dbus_object_ = std::make_unique<brillo::dbus_utils::DBusObject>( nullptr /* object_manager */, bus, GetObjectPath()); RegisterWithDBusObject(dbus_object_.get()); dbus_object_->RegisterAsync(sequencer->GetHandler( "Failed to register D-Bus object" /* descriptive_message */, true /* failure_is_fatal */)); } bool DBusAdaptor::GenerateKeyPair() { std::string last_public_key_digest; // Try to move last snapshot to previous for consistency. if (base::PathExists(last_snapshot_directory_) && boot_lockbox_client_->Read(kLastSnapshotPublicKey, &last_public_key_digest) && !last_public_key_digest.empty()) { if (boot_lockbox_client_->Store(kPreviousSnapshotPublicKey, last_public_key_digest) && ClearSnapshot(false /* last */) && base::Move(last_snapshot_directory_, previous_snapshot_directory_)) { boot_lockbox_client_->Store(kLastSnapshotPublicKey, ""); } else { LOG(ERROR) << "Failed to move last to previous snapshot."; } } // Clear last snapshot - a new one will be created soon. if (!ClearSnapshot(true /* last */)) return false; // Generate a key pair. public_key_info_.clear(); std::unique_ptr<crypto::RSAPrivateKey> generated_private_key( crypto::RSAPrivateKey::Create(4096)); if (!generated_private_key) { LOG(ERROR) << "Failed to generate a key pair."; return false; } if (!generated_private_key->ExportPublicKey(&public_key_info_)) { LOG(ERROR) << "Failed to export public key"; return false; } // Store a new public key digest. std::string encoded_digest = CalculateEncodedSha256Digest(public_key_info_); if (!boot_lockbox_client_->Store(kLastSnapshotPublicKey, encoded_digest)) { LOG(ERROR) << "Failed to store a public key in BootLockbox."; return false; } // Save private key for later usage. private_key_ = std::move(generated_private_key); // block_ui_controller_ is pre-initialized for tests or if already present. if (!block_ui_controller_) { block_ui_controller_ = std::make_unique<BlockUiController>( std::make_unique<EscKeyWatcher>(this), base::FilePath(kCommonSnapshotPath)); } if (!block_ui_controller_->ShowScreen()) { LOG(ERROR) << "update_arc_data_snapshot failed to be shown"; block_ui_controller_.reset(); return false; } return true; } void DBusAdaptor::TakeSnapshot( std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<bool>> response, const std::string& account_id) { std::vector<uint8_t> private_key_info; if (!private_key_ || !private_key_->ExportPrivateKey(&private_key_info)) { LOG(ERROR) << "Failed to export private key info."; response->Return(false); return; } worker_dbus_bridge_ = WorkerBridge::Create(bus_); std::string encoded_private_key = brillo::data_encoding::Base64Encode( private_key_info.data(), private_key_info.size()); std::string encoded_public_key = brillo::data_encoding::Base64Encode( public_key_info_.data(), public_key_info_.size()); worker_dbus_bridge_->Init( account_id, base::BindOnce(&DBusAdaptor::DelegateTakingSnapshot, weak_ptr_factory_.GetWeakPtr(), account_id, encoded_private_key, encoded_public_key, std::move(response))); // Dispose keys. private_key_.reset(); public_key_info_.clear(); } bool DBusAdaptor::ClearSnapshot(bool last) { base::FilePath dir(last ? last_snapshot_directory_ : previous_snapshot_directory_); if (!base::DirectoryExists(dir)) { LOG(WARNING) << "Snapshot directory is already empty: " << dir.value(); return true; } if (!base::DeletePathRecursively(dir)) { LOG(ERROR) << "Failed to delete snapshot directory: " << dir.value(); return false; } return true; } void DBusAdaptor::LoadSnapshot( std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<bool, bool>> response, const std::string& account_id) { worker_dbus_bridge_ = WorkerBridge::Create(bus_); worker_dbus_bridge_->Init( account_id, base::BindOnce(&DBusAdaptor::DelegateLoadingSnapshot, weak_ptr_factory_.GetWeakPtr(), account_id, std::move(response))); } bool DBusAdaptor::Update(int percent) { if (!block_ui_controller_) { LOG(ERROR) << "Failed to update a progress bar on the UI screen, not shown."; return false; } if (percent < 0 || percent > 100) { LOG(ERROR) << "Percentage must be in [0..100], but passed " << percent; return false; } return block_ui_controller_->UpdateProgress(percent); } void DBusAdaptor::SendCancelSignal() { SendUiCancelledSignal(); } DBusAdaptor::DBusAdaptor( const base::FilePath& snapshot_directory, std::unique_ptr<cryptohome::BootLockboxClient> boot_lockbox_client, std::unique_ptr<BlockUiController> block_ui_controller) : org::chromium::ArcDataSnapshotdAdaptor(this), last_snapshot_directory_(snapshot_directory.Append(kLastSnapshotPath)), previous_snapshot_directory_( snapshot_directory.Append(kPreviousSnapshotPath)), boot_lockbox_client_(std::move(boot_lockbox_client)), block_ui_controller_(std::move(block_ui_controller)) { DCHECK(boot_lockbox_client_); } void DBusAdaptor::DelegateTakingSnapshot( const std::string& account_id, const std::string& encoded_private_key, const std::string& encoded_public_key, std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<bool>> response, bool is_initialized) { DCHECK(worker_dbus_bridge_); if (!is_initialized) { LOG(ERROR) << "Failed to initialize arc-data-snapshotd-worker DBus daemon."; response->Return(false); return; } worker_dbus_bridge_->TakeSnapshot(account_id, encoded_private_key, encoded_public_key, std::move(response)); } void DBusAdaptor::DelegateLoadingSnapshot( const std::string& account_id, std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<bool, bool>> response, bool is_initialized) { DCHECK(worker_dbus_bridge_); if (!is_initialized) { LOG(ERROR) << "Failed to initialize arc-data-snapshotd-worker DBus daemon."; response->Return(false, false); return; } worker_dbus_bridge_->LoadSnapshot(account_id, std::move(response)); } } // namespace data_snapshotd } // namespace arc
35.345679
80
0.700547
[ "object", "vector" ]
053a962ff262e9e9c32d360f153482c2c9eff5ca
3,640
cpp
C++
src/Utils.cpp
LRMPUT/wifiSeq
f6137839b1967075b98758fda1178af55c24048d
[ "BSD-2-Clause" ]
2
2020-10-27T07:03:13.000Z
2020-10-27T10:14:48.000Z
src/Utils.cpp
LRMPUT/wifiSeq
f6137839b1967075b98758fda1178af55c24048d
[ "BSD-2-Clause" ]
null
null
null
src/Utils.cpp
LRMPUT/wifiSeq
f6137839b1967075b98758fda1178af55c24048d
[ "BSD-2-Clause" ]
2
2019-09-23T15:31:33.000Z
2022-02-17T10:28:24.000Z
/* Copyright (c) 2019, Mobile Robots Laboratory: -Jan Wietrzykowski (jan.wietrzykowski@put.poznan.pl). Poznan University of Technology All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cmath> #include <algorithm> #include "Utils.hpp" #include "LocationWifi.hpp" std::pair<int, int> Utils::mapCoordToGrid(double x, double y){ return std::make_pair((x - mapMinX)/mapGrid, (y - mapMinY)/mapGrid); }; LocationXY Utils::mapGridToCoord(int x, int y){ return LocationXY(mapMinX + x * mapGrid, mapMinY + y * mapGrid, -1); }; double Utils::orientIdxToOrient(int oIdx){ return orientSectorLen * oIdx; } int Utils::orientToOrientIdx(double o){ int oIdx = (int)((o + 2 * M_PI + orientSectorLen / 2.0) / orientSectorLen); oIdx = ((oIdx % orientSectors) + orientSectors) % orientSectors; return oIdx; } int Utils::mapGridToVal(int x, int y, int o){ return o + orientSectors * x + orientSectors * mapGridSizeX * y; } void Utils::valToMapGrid(double val, int &xIdx, int &yIdx, int &oIdx){ int valInt = (int)round(val); oIdx = valInt % orientSectors; valInt /= orientSectors; xIdx = valInt % mapGridSizeX; valInt /= mapGridSizeX; yIdx = valInt; } double Utils::toPiRange(double o) { // (- 2 * M_PI, 2 * M_PI) o = fmod(o, 2 * M_PI); // [0, 2 * M_PI) o = fmod(o + 2 * M_PI, 2 * M_PI); if (o > M_PI){ return o - 2 * M_PI; } else { return o; } } double Utils::angDiff(double o1, double o2) { if(std::abs(o1 - o2) <= M_PI ){ return o1 - o2; } else if(o1 - o2 < - M_PI){ return o1 - o2 + 2 * M_PI; } else { return o1 - o2 - 2 * M_PI; } } double Utils::meanOrient(const std::vector<double>::const_iterator &beg, const std::vector<double>::const_iterator &end) { double orientOffsetSin = 0; double orientOffsetCos = 0; int cnt = 0; for(auto it = beg; it != end; ++it){ orientOffsetSin += sin(*it); orientOffsetCos += cos(*it); ++cnt; } // mean using sin and cos orientOffsetSin /= cnt; orientOffsetCos /= cnt; // if not spread uniformly on the circle if(orientOffsetSin*orientOffsetSin + orientOffsetCos*orientOffsetCos > 0.01) { return atan2(orientOffsetSin, orientOffsetCos); } // return middle value else { return *(beg + cnt / 2); } }
31.111111
85
0.675549
[ "vector" ]
053d23991fe1389140c1d892bd73ea9e1f471138
2,380
cpp
C++
tests/test_linalg_blas1.cpp
stigrs/scilib
c49f1f882bf2031a4de537e0f5701b2648af181f
[ "MIT" ]
null
null
null
tests/test_linalg_blas1.cpp
stigrs/scilib
c49f1f882bf2031a4de537e0f5701b2648af181f
[ "MIT" ]
null
null
null
tests/test_linalg_blas1.cpp
stigrs/scilib
c49f1f882bf2031a4de537e0f5701b2648af181f
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Stig Rune Sellevag // // This file is distributed under the MIT License. See the accompanying file // LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms // and conditions. #include <scilib/mdarray.h> #include <scilib/linalg.h> #include <gtest/gtest.h> #include <vector> TEST(TestLinAlg, TestAdd) { std::vector<int> data = {1, 2, 3}; std::vector<int> ans = {2, 4, 6}; Sci::Vector<int> x(data, data.size()); Sci::Vector<int> y(data, data.size()); Sci::Vector<int> z(data.size()); Sci::Linalg::add(x, y, z); for (std::size_t i = 0; i < z.size(); ++i) { EXPECT_EQ(z(i), ans[i]); } } TEST(TestLinalg, TestAbsSum) { Sci::Vector<int> v(std::vector<int>{1, 2, 3, -4}, 4); EXPECT_EQ(Sci::Linalg::abs_sum(v), 10); } TEST(TestLinalg, TestAxpy) { std::vector<int> ans = {4, 8, 12, 16, 20}; Sci::Vector<int> x(std::vector<int>{1, 2, 3, 4, 5}, 5); Sci::Vector<int> y(std::vector<int>{2, 4, 6, 8, 10}, 5); Sci::Linalg::axpy(2, x, y); for (std::size_t i = 0; i < x.size(); ++i) { EXPECT_EQ(y(i), ans[i]); } } TEST(TestLinalg, TestDot) { Sci::Vector<int> a(std::vector<int>{1, 3, -5}, 3); Sci::Vector<int> b(std::vector<int>{4, -2, -1}, 3); EXPECT_EQ(Sci::Linalg::dot(a, b), 3); } TEST(TestLinalg, TestIdxAbsMax) { Sci::Vector<int> v(std::vector<int>{1, 3, -5, 2}, 4); EXPECT_EQ(Sci::Linalg::idx_abs_max(v), 2UL); } TEST(TestLinalg, TestIdxAbsMin) { Sci::Vector<int> v(std::vector<int>{1, 3, -5, 2}, 4); EXPECT_EQ(Sci::Linalg::idx_abs_min(v), 0UL); } TEST(TestLinalg, TestNorm2) { Sci::Vector<double> v(std::vector<double>{1.0, 2.0, 3.0}, 3); auto ans = Sci::Linalg::norm2(v); EXPECT_EQ(ans * ans, 14.0); } TEST(TestLinalg, TestNorm2Row) { // clang-format off std::vector<double> aa = {1, 2, 3, 4, 5, 6}; // clang-format on Sci::Matrix<double> ma(aa, 2, 3); auto ans = Sci::Linalg::norm2(Sci::row(ma.view(), 0)); EXPECT_EQ(ans * ans, 14.0); } TEST(TestLinalg, TestScaled) { // clang-format off std::vector<double> a_data = {1, 2, 3, 4, 5, 6}; // clang-format on Sci::Vector<double> a(a_data, 6); auto ans = Sci::Linalg::scaled(2.0, a); for (std::size_t i = 0; i < ans.size(); ++i) { EXPECT_EQ(ans(i), 2.0 * (1.0 + i)); } }
24.791667
78
0.571008
[ "vector" ]
053dc2cdb31e281d76989b5687c01603285717f8
7,066
cpp
C++
src/prefab.cpp
cran/individual
fcb17b41429a0c0b4033452a99613f6844a58012
[ "MIT" ]
null
null
null
src/prefab.cpp
cran/individual
fcb17b41429a0c0b4033452a99613f6844a58012
[ "MIT" ]
null
null
null
src/prefab.cpp
cran/individual
fcb17b41429a0c0b4033452a99613f6844a58012
[ "MIT" ]
null
null
null
/* * prefab.cpp * * Created on: 24 Feb 2021 * Author: slwu89 */ #include "../inst/include/DoubleVariable.h" #include "../inst/include/CategoricalVariable.h" #include "../inst/include/IntegerVariable.h" #include "utils.h" // [[Rcpp::export]] Rcpp::XPtr<process_t> fixed_probability_multinomial_process_internal( Rcpp::XPtr<CategoricalVariable> variable, const std::string source_state, const std::vector<std::string> destination_states, const double rate, const std::vector<double> destination_probabilities ){ // array of cumulative probabilities std::vector<double> cdf(destination_probabilities); std::partial_sum(destination_probabilities.begin(),destination_probabilities.end(),cdf.begin(),std::plus<double>()); // make pointer to lambda function and return XPtr to R return Rcpp::XPtr<process_t>( new process_t([variable,source_state,destination_states,rate,cdf](size_t t){ // sample leavers individual_index_t leaving_individuals(variable->get_index_of(source_state)); bitset_sample_internal(leaving_individuals, rate); // empty bitsets to put them (their destinations) std::vector<individual_index_t> destination_individuals; size_t n = destination_states.size(); for (size_t i=0; i<n; i++) { destination_individuals.emplace_back(leaving_individuals.max_size()); } // random variate for each leaver to see where they go const auto random = Rcpp::runif(leaving_individuals.size()); auto random_index = 0; for (auto it = std::begin(leaving_individuals); it != std::end(leaving_individuals); ++it) { auto dest_it = std::upper_bound(cdf.begin(), cdf.end(), random[random_index]); int dest = std::distance(cdf.begin(), dest_it); destination_individuals[dest].insert(*it); ++random_index; } // queue state updates for (size_t i=0; i<n; i++) { variable->queue_update(destination_states[i], destination_individuals[i]); } }), true ); } // [[Rcpp::export]] Rcpp::XPtr<process_t> multi_probability_multinomial_process_internal( Rcpp::XPtr<CategoricalVariable> variable, const std::string source_state, const std::vector<std::string> destination_states, const Rcpp::XPtr<DoubleVariable> rate_variable, const std::vector<double> destination_probabilities ){ // array of cumulative probabilities std::vector<double> cdf(destination_probabilities); std::partial_sum(destination_probabilities.begin(),destination_probabilities.end(),cdf.begin(),std::plus<double>()); // make pointer to lambda function and return XPtr to R return Rcpp::XPtr<process_t>( new process_t([variable,source_state,destination_states,rate_variable,cdf](size_t t){ // sample leavers with their unique prob individual_index_t leaving_individuals(variable->get_index_of(source_state)); std::vector<double> rate_vector = rate_variable->get_values(leaving_individuals); bitset_sample_multi_internal(leaving_individuals, rate_vector.begin(), rate_vector.end()); // empty bitsets to put them (their destinations) std::vector<individual_index_t> destination_individuals; size_t n = destination_states.size(); for (size_t i=0; i<n; i++) { destination_individuals.emplace_back(leaving_individuals.max_size()); } // random variate for each leaver to see where they go const auto random = Rcpp::runif(leaving_individuals.size()); auto random_index = 0; for (auto it = std::begin(leaving_individuals); it != std::end(leaving_individuals); ++it) { auto dest_it = std::upper_bound(cdf.begin(), cdf.end(), random[random_index]); int dest = std::distance(cdf.begin(), dest_it); destination_individuals[dest].insert(*it); ++random_index; } // queue state updates for (size_t i=0; i<n; i++) { variable->queue_update(destination_states[i], destination_individuals[i]); } }), true ); } // [[Rcpp::export]] Rcpp::XPtr<process_t> multi_probability_bernoulli_process_internal( Rcpp::XPtr<CategoricalVariable> variable, const std::string from, const std::string to, const Rcpp::XPtr<DoubleVariable> rate_variable ){ // make pointer to lambda function and return XPtr to R return Rcpp::XPtr<process_t>( new process_t([variable,rate_variable,from,to](size_t t){ // sample leavers with their unique prob individual_index_t leaving_individuals(variable->get_index_of(from)); std::vector<double> rate_vector = rate_variable->get_values(leaving_individuals); bitset_sample_multi_internal(leaving_individuals, rate_vector.begin(), rate_vector.end()); variable->queue_update(to, leaving_individuals); }), true ); } // [[Rcpp::export]] Rcpp::XPtr<process_t> infection_age_process_internal( Rcpp::XPtr<CategoricalVariable> state, const std::string susceptible, const std::string exposed, const std::string infectious, const Rcpp::XPtr<IntegerVariable> age, const int age_bins, const double p, const double dt, const Rcpp::NumericMatrix mixing ) { // make pointer to lambda function and return XPtr to R return Rcpp::XPtr<process_t>( new process_t([state,age,age_bins,susceptible,exposed,infectious,p,dt,mixing](size_t t){ // data structures we need to compute the age-structured force of infection // need NumericVector for sugar elementwise addition, division, and sum Rcpp::NumericVector N(age_bins); Rcpp::NumericVector I(age_bins); std::vector<individual_index_t> S(age_bins, state->size); // get number of infectious and total individuals in each age bin // and indices of susceptible individuals in each age bin for (int a=1; a <= age_bins; ++a) { individual_index_t I_a = state->get_index_of(infectious); individual_index_t N_a = age->get_index_of_set(a); I_a &= N_a; N[a-1] = N_a.size(); I[a-1] = I_a.size(); S[a-1] = state->get_index_of(susceptible); S[a-1] &= N_a; } // compute foi and sample infection for susceptible individuals in each age bin for (int a=1; a <= age_bins; ++a) { double foi = p * Rcpp::sum(mixing.row(a-1) * (I/N)); bitset_sample_internal(S[a-1], Rf_pexp(foi * dt, 1., 1, 0)); state->queue_update(exposed, S[a-1]); } }), true ); }
39.038674
121
0.631758
[ "vector" ]
0542c4fceafa5d7fc9373ba69307ca4e1589a1e2
16,293
cxx
C++
deps/src/cmake-3.9.3/Source/cmListCommand.cxx
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2018-12-15T20:03:51.000Z
2018-12-15T20:03:51.000Z
deps/src/cmake-3.9.3/Source/cmListCommand.cxx
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
3
2021-09-08T02:18:00.000Z
2022-03-12T00:39:44.000Z
deps/src/cmake-3.9.3/Source/cmListCommand.cxx
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2019-06-01T18:49:28.000Z
2019-06-01T18:49:28.000Z
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmListCommand.h" #include "cmsys/RegularExpression.hxx" #include <algorithm> #include <assert.h> #include <iterator> #include <sstream> #include <stdio.h> #include <stdlib.h> // required for atoi #include "cmAlgorithms.h" #include "cmMakefile.h" #include "cmPolicies.h" #include "cmSystemTools.h" #include "cmake.h" class cmExecutionStatus; bool cmListCommand::InitialPass(std::vector<std::string> const& args, cmExecutionStatus&) { if (args.size() < 2) { this->SetError("must be called with at least two arguments."); return false; } const std::string& subCommand = args[0]; if (subCommand == "LENGTH") { return this->HandleLengthCommand(args); } if (subCommand == "GET") { return this->HandleGetCommand(args); } if (subCommand == "APPEND") { return this->HandleAppendCommand(args); } if (subCommand == "FIND") { return this->HandleFindCommand(args); } if (subCommand == "INSERT") { return this->HandleInsertCommand(args); } if (subCommand == "REMOVE_AT") { return this->HandleRemoveAtCommand(args); } if (subCommand == "REMOVE_ITEM") { return this->HandleRemoveItemCommand(args); } if (subCommand == "REMOVE_DUPLICATES") { return this->HandleRemoveDuplicatesCommand(args); } if (subCommand == "SORT") { return this->HandleSortCommand(args); } if (subCommand == "REVERSE") { return this->HandleReverseCommand(args); } if (subCommand == "FILTER") { return this->HandleFilterCommand(args); } std::string e = "does not recognize sub-command " + subCommand; this->SetError(e); return false; } bool cmListCommand::GetListString(std::string& listString, const std::string& var) { // get the old value const char* cacheValue = this->Makefile->GetDefinition(var); if (!cacheValue) { return false; } listString = cacheValue; return true; } bool cmListCommand::GetList(std::vector<std::string>& list, const std::string& var) { std::string listString; if (!this->GetListString(listString, var)) { return false; } // if the size of the list if (listString.empty()) { return true; } // expand the variable into a list cmSystemTools::ExpandListArgument(listString, list, true); // if no empty elements then just return if (std::find(list.begin(), list.end(), std::string()) == list.end()) { return true; } // if we have empty elements we need to check policy CMP0007 switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0007)) { case cmPolicies::WARN: { // Default is to warn and use old behavior // OLD behavior is to allow compatibility, so recall // ExpandListArgument without the true which will remove // empty values list.clear(); cmSystemTools::ExpandListArgument(listString, list); std::string warn = cmPolicies::GetPolicyWarning(cmPolicies::CMP0007); warn += " List has value = ["; warn += listString; warn += "]."; this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, warn); return true; } case cmPolicies::OLD: // OLD behavior is to allow compatibility, so recall // ExpandListArgument without the true which will remove // empty values list.clear(); cmSystemTools::ExpandListArgument(listString, list); return true; case cmPolicies::NEW: return true; case cmPolicies::REQUIRED_IF_USED: case cmPolicies::REQUIRED_ALWAYS: this->Makefile->IssueMessage( cmake::FATAL_ERROR, cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0007)); return false; } return true; } bool cmListCommand::HandleLengthCommand(std::vector<std::string> const& args) { if (args.size() != 3) { this->SetError("sub-command LENGTH requires two arguments."); return false; } const std::string& listName = args[1]; const std::string& variableName = args[args.size() - 1]; std::vector<std::string> varArgsExpanded; // do not check the return value here // if the list var is not found varArgsExpanded will have size 0 // and we will return 0 this->GetList(varArgsExpanded, listName); size_t length = varArgsExpanded.size(); char buffer[1024]; sprintf(buffer, "%d", static_cast<int>(length)); this->Makefile->AddDefinition(variableName, buffer); return true; } bool cmListCommand::HandleGetCommand(std::vector<std::string> const& args) { if (args.size() < 4) { this->SetError("sub-command GET requires at least three arguments."); return false; } const std::string& listName = args[1]; const std::string& variableName = args[args.size() - 1]; // expand the variable std::vector<std::string> varArgsExpanded; if (!this->GetList(varArgsExpanded, listName)) { this->Makefile->AddDefinition(variableName, "NOTFOUND"); return true; } // FIXME: Add policy to make non-existing lists an error like empty lists. if (varArgsExpanded.empty()) { this->SetError("GET given empty list"); return false; } std::string value; size_t cc; const char* sep = ""; size_t nitem = varArgsExpanded.size(); for (cc = 2; cc < args.size() - 1; cc++) { int item = atoi(args[cc].c_str()); value += sep; sep = ";"; if (item < 0) { item = (int)nitem + item; } if (item < 0 || nitem <= (size_t)item) { std::ostringstream str; str << "index: " << item << " out of range (-" << nitem << ", " << nitem - 1 << ")"; this->SetError(str.str()); return false; } value += varArgsExpanded[item]; } this->Makefile->AddDefinition(variableName, value.c_str()); return true; } bool cmListCommand::HandleAppendCommand(std::vector<std::string> const& args) { assert(args.size() >= 2); // Skip if nothing to append. if (args.size() < 3) { return true; } const std::string& listName = args[1]; // expand the variable std::string listString; this->GetListString(listString, listName); if (!listString.empty() && !args.empty()) { listString += ";"; } listString += cmJoin(cmMakeRange(args).advance(2), ";"); this->Makefile->AddDefinition(listName, listString.c_str()); return true; } bool cmListCommand::HandleFindCommand(std::vector<std::string> const& args) { if (args.size() != 4) { this->SetError("sub-command FIND requires three arguments."); return false; } const std::string& listName = args[1]; const std::string& variableName = args[args.size() - 1]; // expand the variable std::vector<std::string> varArgsExpanded; if (!this->GetList(varArgsExpanded, listName)) { this->Makefile->AddDefinition(variableName, "-1"); return true; } std::vector<std::string>::iterator it = std::find(varArgsExpanded.begin(), varArgsExpanded.end(), args[2]); if (it != varArgsExpanded.end()) { std::ostringstream indexStream; indexStream << std::distance(varArgsExpanded.begin(), it); this->Makefile->AddDefinition(variableName, indexStream.str().c_str()); return true; } this->Makefile->AddDefinition(variableName, "-1"); return true; } bool cmListCommand::HandleInsertCommand(std::vector<std::string> const& args) { if (args.size() < 4) { this->SetError("sub-command INSERT requires at least three arguments."); return false; } const std::string& listName = args[1]; // expand the variable int item = atoi(args[2].c_str()); std::vector<std::string> varArgsExpanded; if ((!this->GetList(varArgsExpanded, listName) || varArgsExpanded.empty()) && item != 0) { std::ostringstream str; str << "index: " << item << " out of range (0, 0)"; this->SetError(str.str()); return false; } if (!varArgsExpanded.empty()) { size_t nitem = varArgsExpanded.size(); if (item < 0) { item = (int)nitem + item; } if (item < 0 || nitem <= (size_t)item) { std::ostringstream str; str << "index: " << item << " out of range (-" << varArgsExpanded.size() << ", " << (varArgsExpanded.empty() ? 0 : (varArgsExpanded.size() - 1)) << ")"; this->SetError(str.str()); return false; } } varArgsExpanded.insert(varArgsExpanded.begin() + item, args.begin() + 3, args.end()); std::string value = cmJoin(varArgsExpanded, ";"); this->Makefile->AddDefinition(listName, value.c_str()); return true; } bool cmListCommand::HandleRemoveItemCommand( std::vector<std::string> const& args) { if (args.size() < 3) { this->SetError("sub-command REMOVE_ITEM requires two or more arguments."); return false; } const std::string& listName = args[1]; // expand the variable std::vector<std::string> varArgsExpanded; if (!this->GetList(varArgsExpanded, listName)) { this->SetError("sub-command REMOVE_ITEM requires list to be present."); return false; } std::vector<std::string> remove(args.begin() + 2, args.end()); std::sort(remove.begin(), remove.end()); std::vector<std::string>::const_iterator remEnd = std::unique(remove.begin(), remove.end()); std::vector<std::string>::const_iterator remBegin = remove.begin(); std::vector<std::string>::const_iterator argsEnd = cmRemoveMatching(varArgsExpanded, cmMakeRange(remBegin, remEnd)); std::vector<std::string>::const_iterator argsBegin = varArgsExpanded.begin(); std::string value = cmJoin(cmMakeRange(argsBegin, argsEnd), ";"); this->Makefile->AddDefinition(listName, value.c_str()); return true; } bool cmListCommand::HandleReverseCommand(std::vector<std::string> const& args) { assert(args.size() >= 2); if (args.size() > 2) { this->SetError("sub-command REVERSE only takes one argument."); return false; } const std::string& listName = args[1]; // expand the variable std::vector<std::string> varArgsExpanded; if (!this->GetList(varArgsExpanded, listName)) { this->SetError("sub-command REVERSE requires list to be present."); return false; } std::string value = cmJoin(cmReverseRange(varArgsExpanded), ";"); this->Makefile->AddDefinition(listName, value.c_str()); return true; } bool cmListCommand::HandleRemoveDuplicatesCommand( std::vector<std::string> const& args) { assert(args.size() >= 2); if (args.size() > 2) { this->SetError("sub-command REMOVE_DUPLICATES only takes one argument."); return false; } const std::string& listName = args[1]; // expand the variable std::vector<std::string> varArgsExpanded; if (!this->GetList(varArgsExpanded, listName)) { this->SetError( "sub-command REMOVE_DUPLICATES requires list to be present."); return false; } std::vector<std::string>::const_iterator argsEnd = cmRemoveDuplicates(varArgsExpanded); std::vector<std::string>::const_iterator argsBegin = varArgsExpanded.begin(); std::string value = cmJoin(cmMakeRange(argsBegin, argsEnd), ";"); this->Makefile->AddDefinition(listName, value.c_str()); return true; } bool cmListCommand::HandleSortCommand(std::vector<std::string> const& args) { assert(args.size() >= 2); if (args.size() > 2) { this->SetError("sub-command SORT only takes one argument."); return false; } const std::string& listName = args[1]; // expand the variable std::vector<std::string> varArgsExpanded; if (!this->GetList(varArgsExpanded, listName)) { this->SetError("sub-command SORT requires list to be present."); return false; } std::sort(varArgsExpanded.begin(), varArgsExpanded.end()); std::string value = cmJoin(varArgsExpanded, ";"); this->Makefile->AddDefinition(listName, value.c_str()); return true; } bool cmListCommand::HandleRemoveAtCommand(std::vector<std::string> const& args) { if (args.size() < 3) { this->SetError("sub-command REMOVE_AT requires at least " "two arguments."); return false; } const std::string& listName = args[1]; // expand the variable std::vector<std::string> varArgsExpanded; if (!this->GetList(varArgsExpanded, listName)) { this->SetError("sub-command REMOVE_AT requires list to be present."); return false; } // FIXME: Add policy to make non-existing lists an error like empty lists. if (varArgsExpanded.empty()) { this->SetError("REMOVE_AT given empty list"); return false; } size_t cc; std::vector<size_t> removed; size_t nitem = varArgsExpanded.size(); for (cc = 2; cc < args.size(); ++cc) { int item = atoi(args[cc].c_str()); if (item < 0) { item = (int)nitem + item; } if (item < 0 || nitem <= (size_t)item) { std::ostringstream str; str << "index: " << item << " out of range (-" << nitem << ", " << nitem - 1 << ")"; this->SetError(str.str()); return false; } removed.push_back(static_cast<size_t>(item)); } std::sort(removed.begin(), removed.end()); std::vector<size_t>::const_iterator remEnd = std::unique(removed.begin(), removed.end()); std::vector<size_t>::const_iterator remBegin = removed.begin(); std::vector<std::string>::const_iterator argsEnd = cmRemoveIndices(varArgsExpanded, cmMakeRange(remBegin, remEnd)); std::vector<std::string>::const_iterator argsBegin = varArgsExpanded.begin(); std::string value = cmJoin(cmMakeRange(argsBegin, argsEnd), ";"); this->Makefile->AddDefinition(listName, value.c_str()); return true; } bool cmListCommand::HandleFilterCommand(std::vector<std::string> const& args) { if (args.size() < 2) { this->SetError("sub-command FILTER requires a list to be specified."); return false; } if (args.size() < 3) { this->SetError("sub-command FILTER requires an operator to be specified."); return false; } if (args.size() < 4) { this->SetError("sub-command FILTER requires a mode to be specified."); return false; } const std::string& listName = args[1]; // expand the variable std::vector<std::string> varArgsExpanded; if (!this->GetList(varArgsExpanded, listName)) { this->SetError("sub-command FILTER requires list to be present."); return false; } const std::string& op = args[2]; bool includeMatches; if (op == "INCLUDE") { includeMatches = true; } else if (op == "EXCLUDE") { includeMatches = false; } else { this->SetError("sub-command FILTER does not recognize operator " + op); return false; } const std::string& mode = args[3]; if (mode == "REGEX") { if (args.size() != 5) { this->SetError("sub-command FILTER, mode REGEX " "requires five arguments."); return false; } return this->FilterRegex(args, includeMatches, listName, varArgsExpanded); } this->SetError("sub-command FILTER does not recognize mode " + mode); return false; } class MatchesRegex { public: MatchesRegex(cmsys::RegularExpression& in_regex, bool in_includeMatches) : regex(in_regex) , includeMatches(in_includeMatches) { } bool operator()(const std::string& target) { return regex.find(target) ^ includeMatches; } private: cmsys::RegularExpression& regex; const bool includeMatches; }; bool cmListCommand::FilterRegex(std::vector<std::string> const& args, bool includeMatches, std::string const& listName, std::vector<std::string>& varArgsExpanded) { const std::string& pattern = args[4]; cmsys::RegularExpression regex(pattern); if (!regex.is_valid()) { std::string error = "sub-command FILTER, mode REGEX "; error += "failed to compile regex \""; error += pattern; error += "\"."; this->SetError(error); return false; } std::vector<std::string>::iterator argsBegin = varArgsExpanded.begin(); std::vector<std::string>::iterator argsEnd = varArgsExpanded.end(); std::vector<std::string>::iterator newArgsEnd = std::remove_if(argsBegin, argsEnd, MatchesRegex(regex, includeMatches)); std::string value = cmJoin(cmMakeRange(argsBegin, newArgsEnd), ";"); this->Makefile->AddDefinition(listName, value.c_str()); return true; }
29.840659
79
0.651998
[ "vector" ]
0546a2e751afc96e4b1e2f1211ca1435a9172b06
4,028
cpp
C++
src/tests/POIMatch_test.cpp
lzzgeo/NLP
2c9e02d62b900d8729a60d3fc68d5954b4d6e3f9
[ "MIT" ]
null
null
null
src/tests/POIMatch_test.cpp
lzzgeo/NLP
2c9e02d62b900d8729a60d3fc68d5954b4d6e3f9
[ "MIT" ]
null
null
null
src/tests/POIMatch_test.cpp
lzzgeo/NLP
2c9e02d62b900d8729a60d3fc68d5954b4d6e3f9
[ "MIT" ]
1
2018-05-18T17:17:35.000Z
2018-05-18T17:17:35.000Z
#include <sys/types.h> #include <string.h> #include <iostream> #include <fstream> #include <string> #include <map> #include <set> #include <vector> #include <stdint.h> #include <algorithm> #include <limits> #include <cmath> #include <stdarg.h> #include "POIInfo.h" #include "POIMatch_API.h" using namespace std; void str_split( char *src, const char *delim, vector<string> &vec ) { vec.clear(); char *token; while ( token = strsep(&src, delim) ) { vec.push_back( token ); } return; } int test_text( POIMatchWrapper &poi_match ) { vector<string> vec; char sentence[4096]; POIInfo poi_src; vector<POIInfo> poi_rs; int num(0); string line; vector<string> param_val; memset( sentence, 0, sizeof(sentence) ); ifstream dictf("./param_poimatch.txt"); while ( getline(dictf, line) ) //while ( std::cin.getline(sentence, sizeof(sentence)) ) { poi_src.clear( ); str_split( (char*) line.c_str(), ",", vec ); if ( vec.size() == 2 ) { poi_src.name = vec[0]; poi_src.address = vec[1]; } num = poi_match.match( poi_src, poi_rs ); poi_src.print(); /* cout << "\n\n" << endl; for ( size_t i=0; i<poi_rs.size(); ++i ) { cout << "\n-------------------------" << endl; poi_rs[i].print(); } */ memset( sentence, 0, sizeof(sentence) ); cout << "\n\n\n\n\n"<< endl; } return 1; } int test_cmd( POIMatchWrapper &poi_match ) { vector<string> vec; char sentence[4096]; POIInfo poi_src; vector<POIInfo> poi_rs; int num; vector<string> param_val; memset( sentence, 0, sizeof(sentence) ); while ( std::cin.getline(sentence, sizeof(sentence)) ) { poi_src.clear( ); str_split( &sentence[0], " ", vec ); for ( size_t i=0; i<vec.size(); ++i ) { str_split( (char*)vec[i].c_str(), "=", param_val ); if ( param_val.size()<2 ) continue; if ( param_val[0] == "name" ) poi_src.name = param_val[1]; else if ( param_val[0] == "kindgim" ) poi_src.kindgim = param_val[1]; else if ( param_val[0] == "kind" ) poi_src.kind = param_val[1]; else if ( param_val[0] == "admincode" ) poi_src.admincode = param_val[1]; else if ( param_val[0] == "address" ) poi_src.address = param_val[1]; else if ( param_val[0] == "telephone" ) poi_src.telephone = param_val[1]; else if ( param_val[0] == "lon" ) poi_src.lon = atof(param_val[1].c_str()); else if ( param_val[0] == "lat" ) poi_src.lat = atof(param_val[1].c_str()); else if ( param_val[0] == "dist" ) poi_src.geodist = atof(param_val[1].c_str()); else if ( param_val[0] == "prov" ) poi_src.prov = param_val[1].c_str(); else if ( param_val[0] == "city" ) poi_src.city = param_val[1].c_str(); else if ( param_val[0] == "county" ) poi_src.county = param_val[1].c_str(); } num = poi_match.match( poi_src, poi_rs ); poi_src.print(); cout << "\n\n" << endl; for ( size_t i=0; i<poi_rs.size(); ++i ) { cout << "\n-------------------------" << endl; poi_rs[i].print(); } memset( sentence, 0, sizeof(sentence) ); cout << "\n\n\n\n\n\n"<< endl; } return 1; } int main(int argc, char **argv) { if (argc < 2) { std::cerr << "Usage: " << "name kind admincode address tel x y" << std::endl; return -1; } POIMatchWrapper poi_match; poi_match.init ( argv[1], "192.168.15.106", 9312 ); //test_cmd( poi_match ); test_text( poi_match ); return 1; }
25.493671
99
0.501241
[ "vector" ]
d72a59ed3f95be6f7f5a1566fb9faafaec61778a
6,876
cc
C++
src/fcst/unit_tests/source/platinum_test.cc
jeremyjiezhou/Learn-PyTorch
7e4404609bacd2ec796f6ca3ea118e8e34ab4a22
[ "MIT" ]
24
2016-10-04T20:49:55.000Z
2022-03-12T19:07:10.000Z
src/fcst/unit_tests/source/platinum_test.cc
jeremyjiezhou/Learn-PyTorch
7e4404609bacd2ec796f6ca3ea118e8e34ab4a22
[ "MIT" ]
3
2016-09-05T10:17:36.000Z
2016-12-11T18:23:06.000Z
src/fcst/unit_tests/source/platinum_test.cc
jeremyjiezhou/Learn-PyTorch
7e4404609bacd2ec796f6ca3ea118e8e34ab4a22
[ "MIT" ]
9
2016-12-11T22:15:03.000Z
2020-11-21T13:51:05.000Z
#include "platinum_test.h" /** * Setup is called before any of the tests are called. */ void PlatinumTest::setup() { FuelCellShop::Material::CatalystBase::declare_Catalyst_parameters(param); catalyst = FuelCellShop::Material::CatalystBase::create_Catalyst(param, "Platinum"); } void PlatinumTest::tear_down() { //delete catalyst; } void PlatinumTest::testSetSolution() { //TEST_ASSERT_MSG(false, "Test not yet implemented!") } void PlatinumTest::testAlphaAnodic() { //We are testing the behaviour of Calculator::add(double a, double b) double answer(0); double expectedAnswer = 0.5; catalyst->set_reaction_kinetics(HOR); catalyst->alpha_anodic (answer); std::ostringstream streamOut; streamOut <<"The value of the alpha_anodic is: "<<answer<<". The expected value is: "<<expectedAnswer<<std::endl; streamOut <<"testAlphaAnodic failed!"<<std::endl; TEST_ASSERT_MSG(expectedAnswer == answer, streamOut.str().c_str()); } void PlatinumTest::testReferenceConcentration() { catalyst->set_reaction_kinetics(ORR); std::vector<VariableNames > reactants; reactants.push_back(oxygen_concentration); std::map< VariableNames, double > answer; catalyst->reference_concentration (reactants, answer); std::vector<double> expectedAnswer; expectedAnswer.push_back(1.6e-05); std::ostringstream streamOut; streamOut <<"The value of the reference_concentration is: "<< answer[oxygen_concentration] <<". The expected value is: "<< expectedAnswer[0]<<std::endl; streamOut <<"testReferenceConcentration failed!"<<std::endl; TEST_ASSERT_DELTA_MSG(expectedAnswer[0], answer[oxygen_concentration], 1e-06, streamOut.str().c_str()); } void PlatinumTest::testNeyerlin() { ParameterHandler param2; FuelCellShop::Material::CatalystBase::declare_Catalyst_parameters(param2); param2.enter_subsection("Materials"); param2.enter_subsection("Platinum"); param2.set("Method for kinetics parameters (ORR)","Neyerlin"); param2.leave_subsection(); param2.leave_subsection(); boost::shared_ptr<FuelCellShop::Material::CatalystBase > catalyst2 = FuelCellShop::Material::CatalystBase::create_Catalyst(param2, "Platinum"); double answer(0); double expectedAnswer = 1; catalyst2->set_reaction_kinetics(ORR); // Test alpha { catalyst2->alpha_cathodic (answer); std::ostringstream streamOut; streamOut <<"The value of the cathodic alpha is: "<<answer<<". The expected value is: "<<expectedAnswer<<std::endl; streamOut <<"testNeyerlin failed!"<<std::endl; TEST_ASSERT_MSG(expectedAnswer == answer, streamOut.str().c_str()); } // Test gamma { expectedAnswer = 0.54; std::vector<VariableNames > reactants; reactants.push_back(oxygen_concentration); std::map< VariableNames, double > reaction_order; catalyst2->reaction_order (reactants, reaction_order); answer = reaction_order[oxygen_concentration]; std::ostringstream streamOut; streamOut <<"The value of the reaction order is: "<<answer<<". The expected value is: "<<expectedAnswer<<std::endl; streamOut <<"testNeyerlin failed!"<<std::endl; TEST_ASSERT_MSG(expectedAnswer == answer, streamOut.str().c_str()); } // Test exchange current density } void PlatinumTest::testParthasarathy() { ParameterHandler param2; FuelCellShop::Material::CatalystBase::declare_Catalyst_parameters(param2); param2.enter_subsection("Materials"); param2.enter_subsection("Platinum"); param2.set("Method for kinetics parameters (ORR)","Parthasarathy"); param2.leave_subsection(); param2.leave_subsection(); boost::shared_ptr<FuelCellShop::Material::CatalystBase > catalyst2 = FuelCellShop::Material::CatalystBase::create_Catalyst(param2, "Platinum"); double answer(0); double expectedAnswer = 1.0; catalyst2->set_reaction_kinetics(ORR); // Test alpha { catalyst2->alpha_cathodic (answer); std::ostringstream streamOut; streamOut <<"The value of the cathodic_anodic is: "<<answer<<". The expected value is: "<<expectedAnswer<<std::endl; streamOut <<"testParthasarathy failed!"<<std::endl; TEST_ASSERT_MSG(expectedAnswer == answer, streamOut.str().c_str()); } // Test gamma { expectedAnswer = 1.0; std::vector<VariableNames > reactants; reactants.push_back(oxygen_concentration); std::map< VariableNames, double > reaction_order; catalyst2->reaction_order (reactants, reaction_order); answer = reaction_order[oxygen_concentration]; std::ostringstream streamOut; streamOut <<"The value of the reaction order is: "<<answer<<". The expected value is: "<<expectedAnswer<<std::endl; streamOut <<"testParthasarathy failed!"<<std::endl; TEST_ASSERT_MSG(expectedAnswer == answer, streamOut.str().c_str()); } } void PlatinumTest::testParthasarathyHCD() { ParameterHandler param2; FuelCellShop::Material::CatalystBase::declare_Catalyst_parameters(param2); param2.enter_subsection("Materials"); param2.enter_subsection("Platinum"); param2.set("Method for kinetics parameters (ORR)","Parthasarathy_hcd"); param2.leave_subsection(); param2.leave_subsection(); boost::shared_ptr<FuelCellShop::Material::CatalystBase > catalyst2 = FuelCellShop::Material::CatalystBase::create_Catalyst(param2, "Platinum"); double answer(0); double expectedAnswer = 0.5; catalyst2->set_reaction_kinetics(ORR); // Test alpha { catalyst2->alpha_cathodic (answer); std::ostringstream streamOut; streamOut <<"The value of the cathodic transfer coefficient is: "<<answer<<". The expected value is: "<<expectedAnswer<<std::endl; streamOut <<"testParthasarathyHCD failed!"<<std::endl; TEST_ASSERT_MSG(expectedAnswer == answer, streamOut.str().c_str()); } // Test gamma { expectedAnswer = 1.0; std::vector<VariableNames > reactants; reactants.push_back(oxygen_concentration); std::map< VariableNames, double > reaction_order; catalyst2->reaction_order (reactants, reaction_order); answer = reaction_order[oxygen_concentration]; std::ostringstream streamOut; streamOut <<"The value of the reaction order is: "<<answer<<". The expected value is: "<<expectedAnswer<<std::endl; streamOut <<"testParthasarathyHCD failed!"<<std::endl; TEST_ASSERT_MSG(expectedAnswer == answer, streamOut.str().c_str()); } }
32.742857
156
0.672484
[ "vector" ]
d72b7754f939087a4bb701eb528d4a4c4019d1da
9,870
cpp
C++
Blizzlike/ArcEmu/C++/QuestScripts/Quest_BoreanTundra.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/ArcEmu/C++/QuestScripts/Quest_BoreanTundra.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/ArcEmu/C++/QuestScripts/Quest_BoreanTundra.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * ArcScripts for ArcEmu MMORPG Server * Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Setup.h" // Call to Arms! class BellRope : public GameObjectAIScript { public: ADD_GAMEOBJECT_FACTORY_FUNCTION(BellRope); BellRope(GameObject* goinstance) : GameObjectAIScript(goinstance) {}; void OnActivate(Player* pPlayer) { if(sEAS.GetQuest(pPlayer, 11965)) sEAS.KillMobForQuest(pPlayer, 11965, 0); }; }; // Reading the Meters class ColdarraGeoMonitorNexus : public GameObjectAIScript { public: ADD_GAMEOBJECT_FACTORY_FUNCTION(ColdarraGeoMonitorNexus); ColdarraGeoMonitorNexus(GameObject* goinstance) : GameObjectAIScript(goinstance) {}; void OnActivate(Player* pPlayer) { if(sEAS.GetQuest(pPlayer, 11900)) sEAS.KillMobForQuest(pPlayer, 11900, 0); }; }; class ColdarraGeoMonitorSouth : public GameObjectAIScript { public: ADD_GAMEOBJECT_FACTORY_FUNCTION(ColdarraGeoMonitorSouth); ColdarraGeoMonitorSouth(GameObject* goinstance) : GameObjectAIScript(goinstance) {}; void OnActivate(Player* pPlayer) { if(sEAS.GetQuest(pPlayer, 11900)) sEAS.KillMobForQuest(pPlayer, 11900, 1); }; }; class ColdarraGeoMonitorNorth : public GameObjectAIScript { public: ADD_GAMEOBJECT_FACTORY_FUNCTION(ColdarraGeoMonitorNorth); ColdarraGeoMonitorNorth(GameObject* goinstance) : GameObjectAIScript(goinstance) {}; void OnActivate(Player* pPlayer) { if(sEAS.GetQuest(pPlayer, 11900)) sEAS.KillMobForQuest(pPlayer, 11900, 2); }; }; class ColdarraGeoMonitorWest : public GameObjectAIScript { public: ADD_GAMEOBJECT_FACTORY_FUNCTION(ColdarraGeoMonitorWest); ColdarraGeoMonitorWest(GameObject* goinstance) : GameObjectAIScript(goinstance) {}; void OnActivate(Player* pPlayer) { if(sEAS.GetQuest(pPlayer, 11900)) sEAS.KillMobForQuest(pPlayer, 11900, 3); }; }; // Neutralizing the Cauldrons #define CN_PURIFYING_TOTEM 25494 class PurifyingTotemAI : public MoonScriptCreatureAI { MOONSCRIPT_FACTORY_FUNCTION(PurifyingTotemAI, MoonScriptCreatureAI); PurifyingTotemAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { SetCanEnterCombat(false); SetCanMove(false); Despawn(8000, 0); } }; // Cutting Off the Source class NerubarEggSac : public GameObjectAIScript { public: ADD_GAMEOBJECT_FACTORY_FUNCTION(NerubarEggSac); NerubarEggSac(GameObject* goinstance) : GameObjectAIScript(goinstance) {}; void OnActivate(Player* pPlayer) { if(sEAS.GetQuest(pPlayer, 11602)) return; sEAS.KillMobForQuest(pPlayer, 11602, 0); _gameobject->SetState(1); _gameobject->SetState(0); _gameobject->Despawn(500, 60000); }; }; // Bury Those Cockroaches! class SeaforiumDepthCharge : public MoonScriptCreatureAI { MOONSCRIPT_FACTORY_FUNCTION(SeaforiumDepthCharge, MoonScriptCreatureAI); SeaforiumDepthCharge(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { SetCanMove(false); SetCanEnterCombat(false); _unit->SetFaction(21); } void OnLoad() { if(!_unit->IsSummon()) return; Unit* summoner = TO< Summon* >(_unit)->GetOwner(); if(summoner != NULL) { if(summoner->IsPlayer()) { Player* p = TO_PLAYER(summoner); if(p->HasQuest(11608)) { GameObject* pSinkhole = p->GetMapMgr()->GetInterface()->GetGameObjectNearestCoords(p->GetPositionX(), p->GetPositionY(), p->GetPositionZ(), 300171); if(pSinkhole != NULL) { _unit->CastSpell(_unit, 45502, true); float posX = pSinkhole->GetPositionX(); if(posX == 2657.13f) sEAS.KillMobForQuest(p, 11608, 0); if(posX == 2716.02f) sEAS.KillMobForQuest(p, 11608, 1); if(posX == 2877.96f) sEAS.KillMobForQuest(p, 11608, 2); if(posX == 2962.16f) sEAS.KillMobForQuest(p, 11608, 3); } } } } _unit->Despawn(500, 0); } }; // Hatching a Plan class BlueDragonEgg : public GameObjectAIScript { public: ADD_GAMEOBJECT_FACTORY_FUNCTION(BlueDragonEgg); BlueDragonEgg(GameObject* goinstance) : GameObjectAIScript(goinstance) {}; void OnActivate(Player* pPlayer) { if(!sEAS.GetQuest(pPlayer, 11936)) return; sEAS.KillMobForQuest(pPlayer, 11936, 0); _gameobject->SetState(1); _gameobject->SetState(0); _gameobject->Despawn(500, 60000); } }; enum eFizzcrank { NPC_FIZZCRANK = 25590, GOSSIP_TEXTID_FIZZCRANK1 = 12456, GOSSIP_TEXTID_FIZZCRANK2 = 12457, GOSSIP_TEXTID_FIZZCRANK3 = 12458, GOSSIP_TEXTID_FIZZCRANK4 = 12459, GOSSIP_TEXTID_FIZZCRANK5 = 12460, GOSSIP_TEXTID_FIZZCRANK6 = 12461, GOSSIP_TEXTID_FIZZCRANK7 = 12462, GOSSIP_TEXTID_FIZZCRANK8 = 12463, GOSSIP_TEXTID_FIZZCRANK9 = 12464, QUEST_THE_MECHAGNOMES = 11708 }; #define GOSSIP_ITEM_GO_ON "Go on." #define GOSSIP_ITEM_TELL_ME "Tell me what's going on out here, Fizzcrank." class FizzcrankGossip : public GossipScript { public: void GossipHello(Object* pObject, Player* pPlayer) { GossipMenu* Menu; objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 1, pPlayer); if(sEAS.GetQuest(pPlayer, QUEST_THE_MECHAGNOMES)) Menu->AddItem(0, GOSSIP_ITEM_TELL_ME, 1); Menu->SendTo(pPlayer); } void GossipSelectOption(Object* pObject, Player* pPlayer, uint32 Id, uint32 IntId, const char* Code) { GossipMenu* Menu; switch(IntId) { case 1: objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), GOSSIP_TEXTID_FIZZCRANK1, pPlayer); Menu->AddItem(0, GOSSIP_ITEM_GO_ON, 2); Menu->SendTo(pPlayer); break; case 2: objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), GOSSIP_TEXTID_FIZZCRANK2, pPlayer); Menu->AddItem(0, GOSSIP_ITEM_GO_ON, 3); Menu->SendTo(pPlayer); break; case 3: objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), GOSSIP_TEXTID_FIZZCRANK3, pPlayer); Menu->AddItem(0, GOSSIP_ITEM_GO_ON, 4); Menu->SendTo(pPlayer); break; case 4: objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), GOSSIP_TEXTID_FIZZCRANK4, pPlayer); Menu->AddItem(0, GOSSIP_ITEM_GO_ON, 5); Menu->SendTo(pPlayer); break; case 5: objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), GOSSIP_TEXTID_FIZZCRANK5, pPlayer); Menu->AddItem(0, GOSSIP_ITEM_GO_ON, 6); Menu->SendTo(pPlayer); break; case 6: objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), GOSSIP_TEXTID_FIZZCRANK6, pPlayer); Menu->AddItem(0, GOSSIP_ITEM_GO_ON, 7); Menu->SendTo(pPlayer); break; case 7: objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), GOSSIP_TEXTID_FIZZCRANK7, pPlayer); Menu->AddItem(0, GOSSIP_ITEM_GO_ON, 8); Menu->SendTo(pPlayer); break; case 8: objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), GOSSIP_TEXTID_FIZZCRANK8, pPlayer); Menu->AddItem(0, GOSSIP_ITEM_GO_ON, 9); Menu->SendTo(pPlayer); break; case 9: objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), GOSSIP_TEXTID_FIZZCRANK9, pPlayer); Menu->SendTo(pPlayer); break; } } }; #define GOSSIP_ITEM_FREE_FLIGHT "I'd like passage to the Transitus Shield." #define GOSSIP_ITEM_FLIGHT "May I use a drake to fly elsewhere?" enum eSurristrasz { NPC_SURRISTRASZ = 24795, SPELL_ABMER_TO_COLDARRA = 46064 }; class SurristraszGossip : public GossipScript { public: void GossipHello(Object* pObject, Player* pPlayer) { GossipMenu* Menu; objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 1, pPlayer); Menu->AddItem(0, GOSSIP_ITEM_FREE_FLIGHT, 1); Menu->AddItem(3, GOSSIP_ITEM_FLIGHT, 2); Menu->SendTo(pPlayer); }; void GossipSelectOption(Object* pObject, Player* pPlayer, uint32 Id, uint32 IntId, const char* Code) { if(!pObject->IsCreature()) return; switch(IntId) { case 1: pPlayer->Gossip_Complete(); pPlayer->CastSpell(pPlayer, SPELL_ABMER_TO_COLDARRA, true); break; case 2: pPlayer->GetSession()->SendTaxiList(TO_CREATURE(pObject)); break; }; }; }; void SetupBoreanTundra(ScriptMgr* mgr) { // Call to Arms! mgr->register_gameobject_script(188163, &BellRope::Create); // Reading the Meters mgr->register_gameobject_script(188100, &ColdarraGeoMonitorNexus::Create); mgr->register_gameobject_script(188101, &ColdarraGeoMonitorSouth::Create); mgr->register_gameobject_script(188102, &ColdarraGeoMonitorNorth::Create); mgr->register_gameobject_script(188103, &ColdarraGeoMonitorWest::Create); // Cutting Off the Source mgr->register_gameobject_script(187655, &NerubarEggSac::Create); // Bury Those Cockroaches! mgr->register_creature_script(25401, &SeaforiumDepthCharge::Create); // Hatching a Plan mgr->register_gameobject_script(188133, &BlueDragonEgg::Create); // Neutralizing the Cauldrons mgr->register_creature_script(CN_PURIFYING_TOTEM, &PurifyingTotemAI::Create); // Mechagnomes // Fizzcrank Fullthrottle GossipScript* fGossip = new FizzcrankGossip; mgr->register_gossip_script(NPC_FIZZCRANK, fGossip); // Surristrasz GossipScript* sGossip = new SurristraszGossip; mgr->register_gossip_script(NPC_SURRISTRASZ, sGossip); }
27.041096
154
0.716312
[ "object" ]
d72f5684aaf1bb118a88cb5ae06c0b8067710eaf
1,538
cpp
C++
algorithms/cpp/587.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
3
2016-10-01T10:15:09.000Z
2017-07-09T02:53:36.000Z
algorithms/cpp/587.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
null
null
null
algorithms/cpp/587.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; struct Point { int x; int y; Point() : x(0), y(0) {} Point(int a, int b) : x(a), y(b) {} }; class Solution { private: static bool compare(const Point &a, const Point &b) { return (a.x < b.x) || (a.x == b.x && a.y < b.y); } double cross(const Point &o, const Point &a, const Point &b) { return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x); } void uniquePoints(vector<Point> &points) { int cnt = 1; for (int i = 1; i < points.size(); i++) { if (points[i].x != points[cnt-1].x || points[i].y != points[cnt-1].y) points[cnt++] = points[i]; } points.resize(cnt); } public: vector<Point> outerTrees(vector<Point> &points) { sort(points.begin(), points.end(), compare); vector<Point> result; for (int i = 0; i < points.size(); i++) { while (result.size() >= 2 && cross(result[result.size()-2], result.back(), points[i]) < 0) result.pop_back(); result.push_back(points[i]); } for (int i = points.size()-2, t = result.size()+1; i >= 0; i--) { while (result.size() >= t && cross(result[result.size()-2], result.back(), points[i]) < 0) result.pop_back(); result.push_back(points[i]); } sort(result.begin(), result.end(), compare); uniquePoints(result); return result; } }; int main() { return 0; }
30.156863
102
0.49935
[ "vector" ]
d7310340f834b739812674d5beb047657da84c00
14,482
cpp
C++
src/core/lib/core_serialization_new/xmlserialization/xmlserializationnode.cpp
wgsyd/wgtf
d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed
[ "BSD-3-Clause" ]
28
2016-06-03T05:28:25.000Z
2019-02-14T12:04:31.000Z
src/core/lib/core_serialization_new/xmlserialization/xmlserializationnode.cpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
null
null
null
src/core/lib/core_serialization_new/xmlserialization/xmlserializationnode.cpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
14
2016-06-03T05:52:27.000Z
2019-03-21T09:56:03.000Z
#include "xmlserializationnode.hpp" #include "core_serialization/resizing_memory_stream.hpp" #include <memory> #include <sstream> #include <codecvt> namespace wgt { XMLSerializationNode::~XMLSerializationNode() { } std::unique_ptr<SerializationNode> XMLSerializationNode::createEmptyChildInternal(const char* childName, size_t nameSize) { if (childName == nullptr) { return nullptr; } // Use a string to ensure null-terminated char* is passed to tinyxml2 std::string name(childName, nameSize); auto doc = xmlNode_->GetDocument(); auto childNode = doc->NewElement(name.size() > 0 ? name.c_str() : ""); if (childNode == nullptr) { return nullptr; } xmlNode_->InsertEndChild(childNode); return std::move(createNodeInternal(childNode)); } std::unique_ptr<SerializationNode> XMLSerializationNode::createEmptyChildInternal(const SStringRef& childName) { return this->createEmptyChildInternal(childName.data(), childName.size()); } std::unique_ptr<SerializationNode> XMLSerializationNode::getChildNode(const char* childName, size_t nameSize) { if (childName == nullptr) { return nullptr; } std::string name(childName, nameSize); auto childNode = xmlNode_->FirstChildElement(name.c_str()); if (childNode == nullptr) { return nullptr; } return std::move(createNodeInternal(childNode)); } std::unique_ptr<SerializationNode> XMLSerializationNode::getChildNode(const SStringRef& childName) { return this->getChildNode(childName.data(), childName.size()); } std::vector<std::unique_ptr<SerializationNode>> XMLSerializationNode::getAllChildren(const char* childName, size_t nameSize) { std::vector<std::unique_ptr<SerializationNode>> childNodes; if (childName == nullptr) { return std::move(childNodes); } std::string nameString(childName, nameSize); const char* childNameSafe = nameString.c_str(); // Iterate through children for (tinyxml2::XMLElement* currentChild = xmlNode_->FirstChildElement(); currentChild != nullptr; currentChild = currentChild->NextSiblingElement()) { // strcmps all throughout new serialization framework are changed to strncmp in future stashed changes if (strcmp(currentChild->Name(), childNameSafe) == 0 || strcmp(childNameSafe, "") == 0) { childNodes.push_back(this->createNodeInternal(currentChild)); } } return std::move(childNodes); } std::vector<std::unique_ptr<SerializationNode>> XMLSerializationNode::getAllChildren(const SStringRef& childName) { return this->getAllChildren(childName.data(), childName.size()); } bool XMLSerializationNode::isNull() const { if (xmlNode_ == nullptr) { return true; } return false; } std::string XMLSerializationNode::getName() const { // makeCharSizeString handles nullptrs for us return this->makeCharSizeString(xmlNode_->Name()); } std::string XMLSerializationNode::getValueString() const { // makeCharSizeString handles nullptrs for us return this->makeCharSizeString(xmlNode_->GetText()); } std::wstring XMLSerializationNode::getValueWString() const { // Get narrow text const char* text = xmlNode_->GetText(); if (text == nullptr) { return std::move(std::wstring(L"")); } // Convert, handling UTF-8 correctly. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter; std::wstring wText = converter.from_bytes(text); // length() only knows the length in wide chars, as opposed to individual UTF-8 encoded characters. return std::move(wText); } double XMLSerializationNode::getValueDouble() const { std::stringstream s; const char* text = xmlNode_->GetText(); // If this was called on the wrong node, then text will be nullptr! if (text == nullptr) return double(0); s << text; double d; s >> d; return d; } intmax_t XMLSerializationNode::getValueInt() const { std::stringstream s; const char* text = xmlNode_->GetText(); // If this was called on the wrong node, then text will be nullptr! if (text == nullptr) return intmax_t(0); s << text; intmax_t i; s >> i; return i; } uintmax_t XMLSerializationNode::getValueUint() const { std::stringstream s; const char* text = xmlNode_->GetText(); // If this was called on the wrong node, then text will be nullptr! if (text == nullptr) return uintmax_t(0); s << text; uintmax_t u; s >> u; return u; } char XMLSerializationNode::getValueChar() const { std::stringstream s; const char* text = xmlNode_->GetText(); // If this was called on the wrong node, then text will be nullptr! if (text == nullptr) return char(0); s << text; char u; s >> u; return u; } wchar_t XMLSerializationNode::getValueWChar() const { // Get narrow text const char* text = xmlNode_->GetText(); if (text == nullptr) { return wchar_t(0); } std::wstring_convert<std::codecvt_utf8<wchar_t>> converter; std::wstring wText = converter.from_bytes(text); return wText.front(); } bool XMLSerializationNode::getValueBool() const { std::stringstream s; const char* text = xmlNode_->GetText(); // If this was called on the wrong node, then text will be nullptr! if (text == nullptr) return false; s << text; bool b; s >> b; return b; } std::string XMLSerializationNode::getType() const { const char* typeTag = xmlNode_->Attribute(this->getDocumentInternal()->getFormatData().typeTag); return this->makeCharSizeString(typeTag); } std::string XMLSerializationNode::getHandlerName() const { const char* handlerNameTag = xmlNode_->Attribute(this->getDocumentInternal()->getFormatData().handlerNameTag); return this->makeCharSizeString(handlerNameTag); } void XMLSerializationNode::setNameInternal(const char* name, size_t nameSize) { if (name == nullptr) { return; } std::string nameString(name, nameSize); xmlNode_->SetName(nameString.c_str() ? nameString.c_str() : ""); } void XMLSerializationNode::setNameInternal(const SStringRef& name) { this->setNameInternal(name.data(), name.size()); } void XMLSerializationNode::setValueString(const char* value, size_t valueSize, bool setType) { if (setType) { const char* typeName = this->getDocument()->getPrimitiveNames().stringName; this->setType(typeName, strlen(typeName)); } std::string valueString(value, valueSize); xmlNode_->SetText(valueString.c_str()); } void XMLSerializationNode::setValueString(const SStringRef& value, bool setType) { this->setValueString(value.data(), value.size()); } void XMLSerializationNode::setValueWString(const wchar_t* value, size_t valueSize, bool setType) { if (setType) { const char* typeName = this->getDocument()->getPrimitiveNames().wstringName; this->setType(typeName, strlen(typeName)); } std::wstring valueString(value, valueSize); // Convert possible UTF-8 encoding to narrow char* std::wstring_convert<std::codecvt_utf8<wchar_t>> converter; std::string narrowValue = converter.to_bytes(valueString); xmlNode_->SetText(narrowValue.c_str()); } void XMLSerializationNode::setValueWString(const WSStringRef& value, bool setType) { this->setValueWString(value.data(), value.size()); } void XMLSerializationNode::setValueDouble(double value, bool setType) { if (setType) { const char* typeName = this->getDocument()->getPrimitiveNames().doubleName; this->setType(typeName, strlen(typeName)); } std::stringstream ss; ss << value; std::string s; ss >> s; xmlNode_->SetText(s.c_str()); } void XMLSerializationNode::setValueInt(intmax_t value, bool setType) { if (setType) { const char* typeName = this->getDocument()->getPrimitiveNames().intName; this->setType(typeName, strlen(typeName)); } std::stringstream ss; ss << value; std::string s; ss >> s; xmlNode_->SetText(s.c_str()); } void XMLSerializationNode::setValueUint(uintmax_t value, bool setType) { if (setType) { const char* typeName = this->getDocument()->getPrimitiveNames().uintName; this->setType(typeName, strlen(typeName)); } std::stringstream ss; ss << value; std::string s; ss >> s; xmlNode_->SetText(s.c_str()); } void XMLSerializationNode::setValueChar(char value, bool setType) { if (setType) { const char* typeName = this->getDocument()->getPrimitiveNames().charName; this->setType(typeName, strlen(typeName)); } char tmp[2] = {}; tmp[0] = value; xmlNode_->SetText(tmp); } void XMLSerializationNode::setValueWChar(wchar_t value, bool setType) { if (setType) { const char* typeName = this->getDocument()->getPrimitiveNames().wstringName; this->setType(typeName, strlen(typeName)); } std::wstring_convert<std::codecvt_utf8<wchar_t>> converter; std::string narrowValue = converter.to_bytes(value); xmlNode_->SetText(narrowValue.c_str()); } void XMLSerializationNode::setValueBool(bool value, bool setType) { if (setType) { const char* typeName = this->getDocument()->getPrimitiveNames().boolName; this->setType(typeName, strlen(typeName)); } std::stringstream ss; ss << value; std::string s; ss >> s; xmlNode_->SetText(s.c_str()); } void XMLSerializationNode::setValueRawData(const char* value, size_t valueSize, const char* typeName, size_t typeNameSize) { if (typeName != nullptr) { this->setType(typeName, typeNameSize); } std::string nameString(value, valueSize); xmlNode_->SetText(nameString.c_str()); } void XMLSerializationNode::setValueRawData(const char* value, size_t valueSize, const SStringRef& typeName) { setValueRawData(value, valueSize, typeName.data(), typeName.size()); } void XMLSerializationNode::setHandlerName(const char* handlerName, size_t handlerNameSize) { if (handlerNameSize == size_t(0)) { return; } std::string handlerNameString(handlerName, handlerNameSize); xmlNode_->SetAttribute(this->getDocumentInternal()->getFormatData().handlerNameTag, handlerNameString.c_str()); } void XMLSerializationNode::setHandlerName(const SStringRef& value) { this->setHandlerName(value.data(), value.size()); } void XMLSerializationNode::deleteChild(const char* childName, size_t nameSize) { if (childName == nullptr) { return; } std::string nameString(childName, nameSize); auto targetChild = xmlNode_->FirstChildElement(nameString.c_str()); if (targetChild == nullptr) { return; } xmlNode_->DeleteChild(targetChild); } void XMLSerializationNode::deleteChild(const SStringRef& childName) { this->deleteChild(childName.data(), childName.size()); } void XMLSerializationNode::deleteChild(std::unique_ptr<SerializationNode>& childNode) { // Ensure that we have the same document (and must therefore be of the same type) if (childNode->getDocument() != this->getDocument()) { return; } auto childNodeXML = static_cast<XMLSerializationNode*>(childNode.get()); tinyxml2::XMLElement* internalXMLNode = childNodeXML->getInternalNode(); // Iterate through child XML nodes bool found = false; auto currentNode = xmlNode_->FirstChildElement(); auto lastNode = xmlNode_->LastChildElement(); while (currentNode != lastNode) { if (currentNode == internalXMLNode) { found = true; break; } currentNode = currentNode->NextSiblingElement(); } // childNode isn't actually a child if (!found) { return; } xmlNode_->DeleteChild(internalXMLNode); childNode.reset(); } void XMLSerializationNode::deleteChildren() { xmlNode_->DeleteChildren(); } tinyxml2::XMLElement* XMLSerializationNode::getInternalNode() { return xmlNode_; } void XMLSerializationNode::setType(const char* typeName, size_t nameSize) { std::string nameString(typeName, nameSize); xmlNode_->SetAttribute(this->getDocumentInternal()->getFormatData().typeTag, nameString.c_str() ? nameString.c_str() : ""); } void XMLSerializationNode::setType(const SStringRef& typeName) { this->setType(typeName.data(), typeName.size()); } bool operator==(XMLSerializationNode& lhs, XMLSerializationNode& rhs) { return lhs.getInternalNode() == rhs.getInternalNode(); } std::unique_ptr<SerializationNode> XMLSerializationNode::createNodeInternal(tinyxml2::XMLElement* node) { SerializationNode* newNode = new XMLSerializationNode((XMLSerializationDocument*)this->getDocument(), node); return std::unique_ptr<SerializationNode>(newNode); } XMLSerializationDocument* XMLSerializationNode::getDocumentInternal() const { // XMLNodes are only created by an XMLDocument or other XMLNodes, so this should always be valid. return (XMLSerializationDocument*)this->getDocument(); } std::string XMLSerializationNode::makeCharSizeString(const char* charData) const { if (charData == nullptr) { return std::string(""); } // tinyxml2 returns null terminated char* size_t count = 0; while (charData[count] != 0) { ++count; } return std::move(std::string(charData, count)); } } // end namespace wgt
27.690249
117
0.63976
[ "vector" ]
d735852bcf78350ced6ccd60407b7541f52059e6
740
cpp
C++
src/MajorityElementII.cpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
43
2015-10-10T12:59:52.000Z
2018-07-11T18:07:00.000Z
src/MajorityElementII.cpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
null
null
null
src/MajorityElementII.cpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
11
2015-10-10T14:41:11.000Z
2018-07-28T06:03:16.000Z
#include "MajorityElementII.hpp" vector<int> MajorityElementII::majorityElement(vector<int> &nums) { int cnt1 = 0, cnt2 = 0; int num1, num2; for (auto n : nums) { if (cnt1 == 0 || n == num1) { cnt1++; num1 = n; } else if (cnt2 == 0 || n == num2) { cnt2++; num2 = n; } else { cnt1--; cnt2--; } } cnt1 = cnt2 = 0; for (auto n : nums) { if (n == num1) cnt1++; else if (n == num2) cnt2++; } vector<int> result; if (cnt1 > nums.size() / 3) result.push_back(num1); if (cnt2 > nums.size() / 3) result.push_back(num2); return result; }
18.974359
67
0.428378
[ "vector" ]
d736efe91f210996278c853a5b7737b177a7b8a1
39,432
cpp
C++
src/shogun/machine/gp/SingleFITCLaplaceInferenceMethod.cpp
LiuYuHui/shogun
aab9e644d0be2bc4a9a3f40810c6010a987956c0
[ "BSD-3-Clause" ]
1
2020-09-18T04:30:46.000Z
2020-09-18T04:30:46.000Z
src/shogun/machine/gp/SingleFITCLaplaceInferenceMethod.cpp
awesomemachinelearning/shogun
f143eaf9fdd95f138335e49b3a26693847af5dac
[ "BSD-3-Clause" ]
null
null
null
src/shogun/machine/gp/SingleFITCLaplaceInferenceMethod.cpp
awesomemachinelearning/shogun
f143eaf9fdd95f138335e49b3a26693847af5dac
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (W) 2015 Wu Lin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. * */ #include <shogun/machine/gp/SingleFITCLaplaceInferenceMethod.h> #include <shogun/machine/gp/StudentsTLikelihood.h> #include <shogun/mathematics/Math.h> #include <shogun/machine/visitors/ShapeVisitor.h> #ifdef USE_GPL_SHOGUN #include <shogun/lib/external/brent.h> #endif //USE_GPL_SHOGUN #include <shogun/mathematics/eigen3.h> #include <shogun/features/DotFeatures.h> #include <shogun/optimization/FirstOrderMinimizer.h> #include <utility> using namespace shogun; using namespace Eigen; namespace shogun { #ifndef DOXYGEN_SHOULD_SKIP_THIS #ifdef USE_GPL_SHOGUN /** Wrapper class used for the Brent minimizer */ class CFITCPsiLine : public func_base { public: float64_t log_scale; VectorXd dalpha; VectorXd start_alpha; SGVector<float64_t>* alpha; SGVector<float64_t>* dlp; SGVector<float64_t>* W; SGVector<float64_t>* f; SGVector<float64_t>* m; std::shared_ptr<LikelihoodModel> lik; std::shared_ptr<Labels> lab; std::shared_ptr<SingleFITCLaplaceInferenceMethod >inf; virtual double operator() (double x) { //time complexity O(m*n) Map<VectorXd> eigen_f(f->vector, f->vlen); Map<VectorXd> eigen_m(m->vector, m->vlen); Map<VectorXd> eigen_alpha(alpha->vector, alpha->vlen); //alpha = alpha + s*dalpha; eigen_alpha=start_alpha+x*dalpha; SGVector<float64_t> tmp=inf->compute_mvmK(*alpha); Map<VectorXd> eigen_tmp(tmp.vector, tmp.vlen); //f = mvmK(alpha,V,d0)+m; eigen_f=eigen_tmp+eigen_m; // get first and second derivatives of log likelihood (*dlp)=lik->get_log_probability_derivative_f(lab, (*f), 1); (*W)=lik->get_log_probability_derivative_f(lab, (*f), 2); W->scale(-1.0); // compute psi=alpha'*(f-m)/2-lp float64_t result = eigen_alpha.dot(eigen_f-eigen_m)/2.0- SGVector<float64_t>::sum(lik->get_log_probability_f(lab, *f)); return result; } }; #endif //USE_GPL_SHOGUN class SingleFITCLaplaceInferenceMethodCostFunction: public FirstOrderCostFunction { public: SingleFITCLaplaceInferenceMethodCostFunction():FirstOrderCostFunction() { init(); } virtual ~SingleFITCLaplaceInferenceMethodCostFunction() { clean(); } void set_target(const std::shared_ptr<SingleFITCLaplaceInferenceMethod >&obj) { require(obj, "Obj must set"); if(m_obj != obj) { m_obj=obj; } } void clean() { } virtual float64_t get_cost() { require(m_obj,"Object not set"); return m_obj->get_psi_wrt_alpha(); } void unset_target(bool is_unref) { if(is_unref) { } m_obj=NULL; } virtual SGVector<float64_t> obtain_variable_reference() { require(m_obj,"Object not set"); m_derivatives = SGVector<float64_t>((m_obj->m_al).vlen); return m_obj->m_al; } virtual SGVector<float64_t> get_gradient() { require(m_obj,"Object not set"); m_obj->get_gradient_wrt_alpha(m_derivatives); return m_derivatives; } virtual const char* get_name() const { return "SingleFITCLaplaceInferenceMethodCostFunction"; } private: void init() { m_obj=NULL; m_derivatives = SGVector<float64_t>(); SG_ADD(&m_derivatives, "SingleFITCLaplaceInferenceMethodCostFunction__m_derivatives", "derivatives in SingleFITCLaplaceInferenceMethodCostFunction"); SG_ADD((std::shared_ptr<SGObject>*)&m_obj, "SingleFITCLaplaceInferenceMethodCostFunction__m_obj", "obj in SingleFITCLaplaceInferenceMethodCostFunction"); } SGVector<float64_t> m_derivatives; std::shared_ptr<SingleFITCLaplaceInferenceMethod >m_obj; }; #endif /* DOXYGEN_SHOULD_SKIP_THIS */ void SingleFITCLaplaceNewtonOptimizer::set_target(const std::shared_ptr<SingleFITCLaplaceInferenceMethod >&obj) { require(obj, "Obj must set"); if(m_obj != obj) { m_obj=obj; } } void SingleFITCLaplaceNewtonOptimizer::unset_target(bool is_unref) { if(is_unref) { } m_obj=NULL; } void SingleFITCLaplaceNewtonOptimizer::init() { m_obj=NULL; m_iter=20; m_tolerance=1e-6; m_opt_tolerance=1e-6; m_opt_max=10; SG_ADD((std::shared_ptr<SGObject>*)&m_obj, "CSingleFITCLaplaceNewtonOptimizer__m_obj", "obj in CSingleFITCLaplaceNewtonOptimizer"); SG_ADD(&m_iter, "CSingleFITCLaplaceNewtonOptimizer__m_iter", "iter in CSingleFITCLaplaceNewtonOptimizer"); SG_ADD(&m_tolerance, "CSingleFITCLaplaceNewtonOptimizer__m_tolerance", "tolerance in CSingleFITCLaplaceNewtonOptimizer"); SG_ADD(&m_opt_tolerance, "CSingleFITCLaplaceNewtonOptimizer__m_opt_tolerance", "opt_tolerance in CSingleFITCLaplaceNewtonOptimizer"); SG_ADD(&m_opt_max, "CSingleFITCLaplaceNewtonOptimizer__m_opt_max", "opt_max in CSingleFITCLaplaceNewtonOptimizer"); } float64_t SingleFITCLaplaceNewtonOptimizer::minimize() { require(m_obj,"Object not set"); //time complexity O(m^2*n); Map<MatrixXd> eigen_kuu((m_obj->m_kuu).matrix, (m_obj->m_kuu).num_rows, (m_obj->m_kuu).num_cols); Map<MatrixXd> eigen_V((m_obj->m_V).matrix, (m_obj->m_V).num_rows, (m_obj->m_V).num_cols); Map<VectorXd> eigen_dg((m_obj->m_dg).vector, (m_obj->m_dg).vlen); Map<MatrixXd> eigen_R0((m_obj->m_chol_R0).matrix, (m_obj->m_chol_R0).num_rows, (m_obj->m_chol_R0).num_cols); Map<VectorXd> eigen_mu(m_obj->m_mu, (m_obj->m_mu).vlen); SGVector<float64_t> mean=m_obj->m_mean->get_mean_vector(m_obj->m_features); Map<VectorXd> eigen_mean(mean.vector, mean.vlen); float64_t Psi_Old=Math::INFTY; float64_t Psi_New=m_obj->m_Psi; // compute W = -d2lp m_obj->m_W=m_obj->m_model->get_log_probability_derivative_f(m_obj->m_labels, m_obj->m_mu, 2); m_obj->m_W.scale(-1.0); //n-by-1 vector Map<VectorXd> eigen_al((m_obj->m_al).vector, (m_obj->m_al).vlen); // get first derivative of log probability function m_obj->m_dlp=m_obj->m_model->get_log_probability_derivative_f(m_obj->m_labels, m_obj->m_mu, 1); index_t iter=0; m_obj->m_Wneg=false; while (Psi_Old-Psi_New>m_tolerance && iter<m_iter) { //time complexity O(m^2*n) Map<VectorXd> eigen_W((m_obj->m_W).vector, (m_obj->m_W).vlen); Map<VectorXd> eigen_dlp((m_obj->m_dlp).vector, (m_obj->m_dlp).vlen); Psi_Old = Psi_New; iter++; if (eigen_W.minCoeff() < 0) { // Suggested by Vanhatalo et. al., // Gaussian Process Regression with Student's t likelihood, NIPS 2009 // Quoted from infFITC_Laplace.m float64_t df; if (m_obj->m_model->get_model_type()==LT_STUDENTST) { auto lik = m_obj->m_model->as<StudentsTLikelihood>(); df=lik->get_degrees_freedom(); } else df=1; eigen_W+=(2.0/(df+1))*eigen_dlp.cwiseProduct(eigen_dlp); } //b = W.*(f-m) + dlp; VectorXd b=eigen_W.cwiseProduct(eigen_mu-eigen_mean)+eigen_dlp; //dd = 1./(1+W.*d0); VectorXd dd=MatrixXd::Ones(b.rows(),1).cwiseQuotient(eigen_W.cwiseProduct(eigen_dg)+MatrixXd::Ones(b.rows(),1)); VectorXd eigen_t=eigen_W.cwiseProduct(dd); //m-by-m matrix SGMatrix<float64_t> tmp( (m_obj->m_V).num_rows, (m_obj->m_V).num_rows); Map<MatrixXd> eigen_tmp(tmp.matrix, tmp.num_rows, tmp.num_cols); //eye(nu)+(V.*repmat((W.*dd)',nu,1))*V' eigen_tmp=eigen_V*eigen_t.asDiagonal()*eigen_V.transpose()+MatrixXd::Identity(tmp.num_rows,tmp.num_rows); tmp=m_obj->get_chol_inv(tmp); //chol_inv(eye(nu)+(V.*repmat((W.*dd)',nu,1))*V') Map<MatrixXd> eigen_tmp2(tmp.matrix, tmp.num_rows, tmp.num_cols); //RV = chol_inv(eye(nu)+(V.*repmat((W.*dd)',nu,1))*V')*V; // m-by-n matrix MatrixXd eigen_RV=eigen_tmp2*eigen_V; //dalpha = dd.*b - (W.*dd).*(RV'*(RV*(dd.*b))) - alpha; % Newt dir + line search VectorXd dalpha=dd.cwiseProduct(b)-eigen_t.cwiseProduct(eigen_RV.transpose()*(eigen_RV*(dd.cwiseProduct(b))))-eigen_al; #ifdef USE_GPL_SHOGUN //perform Brent's optimization CFITCPsiLine func; func.log_scale=m_obj->m_log_scale; func.dalpha=dalpha; func.start_alpha=eigen_al; func.alpha=&(m_obj->m_al); func.dlp=&(m_obj->m_dlp); func.f=&(m_obj->m_mu); func.m=&mean; func.W=&(m_obj->m_W); func.lik=m_obj->m_model; func.lab=m_obj->m_labels; func.inf=m_obj; float64_t x; Psi_New=local_min(0, m_opt_max, m_opt_tolerance, func, x); #else gpl_only(SOURCE_LOCATION); #endif //USE_GPL_SHOGUN } if (Psi_Old-Psi_New>m_tolerance && iter>=m_iter) { io::warn("Max iterations ({}) reached, but convergence level ({}) is not yet below tolerance ({})", m_iter, Psi_Old-Psi_New, m_tolerance); } return Psi_New; } SingleFITCLaplaceInferenceMethod::SingleFITCLaplaceInferenceMethod() : SingleFITCInference() { init(); } SingleFITCLaplaceInferenceMethod::SingleFITCLaplaceInferenceMethod(std::shared_ptr<Kernel> kern, std::shared_ptr<Features> feat, std::shared_ptr<MeanFunction> m, std::shared_ptr<Labels> lab, std::shared_ptr<LikelihoodModel> mod, std::shared_ptr<Features> lat) : SingleFITCInference(std::move(kern), std::move(feat), std::move(m), std::move(lab), std::move(mod), std::move(lat)) { init(); } void SingleFITCLaplaceInferenceMethod::init() { m_Psi=0; m_Wneg=false; SG_ADD(&m_dlp, "dlp", "derivative of log likelihood with respect to function location"); SG_ADD(&m_W, "W", "the noise matrix"); SG_ADD(&m_sW, "sW", "square root of W"); SG_ADD(&m_d2lp, "d2lp", "second derivative of log likelihood with respect to function location"); SG_ADD(&m_d3lp, "d3lp", "third derivative of log likelihood with respect to function location"); SG_ADD(&m_chol_R0, "chol_R0", "Cholesky of inverse covariance of inducing features"); SG_ADD(&m_dfhat, "dfhat", "derivative of negative log (approximated) marginal likelihood wrt f"); SG_ADD(&m_g, "g", "variable g defined in infFITC_Laplace.m"); SG_ADD(&m_dg, "dg", "variable d0 defined in infFITC_Laplace.m"); SG_ADD(&m_Psi, "Psi", "the negative log likelihood without constant terms used in Newton's method"); SG_ADD(&m_Wneg, "Wneg", "whether W contains negative elements"); register_minimizer(std::make_shared<SingleFITCLaplaceNewtonOptimizer>()); } void SingleFITCLaplaceInferenceMethod::compute_gradient() { Inference::compute_gradient(); if (!m_gradient_update) { update_approx_cov(); update_deriv(); m_gradient_update=true; update_parameter_hash(); } } void SingleFITCLaplaceInferenceMethod::update() { SG_TRACE("entering"); Inference::update(); update_init(); update_alpha(); update_chol(); m_gradient_update=false; update_parameter_hash(); SG_TRACE("leaving"); } SGVector<float64_t> SingleFITCLaplaceInferenceMethod::get_diagonal_vector() { if (parameter_hash_changed()) update(); return SGVector<float64_t>(m_sW); } SingleFITCLaplaceInferenceMethod::~SingleFITCLaplaceInferenceMethod() { } SGVector<float64_t> SingleFITCLaplaceInferenceMethod::compute_mvmZ(SGVector<float64_t> x) { //time complexity O(m*n) Map<MatrixXd> eigen_Rvdd(m_Rvdd.matrix, m_Rvdd.num_rows, m_Rvdd.num_cols); Map<VectorXd> eigen_t(m_t.vector, m_t.vlen); Map<VectorXd> eigen_x(x.vector, x.vlen); SGVector<float64_t> res(x.vlen); Map<VectorXd> eigen_res(res.vector, res.vlen); //Zx = t.*x - RVdd'*(RVdd*x); eigen_res=eigen_x.cwiseProduct(eigen_t)-eigen_Rvdd.transpose()*(eigen_Rvdd*eigen_x); return res; } SGVector<float64_t> SingleFITCLaplaceInferenceMethod::compute_mvmK(SGVector<float64_t> al) { //time complexity O(m*n) Map<MatrixXd> eigen_V(m_V.matrix, m_V.num_rows, m_V.num_cols); Map<VectorXd> eigen_dg(m_dg.vector, m_dg.vlen); Map<VectorXd> eigen_al(al.vector, al.vlen); SGVector<float64_t> res(al.vlen); Map<VectorXd> eigen_res(res.vector, res.vlen); //Kal = V'*(V*al) + d0.*al; eigen_res= eigen_V.transpose()*(eigen_V*eigen_al)+eigen_dg.cwiseProduct(eigen_al); return res; } std::shared_ptr<SingleFITCLaplaceInferenceMethod> SingleFITCLaplaceInferenceMethod::obtain_from_generic( const std::shared_ptr<Inference>& inference) { require(inference!=NULL, "Inference should be not NULL"); if (inference->get_inference_type()!=INF_FITC_LAPLACE_SINGLE) error("Provided inference is not of type SingleFITCLaplaceInferenceMethod!"); return inference->as<SingleFITCLaplaceInferenceMethod>(); } SGMatrix<float64_t> SingleFITCLaplaceInferenceMethod::get_chol_inv(SGMatrix<float64_t> mtx) { //time complexity O(m^3), where mtx is a m-by-m matrix require(mtx.num_rows==mtx.num_cols, "Matrix must be square"); Map<MatrixXd> eigen_mtx(mtx.matrix, mtx.num_rows, mtx.num_cols); LLT<MatrixXd> chol(eigen_mtx.colwise().reverse().rowwise().reverse().matrix()); //tmp=chol(rot180(A))' MatrixXd tmp=chol.matrixL(); SGMatrix<float64_t> res(mtx.num_rows, mtx.num_cols); Map<MatrixXd> eigen_res(res.matrix, res.num_rows, res.num_cols); //chol_inv = @(A) rot180(chol(rot180(A))')\eye(nu); % chol(inv(A)) eigen_res=tmp.colwise().reverse().rowwise().reverse().matrix().triangularView<Upper>( ).solve(MatrixXd::Identity(mtx.num_rows, mtx.num_cols)); return res; } float64_t SingleFITCLaplaceInferenceMethod::get_negative_log_marginal_likelihood() { if (parameter_hash_changed()) update(); if (m_Wneg) { io::warn("nlZ cannot be computed since W is too negative"); //nlZ = NaN; return Math::INFTY; } //time complexity O(m^2*n) Map<VectorXd> eigen_alpha(m_al.vector, m_al.vlen); Map<VectorXd> eigen_mu(m_mu.vector, m_mu.vlen); SGVector<float64_t> mean=m_mean->get_mean_vector(m_features); Map<VectorXd> eigen_mean(mean.vector, mean.vlen); // get log likelihood float64_t lp=SGVector<float64_t>::sum(m_model->get_log_probability_f(m_labels, m_mu)); Map<MatrixXd> eigen_V(m_V.matrix, m_V.num_rows, m_V.num_cols); Map<VectorXd>eigen_t(m_t.vector, m_t.vlen); MatrixXd A=eigen_V*eigen_t.asDiagonal()*eigen_V.transpose()+MatrixXd::Identity(m_V.num_rows,m_V.num_rows); LLT<MatrixXd> chol(A); A=chol.matrixU(); Map<VectorXd> eigen_dg(m_dg.vector, m_dg.vlen); Map<VectorXd> eigen_W(m_W.vector, m_W.vlen); //nlZ = alpha'*(f-m)/2 - sum(lp) - sum(log(dd))/2 + sum(log(diag(chol(A)))); float64_t result=eigen_alpha.dot(eigen_mu-eigen_mean)/2.0-lp+ A.diagonal().array().log().sum()+(eigen_W.cwiseProduct(eigen_dg)+MatrixXd::Ones(eigen_dg.rows(),1)).array().log().sum()/2.0; return result; } void SingleFITCLaplaceInferenceMethod::update_approx_cov() { } void SingleFITCLaplaceInferenceMethod::update_init() { //time complexity O(m^2*n) //m-by-m matrix Map<MatrixXd> eigen_kuu(m_kuu.matrix, m_kuu.num_rows, m_kuu.num_cols); //m-by-n matrix Map<MatrixXd> eigen_ktru(m_ktru.matrix, m_ktru.num_rows, m_ktru.num_cols); Map<VectorXd> eigen_ktrtr_diag(m_ktrtr_diag.vector, m_ktrtr_diag.vlen); SGMatrix<float64_t> cor_kuu(m_kuu.num_rows, m_kuu.num_cols); Map<MatrixXd> eigen_cor_kuu(cor_kuu.matrix, cor_kuu.num_rows, cor_kuu.num_cols); eigen_cor_kuu = eigen_kuu * std::exp(m_log_scale * 2.0) + std::exp(m_log_ind_noise) * MatrixXd::Identity(m_kuu.num_rows, m_kuu.num_cols); //R0 = chol_inv(Kuu+snu2*eye(nu)); m-by-m matrix m_chol_R0=get_chol_inv(cor_kuu); Map<MatrixXd> eigen_R0(m_chol_R0.matrix, m_chol_R0.num_rows, m_chol_R0.num_cols); //V = R0*Ku; m-by-n matrix m_V=SGMatrix<float64_t>(m_chol_R0.num_cols, m_ktru.num_cols); Map<MatrixXd> eigen_V(m_V.matrix, m_V.num_rows, m_V.num_cols); eigen_V = eigen_R0 * (eigen_ktru * std::exp(m_log_scale * 2.0)); m_dg=SGVector<float64_t>(m_ktrtr_diag.vlen); Map<VectorXd> eigen_dg(m_dg.vector, m_dg.vlen); //d0 = diagK-sum(V.*V,1)'; eigen_dg = eigen_ktrtr_diag * std::exp(m_log_scale * 2.0) - (eigen_V.cwiseProduct(eigen_V)).colwise().sum().adjoint(); // get mean vector and create eigen representation of it m_mean_f=m_mean->get_mean_vector(m_features); Map<VectorXd> eigen_mean(m_mean_f.vector, m_mean_f.vlen); // create shogun and eigen representation of function vector m_mu=SGVector<float64_t>(m_mean_f.vlen); Map<VectorXd> eigen_mu(m_mu, m_mu.vlen); float64_t Psi_New; float64_t Psi_Def; if (m_al.vlen!=m_labels->get_num_labels()) { // set alpha a zero vector m_al=SGVector<float64_t>(m_labels->get_num_labels()); m_al.zero(); // f = mean, if length of alpha and length of y doesn't match eigen_mu=eigen_mean; Psi_New=-SGVector<float64_t>::sum(m_model->get_log_probability_f( m_labels, m_mu)); } else { Map<VectorXd> eigen_alpha(m_al.vector, m_al.vlen); // compute f = K * alpha + m SGVector<float64_t> tmp=compute_mvmK(m_al); Map<VectorXd> eigen_tmp(tmp.vector, tmp.vlen); eigen_mu=eigen_tmp+eigen_mean; Psi_New=eigen_alpha.dot(eigen_tmp)/2.0- SGVector<float64_t>::sum(m_model->get_log_probability_f(m_labels, m_mu)); Psi_Def=-SGVector<float64_t>::sum(m_model->get_log_probability_f(m_labels, m_mean_f)); // if default is better, then use it if (Psi_Def < Psi_New) { m_al.zero(); eigen_mu=eigen_mean; Psi_New=Psi_Def; } } m_Psi=Psi_New; } void SingleFITCLaplaceInferenceMethod::register_minimizer(std::shared_ptr<Minimizer> minimizer) { require(minimizer, "Minimizer must set"); if (!std::dynamic_pointer_cast<SingleFITCLaplaceNewtonOptimizer>(minimizer)) { auto opt= std::dynamic_pointer_cast<FirstOrderMinimizer>(minimizer); require(opt, "The provided minimizer is not supported"); } Inference::register_minimizer(minimizer); } void SingleFITCLaplaceInferenceMethod::update_alpha() { auto opt=std::dynamic_pointer_cast<SingleFITCLaplaceNewtonOptimizer>(m_minimizer); bool cleanup=false; if (opt) { opt->set_target(shared_from_this()->as<SingleFITCLaplaceInferenceMethod>()); opt->minimize(); } else { auto minimizer= std::dynamic_pointer_cast<FirstOrderMinimizer>(m_minimizer); require(minimizer, "The provided minimizer is not supported"); auto cost_fun=std::make_shared<SingleFITCLaplaceInferenceMethodCostFunction>(); cost_fun->set_target(shared_from_this()->as<SingleFITCLaplaceInferenceMethod>()); minimizer->set_cost_function(cost_fun); minimizer->minimize(); minimizer->unset_cost_function(false); } Map<VectorXd> eigen_mean(m_mean_f.vector, m_mean_f.vlen); Map<MatrixXd> eigen_V(m_V.matrix, m_V.num_rows, m_V.num_cols); Map<MatrixXd> eigen_R0(m_chol_R0.matrix, m_chol_R0.num_rows, m_chol_R0.num_cols); Map<VectorXd> eigen_mu(m_mu, m_mu.vlen); Map<VectorXd> eigen_al(m_al.vector, m_al.vlen); // compute f = K * alpha + m SGVector<float64_t> tmp=compute_mvmK(m_al); Map<VectorXd> eigen_tmp(tmp.vector, tmp.vlen); eigen_mu=eigen_tmp+eigen_mean; m_alpha=SGVector<float64_t>(m_chol_R0.num_cols); Map<VectorXd> eigen_post_alpha(m_alpha.vector, m_alpha.vlen); //post.alpha = R0'*(V*alpha); //m-by-1 vector eigen_post_alpha=eigen_R0.transpose()*(eigen_V*eigen_al); } void SingleFITCLaplaceInferenceMethod::update_chol() { //time complexity O(m^2*n) Map<VectorXd> eigen_dg(m_dg.vector, m_dg.vlen); Map<MatrixXd> eigen_R0(m_chol_R0.matrix, m_chol_R0.num_rows, m_chol_R0.num_cols); Map<MatrixXd> eigen_V(m_V.matrix, m_V.num_rows, m_V.num_cols); // get log probability derivatives m_dlp=m_model->get_log_probability_derivative_f(m_labels, m_mu, 1); m_d2lp=m_model->get_log_probability_derivative_f(m_labels, m_mu, 2); m_d3lp=m_model->get_log_probability_derivative_f(m_labels, m_mu, 3); // W = -d2lp m_W=m_d2lp.clone(); m_W.scale(-1.0); Map<VectorXd> eigen_W(m_W.vector, m_W.vlen); m_sW=SGVector<float64_t>(m_W.vlen); Map<VectorXd> eigen_sW(m_sW.vector, m_sW.vlen); VectorXd Wd0_1=eigen_W.cwiseProduct(eigen_dg)+MatrixXd::Ones(eigen_W.rows(),1); // compute sW // post.sW = sqrt(abs(W)).*sign(W); % preserve sign in case of negative if (eigen_W.minCoeff()>0) { eigen_sW=eigen_W.cwiseSqrt(); } else { eigen_sW=((eigen_W.array().abs()+eigen_W.array())/2).sqrt()-((eigen_W.array().abs()-eigen_W.array())/2).sqrt(); //any(1+d0.*W<0) if (!(Wd0_1.array().abs().matrix()==Wd0_1)) m_Wneg=true; } m_t=SGVector<float64_t>(m_W.vlen); Map<VectorXd>eigen_t(m_t.vector, m_t.vlen); //dd = 1./(1+d0.*W); VectorXd dd=MatrixXd::Ones(Wd0_1.rows(),1).cwiseQuotient(Wd0_1); eigen_t=eigen_W.cwiseProduct(dd); //m-by-m matrix SGMatrix<float64_t> A(m_V.num_rows, m_V.num_rows); Map<MatrixXd> eigen_A(A.matrix, A.num_rows, A.num_cols); //A = eye(nu)+(V.*repmat((W.*dd)',nu,1))*V'; eigen_A=eigen_V*eigen_t.asDiagonal()*eigen_V.transpose()+MatrixXd::Identity(A.num_rows,A.num_rows); //R0tV = R0'*V; m-by-n MatrixXd R0tV=eigen_R0.transpose()*eigen_V; //B = R0tV.*repmat((W.*dd)',nu,1); m-by-n matrix MatrixXd B=R0tV*eigen_t.asDiagonal(); //m-by-m matrix m_L=SGMatrix<float64_t>(m_kuu.num_rows, m_kuu.num_cols); Map<MatrixXd> eigen_L(m_L.matrix, m_L.num_rows, m_L.num_cols); //post.L = -B*R0tV'; eigen_L=-B*R0tV.transpose(); SGMatrix<float64_t> tmp=get_chol_inv(A); Map<MatrixXd> eigen_tmp(tmp.matrix, tmp.num_rows, tmp.num_cols); //RV = chol_inv(A)*V; m-by-n matrix MatrixXd eigen_RV=eigen_tmp*eigen_V; //RVdd m-by-n matrix m_Rvdd=SGMatrix<float64_t>(m_V.num_rows, m_V.num_cols); Map<MatrixXd> eigen_Rvdd(m_Rvdd.matrix, m_Rvdd.num_rows, m_Rvdd.num_cols); //RVdd = RV.*repmat((W.*dd)',nu,1); eigen_Rvdd=eigen_RV*eigen_t.asDiagonal(); if (!m_Wneg) { //B = B*RV'; B=B*eigen_RV.transpose(); //post.L = post.L + B*B'; eigen_L+=B*B.transpose(); } else { //B = B*V'; B=B*eigen_V.transpose(); //post.L = post.L + (B*inv(A))*B'; FullPivLU<MatrixXd> lu(eigen_A); eigen_L+=B*lu.inverse()*B.transpose(); } Map<MatrixXd> eigen_ktru(m_ktru.matrix, m_ktru.num_rows, m_ktru.num_cols); m_g=SGVector<float64_t>(m_dg.vlen); Map<VectorXd> eigen_g(m_g.vector, m_g.vlen); //g = d/2 + sum(((R*R0)*P).^2,1)'/2 eigen_g = ((eigen_dg.cwiseProduct(dd)).array() + ((eigen_tmp * eigen_R0) * (eigen_ktru * std::exp(m_log_scale * 2.0)) * dd.asDiagonal()) .array() .pow(2) .colwise() .sum() .transpose()) / 2; } void SingleFITCLaplaceInferenceMethod::update_deriv() { //time complexity O(m^2*n) Map<MatrixXd> eigen_ktru(m_ktru.matrix, m_ktru.num_rows, m_ktru.num_cols); Map<MatrixXd> eigen_R0(m_chol_R0.matrix, m_chol_R0.num_rows, m_chol_R0.num_cols); Map<VectorXd> eigen_al(m_al.vector, m_al.vlen); Map<MatrixXd> eigen_V(m_V.matrix, m_V.num_rows, m_V.num_cols); // create shogun and eigen representation of B // m-by-n matrix m_B=SGMatrix<float64_t>(m_ktru.num_rows, m_ktru.num_cols); Map<MatrixXd> eigen_B(m_B.matrix, m_B.num_rows, m_B.num_cols); //B = (R0'*R0)*Ku eigen_B=eigen_R0.transpose()*eigen_V; // create shogun and eigen representation of w m_w=SGVector<float64_t>(m_B.num_rows); //w = B*al; Map<VectorXd> eigen_w(m_w.vector, m_w.vlen); eigen_w=eigen_B*eigen_al; // create shogun and eigen representation of the vector dfhat Map<VectorXd> eigen_d3lp(m_d3lp.vector, m_d3lp.vlen); Map<VectorXd> eigen_g(m_g.vector, m_g.vlen); m_dfhat=SGVector<float64_t>(m_g.vlen); Map<VectorXd> eigen_dfhat(m_dfhat.vector, m_dfhat.vlen); // compute derivative of nlZ wrt fhat // dfhat = g.*d3lp; eigen_dfhat=eigen_g.cwiseProduct(eigen_d3lp); } float64_t SingleFITCLaplaceInferenceMethod::get_derivative_related_cov(SGVector<float64_t> ddiagKi, SGMatrix<float64_t> dKuui, SGMatrix<float64_t> dKui) { //time complexity O(m^2*n) Map<MatrixXd> eigen_R0tV(m_B.matrix, m_B.num_rows, m_B.num_cols); Map<VectorXd> eigen_ddiagKi(ddiagKi.vector, ddiagKi.vlen); //m-by-m matrix Map<MatrixXd> eigen_dKuui(dKuui.matrix, dKuui.num_rows, dKuui.num_cols); //m-by-n matrix Map<MatrixXd> eigen_dKui(dKui.matrix, dKui.num_rows, dKui.num_cols); // compute R=2*dKui-dKuui*B SGMatrix<float64_t> dA(dKui.num_rows, dKui.num_cols); Map<MatrixXd> eigen_dA(dA.matrix, dA.num_rows, dA.num_cols); //dA = 2*dKu'-R0tV'*dKuu; //dA' = 2*dKu-dKuu'*R0tV; eigen_dA=2*eigen_dKui-eigen_dKuui*eigen_R0tV; SGVector<float64_t> v(ddiagKi.vlen); Map<VectorXd> eigen_v(v.vector, v.vlen); //w = sum(dA.*R0tV',2); //w' = sum(dA'.*R0tV,1); //v = ddiagK-w; eigen_v=eigen_ddiagKi-eigen_dA.cwiseProduct(eigen_R0tV).colwise().sum().transpose(); //explicit term float64_t result=SingleFITCInference::get_derivative_related_cov(ddiagKi, dKuui, dKui, v, dA); //implicit term Map<VectorXd> eigen_dlp(m_dlp.vector, m_dlp.vlen); Map<VectorXd> eigen_dfhat(m_dfhat.vector, m_dfhat.vlen); SGVector<float64_t> b(v.vlen); Map<VectorXd> eigen_b(b.vector, b.vlen); //b = dA*(R0tV*dlp) + v.*dlp; eigen_b=eigen_dA.transpose()*(eigen_R0tV*eigen_dlp)+eigen_v.cwiseProduct(eigen_dlp); //KZb = mvmK(mvmZ(b,RVdd,t),V,d0); SGVector<float64_t> KZb=compute_mvmK(compute_mvmZ(b)); Map<VectorXd> eigen_KZb(KZb.vector, KZb.vlen); //dnlZ.cov(i) = dnlZ.cov(i) - dfhat'*( b-KZb ); result-=eigen_dfhat.dot(eigen_b-eigen_KZb); return result; } SGVector<float64_t> SingleFITCLaplaceInferenceMethod::get_derivative_wrt_inference_method( Parameters::const_reference param) { //time complexity O(m^2*n); require(param.first == "log_scale" || param.first == "log_inducing_noise" || param.first == "inducing_features", "Can't compute derivative of" " the nagative log marginal likelihood wrt {}.{} parameter", get_name(), param.first); SGVector<float64_t> result; int32_t len; if (param.first == "inducing_features") { if(m_Wneg) { auto inducing_feat = m_inducing_features->as<DotFeatures>(); int32_t dim = inducing_feat->get_dim_feature_space(); int32_t num_samples = inducing_feat->get_num_vectors(); len=dim*num_samples; } else if (!m_fully_sparse) return SingleFITCInference::get_derivative_wrt_inference_method(param); else return get_derivative_wrt_inducing_features(param); } else len=1; if (m_Wneg) { result=SGVector<float64_t>(len); return derivative_helper_when_Wneg(result, param); } if (param.first == "log_inducing_noise") // wrt inducing_noise // compute derivative wrt inducing noise return get_derivative_wrt_inducing_noise(param); result=SGVector<float64_t>(len); // wrt scale // clone kernel matrices SGVector<float64_t> deriv_trtr=m_ktrtr_diag.clone(); SGMatrix<float64_t> deriv_uu=m_kuu.clone(); SGMatrix<float64_t> deriv_tru=m_ktru.clone(); // create eigen representation of kernel matrices Map<VectorXd> ddiagKi(deriv_trtr.vector, deriv_trtr.vlen); Map<MatrixXd> dKuui(deriv_uu.matrix, deriv_uu.num_rows, deriv_uu.num_cols); Map<MatrixXd> dKui(deriv_tru.matrix, deriv_tru.num_rows, deriv_tru.num_cols); // compute derivatives wrt scale for each kernel matrix result[0]=get_derivative_related_cov(deriv_trtr, deriv_uu, deriv_tru); result[0] *= std::exp(m_log_scale * 2.0) * 2.0; return result; } SGVector<float64_t> SingleFITCLaplaceInferenceMethod::get_derivative_wrt_likelihood_model( Parameters::const_reference param) { SGVector<float64_t> result(1); if (m_Wneg) return derivative_helper_when_Wneg(result, param); // get derivatives wrt likelihood model parameters SGVector<float64_t> lp_dhyp=m_model->get_first_derivative(m_labels, m_mu, param); SGVector<float64_t> dlp_dhyp=m_model->get_second_derivative(m_labels, m_mu, param); SGVector<float64_t> d2lp_dhyp=m_model->get_third_derivative(m_labels, m_mu, param); // create eigen representation of the derivatives Map<VectorXd> eigen_lp_dhyp(lp_dhyp.vector, lp_dhyp.vlen); Map<VectorXd> eigen_dlp_dhyp(dlp_dhyp.vector, dlp_dhyp.vlen); Map<VectorXd> eigen_d2lp_dhyp(d2lp_dhyp.vector, d2lp_dhyp.vlen); Map<VectorXd> eigen_g(m_g.vector, m_g.vlen); Map<VectorXd> eigen_dfhat(m_dfhat.vector, m_dfhat.vlen); //explicit term //dnlZ.lik(i) = -g'*d2lp_dhyp - sum(lp_dhyp); result[0]=-eigen_g.dot(eigen_d2lp_dhyp)-eigen_lp_dhyp.sum(); //implicit term //b = mvmK(dlp_dhyp,V,d0); SGVector<float64_t> b=compute_mvmK(dlp_dhyp); //dnlZ.lik(i) = dnlZ.lik(i) - dfhat'*(b-mvmK(mvmZ(b,RVdd,t),V,d0)); result[0]-= get_derivative_implicit_term_helper(b); return result; } SGVector<float64_t> SingleFITCLaplaceInferenceMethod::get_derivative_wrt_kernel( Parameters::const_reference param) { SGVector<float64_t> result; auto visitor = std::make_unique<ShapeVisitor>(); param.second->get_value().visit(visitor.get()); int64_t len= visitor->get_size(); result=SGVector<float64_t>(len); if (m_Wneg) return derivative_helper_when_Wneg(result, param); m_lock.lock(); auto inducing_features=get_inducing_features(); for (index_t i=0; i<result.vlen; i++) { //time complexity O(m^2*n) SGVector<float64_t> deriv_trtr; SGMatrix<float64_t> deriv_uu; SGMatrix<float64_t> deriv_tru; m_kernel->init(m_features, m_features); deriv_trtr=m_kernel->get_parameter_gradient_diagonal(param, i); m_kernel->init(inducing_features, inducing_features); deriv_uu=m_kernel->get_parameter_gradient(param, i); m_kernel->init(inducing_features, m_features); deriv_tru=m_kernel->get_parameter_gradient(param, i); // create eigen representation of derivatives Map<VectorXd> ddiagKi(deriv_trtr.vector, deriv_trtr.vlen); Map<MatrixXd> dKuui(deriv_uu.matrix, deriv_uu.num_rows, deriv_uu.num_cols); Map<MatrixXd> dKui(deriv_tru.matrix, deriv_tru.num_rows, deriv_tru.num_cols); result[i]=get_derivative_related_cov(deriv_trtr, deriv_uu, deriv_tru); result[i] *= std::exp(m_log_scale * 2.0); } m_lock.unlock(); return result; } float64_t SingleFITCLaplaceInferenceMethod::get_derivative_related_mean(SGVector<float64_t> dmu) { //time complexity O(m*n) //explicit term float64_t result=SingleFITCInference::get_derivative_related_mean(dmu); //implicit term //Zdm = mvmZ(dm,RVdd,t); //tmp = mvmK(Zdm,V,d0) //dnlZ.mean(i) = dnlZ.mean(i) - dfhat'*(dm-mvmK(Zdm,V,d0)); result-=get_derivative_implicit_term_helper(dmu); return result; } float64_t SingleFITCLaplaceInferenceMethod::get_derivative_implicit_term_helper(SGVector<float64_t> d) { //time complexity O(m*n) Map<VectorXd> eigen_d(d.vector, d.vlen); SGVector<float64_t> tmp=compute_mvmK(compute_mvmZ(d)); Map<VectorXd> eigen_tmp(tmp.vector, tmp.vlen); Map<VectorXd> eigen_dfhat(m_dfhat.vector, m_dfhat.vlen); return eigen_dfhat.dot(eigen_d-eigen_tmp); } SGVector<float64_t> SingleFITCLaplaceInferenceMethod::get_derivative_wrt_mean( Parameters::const_reference param) { //time complexity O(m*n) SGVector<float64_t> result; auto visitor = std::make_unique<ShapeVisitor>(); param.second->get_value().visit(visitor.get()); int64_t len= visitor->get_size(); result=SGVector<float64_t>(len); if (m_Wneg) return derivative_helper_when_Wneg(result, param); for (index_t i=0; i<result.vlen; i++) { SGVector<float64_t> dmu; dmu=m_mean->get_parameter_derivative(m_features, param, i); result[i]=get_derivative_related_mean(dmu); } return result; } SGVector<float64_t> SingleFITCLaplaceInferenceMethod::derivative_helper_when_Wneg( SGVector<float64_t> res, Parameters::const_reference param) { io::warn("Derivative wrt {} cannot be computed since W (the Hessian (diagonal) matrix) is too negative", param.first); //dnlZ = struct('cov',0*hyp.cov, 'mean',0*hyp.mean, 'lik',0*hyp.lik); res.zero(); return res; } SGVector<float64_t> SingleFITCLaplaceInferenceMethod::get_derivative_wrt_inducing_features( Parameters::const_reference param) { //time complexity depends on the implementation of the provided kernel //time complexity is at least O(max((p*n*m),(m^2*n))), where p is the dimension (#) of features //For an ARD kernel with KL_FULL, the time complexity is O(max((p*n*m*d),(m^2*n))) //where the paramter \f$\Lambda\f$ of the ARD kerenl is a \f$d\f$-by-\f$p\f$ matrix, //For an ARD kernel with KL_SCALE and KL_DIAG, the time complexity is O(max((p*n*m),(m^2*n))) //efficiently compute the implicit term and explicit term at one shot Map<VectorXd> eigen_al(m_al.vector, m_al.vlen); Map<MatrixXd> eigen_Rvdd(m_Rvdd.matrix, m_Rvdd.num_rows, m_Rvdd.num_cols); //w=B*al Map<VectorXd> eigen_w(m_w.vector, m_w.vlen); Map<MatrixXd> eigen_B(m_B.matrix, m_B.num_rows, m_B.num_cols); Map<VectorXd> eigen_dlp(m_dlp.vector, m_dlp.vlen); Map<VectorXd> eigen_dfhat(m_dfhat.vector, m_dfhat.vlen); //q = dfhat - mvmZ(mvmK(dfhat,V,d0),RVdd,t); SGVector<float64_t> q=compute_mvmZ(compute_mvmK(m_dfhat)); Map<VectorXd> eigen_q(q.vector, q.vlen); eigen_q=eigen_dfhat-eigen_q; //explicit term //diag_dK = alpha.*alpha + sum(RVdd.*RVdd,1)'-t, where t can be cancelled out //-v_1=get_derivative_related_cov_diagonal= -(alpha.*alpha + sum(RVdd.*RVdd,1)') //implicit term //-v_2=-2*dlp.*q //neg_v = -(diag_dK+ 2*dlp.*q); SGVector<float64_t> neg_v=get_derivative_related_cov_diagonal(); Map<VectorXd> eigen_neg_v(neg_v.vector, neg_v.vlen); eigen_neg_v-=2*eigen_dlp.cwiseProduct(eigen_q); SGMatrix<float64_t> BdK(m_B.num_rows, m_B.num_cols); Map<MatrixXd> eigen_BdK(BdK.matrix, BdK.num_rows, BdK.num_cols); //explicit //BdK = (B*alpha)*alpha' + (B*RVdd')*RVdd - B.*repmat(v_1',nu,1), //implicit //BdK = BdK + (B*dlp)*q' + (B*q)*dlp' - B.*repmat(v_2',nu,1) //where v_1 is the explicit part of v and v_2 is the implicit part of v //v=v_1+v_2 eigen_BdK=eigen_B*eigen_neg_v.asDiagonal()+eigen_w*(eigen_al.transpose())+ (eigen_B*eigen_Rvdd.transpose())*eigen_Rvdd+ (eigen_B*eigen_dlp)*eigen_q.transpose()+(eigen_B*eigen_q)*eigen_dlp.transpose(); return get_derivative_related_inducing_features(BdK, param); } SGVector<float64_t> SingleFITCLaplaceInferenceMethod::get_derivative_wrt_inducing_noise( Parameters::const_reference param) { //time complexity O(m^2*n) //explicit term SGVector<float64_t> result=SingleFITCInference::get_derivative_wrt_inducing_noise(param); //implicit term Map<MatrixXd> eigen_B(m_B.matrix, m_B.num_rows, m_B.num_cols); Map<VectorXd> eigen_dlp(m_dlp.vector, m_dlp.vlen); //snu = sqrt(snu2); //T = chol_inv(Kuu + snu2*eye(nu)); T = T'*(T*(snu*Ku)); //t1 = sum(T.*T,1)'; VectorXd eigen_t1=eigen_B.cwiseProduct(eigen_B).colwise().sum().adjoint(); //b = (t1.*dlp-T'*(T*dlp))*2; SGVector<float64_t> b(eigen_t1.rows()); Map<VectorXd> eigen_b(b.vector, b.vlen); float64_t factor = 2.0 * std::exp(m_log_ind_noise); eigen_b=(eigen_t1.cwiseProduct(eigen_dlp)-eigen_B.transpose()*(eigen_B*eigen_dlp))*factor; //KZb = mvmK(mvmZ(b,RVdd,t),V,d0); //z = z - dfhat'*( b-KZb ); result[0]-=get_derivative_implicit_term_helper(b); return result; } SGVector<float64_t> SingleFITCLaplaceInferenceMethod::get_posterior_mean() { compute_gradient(); SGVector<float64_t> res(m_mu.vlen); Map<VectorXd> eigen_res(res.vector, res.vlen); /* //true posterior mean with equivalent FITC prior approximated by Newton method //time complexity O(n) Map<VectorXd> eigen_mu(m_mu, m_mu.vlen); SGVector<float64_t> mean=m_mean->get_mean_vector(m_features); Map<VectorXd> eigen_mean(mean.vector, mean.vlen); eigen_res=eigen_mu-eigen_mean; */ //FITC (further) approximated posterior mean with Netwon method //time complexity of the following operation is O(m*n) Map<VectorXd> eigen_post_alpha(m_alpha.vector, m_alpha.vlen); Map<MatrixXd> eigen_Ktru(m_ktru.matrix, m_ktru.num_rows, m_ktru.num_cols); eigen_res = std::exp(m_log_scale * 2.0) * eigen_Ktru.adjoint() * eigen_post_alpha; return res; } SGMatrix<float64_t> SingleFITCLaplaceInferenceMethod::get_posterior_covariance() { compute_gradient(); //time complexity of the following operations is O(m*n^2) //Warning: the the time complexity increases from O(m^2*n) to O(n^2*m) if this method is called m_Sigma=SGMatrix<float64_t>(m_ktrtr_diag.vlen, m_ktrtr_diag.vlen); Map<MatrixXd> eigen_Sigma(m_Sigma.matrix, m_Sigma.num_rows, m_Sigma.num_cols); //FITC (further) approximated posterior covariance with Netwon method Map<MatrixXd> eigen_L(m_L.matrix, m_L.num_rows, m_L.num_cols); Map<MatrixXd> eigen_Ktru(m_ktru.matrix, m_ktru.num_rows, m_ktru.num_cols); Map<VectorXd> eigen_dg(m_dg.vector, m_dg.vlen); Map<MatrixXd> eigen_V(m_V.matrix, m_V.num_rows, m_V.num_cols); MatrixXd diagonal_part=eigen_dg.asDiagonal(); //FITC equivalent prior MatrixXd prior=eigen_V.transpose()*eigen_V+diagonal_part; MatrixXd tmp = std::exp(m_log_scale * 2.0) * eigen_Ktru; eigen_Sigma=prior-tmp.adjoint()*eigen_L*tmp; /* //true posterior mean with equivalent FITC prior approximated by Newton method Map<VectorXd> eigen_t(m_t.vector, m_t.vlen); Map<MatrixXd> eigen_Rvdd(m_Rvdd.matrix, m_Rvdd.num_rows, m_Rvdd.num_cols); Map<VectorXd> eigen_W(m_W.vector, m_W.vlen); MatrixXd tmp1=eigen_Rvdd*prior; eigen_Sigma=prior+tmp.transpose()*tmp; MatrixXd tmp2=((eigen_dg.cwiseProduct(eigen_t)).asDiagonal()*eigen_V.transpose())*eigen_V; eigen_Sigma-=(tmp2+tmp2.transpose()); eigen_Sigma-=eigen_V.transpose()*(eigen_V*eigen_t.asDiagonal()*eigen_V.transpose())*eigen_V; MatrixXd tmp3=((eigen_dg.cwiseProduct(eigen_dg)).cwiseProduct(eigen_t)).asDiagonal(); eigen_Sigma-=tmp3; */ return SGMatrix<float64_t>(m_Sigma); } float64_t SingleFITCLaplaceInferenceMethod::get_psi_wrt_alpha() { //time complexity O(m*n) Map<VectorXd> eigen_alpha(m_al, m_al.vlen); SGVector<float64_t> f(m_al.vlen); Map<VectorXd> eigen_f(f.vector, f.vlen); Map<VectorXd> eigen_mean_f(m_mean_f.vector,m_mean_f.vlen); /* f = K * alpha + mean_f given alpha*/ SGVector<float64_t> tmp=compute_mvmK(m_al); Map<VectorXd> eigen_tmp(tmp.vector, tmp.vlen); eigen_f=eigen_tmp+eigen_mean_f; /* psi = 0.5 * alpha .* (f - m) - sum(dlp)*/ float64_t psi=eigen_alpha.dot(eigen_tmp) * 0.5; psi-=SGVector<float64_t>::sum(m_model->get_log_probability_f(m_labels, f)); return psi; } void SingleFITCLaplaceInferenceMethod::get_gradient_wrt_alpha(SGVector<float64_t> gradient) { //time complexity O(m*n) Map<VectorXd> eigen_alpha(m_al, m_al.vlen); Map<VectorXd> eigen_gradient(gradient.vector, gradient.vlen); SGVector<float64_t> f(m_al.vlen); Map<VectorXd> eigen_f(f.vector, f.vlen); Map<MatrixXd> kernel(m_ktrtr.matrix, m_ktrtr.num_rows, m_ktrtr.num_cols); Map<VectorXd> eigen_mean_f(m_mean_f.vector, m_mean_f.vlen); /* f = K * alpha + mean_f given alpha*/ SGVector<float64_t> tmp=compute_mvmK(m_al); Map<VectorXd> eigen_tmp(tmp.vector, tmp.vlen); eigen_f=eigen_tmp+eigen_mean_f; SGVector<float64_t> dlp_f = m_model->get_log_probability_derivative_f(m_labels, f, 1); Map<VectorXd> eigen_dlp_f(dlp_f.vector, dlp_f.vlen); /* g_alpha = K * (alpha - dlp_f)*/ SGVector<float64_t> tmp2(m_al.vlen); Map<VectorXd> eigen_tmp2(tmp2.vector, tmp2.vlen); eigen_tmp2=eigen_alpha-eigen_dlp_f; tmp2=compute_mvmK(tmp2); Map<VectorXd> eigen_tmp3(tmp2.vector, tmp2.vlen); eigen_gradient=eigen_tmp3; } }
33.502124
140
0.742088
[ "object", "vector", "model" ]
d737d76acfb02a03a1ce0e1fa537b7b4f6ba559c
1,678
cpp
C++
src/video_provider.cpp
corenel/image-stitching
844af322999f47868d71d250b77d9ca0bc8b143f
[ "MIT" ]
null
null
null
src/video_provider.cpp
corenel/image-stitching
844af322999f47868d71d250b77d9ca0bc8b143f
[ "MIT" ]
null
null
null
src/video_provider.cpp
corenel/image-stitching
844af322999f47868d71d250b77d9ca0bc8b143f
[ "MIT" ]
null
null
null
#include "video_provider.hpp" #include <iostream> MultipleVideoProvider::MultipleVideoProvider( const std::vector<std::string>& video_files) { open(video_files); } MultipleVideoProvider::~MultipleVideoProvider() { close(); } bool MultipleVideoProvider::open(const std::vector<std::string>& video_files) { video_files_ = video_files; for (const auto& video_file : video_files) { video_readers_.emplace_back( cv::makePtr<cv::VideoCapture>(video_file, cv::CAP_ANY)); } return true; } bool MultipleVideoProvider::isOpened() { if (video_readers_.empty()) { return false; } for (size_t i = 0; i < video_readers_.size(); ++i) { if (!video_readers_[i]->isOpened()) { std::cerr << "ERROR! frame not grabbed: " << video_files_[i] << std::endl; return false; } } return true; } void MultipleVideoProvider::close() { for (auto& video_reader : video_readers_) { video_reader.release(); } } bool MultipleVideoProvider::read(std::vector<cv::Mat>& frames) { frames.clear(); frames.resize(video_readers_.size()); bool rets = true; #ifdef USE_OPENMP #pragma omp parallel for #endif for (size_t i = 0; i < video_readers_.size(); ++i) { // wait for a new frame from camera and store it into 'frame' bool ret = video_readers_[i]->read(frames[i]); // check if we succeeded if (!ret) { std::cerr << "ERROR! frame not grabbed: " << video_files_[i] << std::endl; rets = false; continue; } else if (frames[i].empty()) { std::cerr << "ERROR! blank frame grabbed: " << video_files_[i] << std::endl; rets = false; continue; } } return rets; }
25.815385
80
0.641836
[ "vector" ]
d73b18c11e254a302edf574ccfda26fd7d413617
24,706
cpp
C++
modules/DiscordIntegration/main.cpp
alexvann/SokuMods
4f0c10a7d6014b96de49156158b5340437234556
[ "Unlicense" ]
8
2021-03-06T08:32:37.000Z
2022-02-13T16:00:50.000Z
modules/DiscordIntegration/main.cpp
alexvann/SokuMods
4f0c10a7d6014b96de49156158b5340437234556
[ "Unlicense" ]
17
2020-11-29T12:10:47.000Z
2022-02-21T23:28:35.000Z
modules/DiscordIntegration/main.cpp
alexvann/SokuMods
4f0c10a7d6014b96de49156158b5340437234556
[ "Unlicense" ]
3
2021-03-05T13:43:58.000Z
2021-11-19T15:49:32.000Z
// // Created by Gegel85 on 31/10/2020 // #include "CompiledString/CompiledStringFactory.hpp" #include "CompiledString/Vars/vars.hpp" #include "Exceptions.hpp" #include "Network/getPublicIp.hpp" #include "logger.hpp" #include "nlohmann/json.hpp" #include <SokuLib.hpp> #include <array> #include <ctime> #include <discord.h> #include <fstream> #include <process.h> #include <shlwapi.h> #include <string> #include <thread> #include <sstream> static bool hasSoku2 = false; enum StringIndex { STRING_INDEX_LOGO, STRING_INDEX_OPENING, STRING_INDEX_TITLE, STRING_INDEX_SELECT_VSCOMPUTER, STRING_INDEX_BATTLE_VSCOMPUTER, STRING_INDEX_LOADING_VSCOMPUTER, STRING_INDEX_SELECT_STORY, STRING_INDEX_BATTLE_STORY, STRING_INDEX_LOADING_STORY, STRING_INDEX_SELECT_ARCADE, STRING_INDEX_BATTLE_ARCADE, STRING_INDEX_LOADING_ARCADE, STRING_INDEX_BATTLE_TIMETRIAL, STRING_INDEX_LOADING_TIMETRIAL, STRING_INDEX_SELECT_VSPLAYER, STRING_INDEX_BATTLE_VSPLAYER, STRING_INDEX_LOADING_VSPLAYER, STRING_INDEX_SELECT_PRACTICE, STRING_INDEX_BATTLE_PRACTICE, STRING_INDEX_LOADING_PRACTICE, STRING_INDEX_SELECT_VSNETWORK, STRING_INDEX_BATTLE_VSNETWORK, STRING_INDEX_LOADING_VSNETWORK, STRING_INDEX_BATTLE_SPECTATOR, STRING_INDEX_LOADING_SPECTATOR, STRING_INDEX_BATTLE_REPLAY, STRING_INDEX_LOADING_REPLAY, STRING_INDEX_BATTLE_STORY_REPLAY, STRING_INDEX_LOADING_STORY_REPLAY, STRING_INDEX_ENDING, STRING_INDEX_HOSTING, STRING_INDEX_CONNECTING, STRING_INDEX_MAX }; static const char *const allElems[]{ "logo", "opening", "title", "select_vscomputer", "battle_vscomputer", "loading_vscomputer", "select_story", "battle_story", "loading_story", "select_arcade", "battle_arcade", "loading_arcade", "battle_timetrial", "loading_timetrial", "select_vsplayer", "battle_vsplayer", "loading_vsplayer", "select_practice", "battle_practice", "loading_practice", "select_vsnetwork", "battle_vsnetwork", "loading_vsnetwork", "battle_spectator", "loading_spectator", "battle_replay", "loading_replay", "battle_story_replay", "loading_story_replay", "ending", "hosting", "connecting", }; struct StringConfig { bool timestamp; bool set_timestamp; std::shared_ptr<CompiledString> title; std::shared_ptr<CompiledString> description; std::shared_ptr<CompiledString> large_image; std::shared_ptr<CompiledString> large_text; std::shared_ptr<CompiledString> small_image; std::shared_ptr<CompiledString> small_text; }; struct Config { std::vector<StringConfig> strings; time_t refreshRate = 0; }; struct State { unsigned host = 0; time_t gameTimestamp = 0; time_t totalTimestamp = 0; discord::Core *core = nullptr; std::string roomIp; std::pair<unsigned, unsigned> won = {0, 0}; discord::Activity lastActivity; }; static State state; static Config config; static const std::vector<const char *> discordResultToString{ "Ok", "ServiceUnavailable", "InvalidVersion", "LockFailed", "InternalError", "InvalidPayload", "InvalidCommand", "InvalidPermissions", "NotFetched", "NotFound", "Conflict", "InvalidSecret", "InvalidJoinSecret", "NoEligibleActivity", "InvalidInvite", "NotAuthenticated", "InvalidAccessToken", "ApplicationMismatch", "InvalidDataUrl", "InvalidBase64", "NotFiltered", "LobbyFull", "InvalidLobbySecret", "InvalidFilename", "InvalidFileSize", "InvalidEntitlement", "NotInstalled", "NotRunning", "InsufficientBuffer", "PurchaseCanceled", "InvalidGuild", "InvalidEvent", "InvalidChannel", "InvalidOrigin", "RateLimited", "OAuth2Error", "SelectChannelTimeout", "GetGuildTimeout", "SelectVoiceForceRequired", "CaptureShortcutAlreadyListening", "UnauthorizedForAchievement", "InvalidGiftCode", "PurchaseError", "TransactionAborted", }; #define cmpstr(a, b, f)if ((a).f() == (b).f());\ else if (!(a).f() || !(b).f() || strcmp((a).f(), (b).f()) != 0)\ return false; bool operator==(const discord::ActivityAssets &a, const discord::ActivityAssets &b) { cmpstr(a, b, GetLargeImage); cmpstr(a, b, GetLargeText); cmpstr(a, b, GetSmallImage); cmpstr(a, b, GetSmallText); return true; } bool operator==(const discord::ActivityTimestamps &a, const discord::ActivityTimestamps &b) { return a.GetStart() == b.GetStart() && a.GetEnd() == b.GetEnd(); } bool operator==(const discord::ActivityParty &a, const discord::ActivityParty &b) { cmpstr(a, b, GetId); return a.GetSize().GetCurrentSize() == b.GetSize().GetCurrentSize() && a.GetSize().GetMaxSize() == b.GetSize().GetMaxSize(); } bool operator==(const discord::ActivitySecrets &a, const discord::ActivitySecrets &b) { cmpstr(a, b, GetMatch); cmpstr(a, b, GetSpectate); cmpstr(a, b, GetJoin); return true; } bool operator==(const discord::Activity &a, const discord::Activity &b) { cmpstr(a, b, GetState); cmpstr(a, b, GetDetails); return a.GetTimestamps() == b.GetTimestamps() && a.GetAssets() == b.GetAssets() && a.GetParty() == b.GetParty() && a.GetSecrets() == b.GetSecrets(); } std::string getImageStr(const std::string &str) { if (str == "cover" && hasSoku2) return "soku2"; return str; } void updateActivity(StringIndex index, unsigned party) { if (index >= config.strings.size()) return; discord::Activity activity{}; auto &assets = activity.GetAssets(); auto &timeStamp = activity.GetTimestamps(); auto &partyObj = activity.GetParty(); auto &secrets = activity.GetSecrets(); auto &elem = config.strings[index]; if (party) { if (!state.roomIp.empty()) { if (party == 1) secrets.SetJoin(("join" + state.roomIp).c_str()); secrets.SetSpectate(("spec" + state.roomIp).c_str()); } partyObj.SetId(state.roomIp.c_str()); partyObj.GetSize().SetCurrentSize(party); partyObj.GetSize().SetMaxSize(2); } if (elem.timestamp) timeStamp.SetStart(state.totalTimestamp); if (elem.set_timestamp) timeStamp.SetStart(state.gameTimestamp); if (elem.title) activity.SetState(elem.title->getString().c_str()); if (elem.description) activity.SetDetails(elem.description->getString().c_str()); if (elem.large_image) assets.SetLargeImage(getImageStr(elem.large_image->getString()).c_str()); if (elem.large_text) assets.SetLargeText(elem.large_text->getString().c_str()); if (elem.small_image) assets.SetSmallImage(getImageStr(elem.small_image->getString()).c_str()); if (elem.small_text) assets.SetSmallText(elem.small_text->getString().c_str()); if (state.lastActivity == activity) return; logMessage("Updating presence...\n"); state.core->ActivityManager().UpdateActivity(activity, [](discord::Result result) { auto code = static_cast<unsigned>(result); if (code) logMessagef("Error updating presence: %s\n", discordResultToString[code]); }); state.lastActivity = activity; } void getActivityParams(StringIndex &index, unsigned &party) { party = 0; switch (SokuLib::sceneId) { case SokuLib::SCENE_SELECT: state.host = 0; switch (SokuLib::mainMode) { case SokuLib::BATTLE_MODE_PRACTICE: index = STRING_INDEX_SELECT_PRACTICE; return; case SokuLib::BATTLE_MODE_VSPLAYER: index = STRING_INDEX_SELECT_VSPLAYER; return; default: index = STRING_INDEX_SELECT_VSCOMPUTER; return; } case SokuLib::SCENE_SELECTSV: case SokuLib::SCENE_SELECTCL: state.host = 0; index = STRING_INDEX_SELECT_VSNETWORK; party = 2; return; case SokuLib::SCENE_LOADING: state.host = 0; switch (SokuLib::mainMode) { case SokuLib::BATTLE_MODE_PRACTICE: index = STRING_INDEX_LOADING_PRACTICE; return; case SokuLib::BATTLE_MODE_VSPLAYER: if (SokuLib::subMode == SokuLib::BATTLE_SUBMODE_REPLAY) index = STRING_INDEX_LOADING_REPLAY; else index = STRING_INDEX_LOADING_VSPLAYER; return; case SokuLib::BATTLE_MODE_STORY: if (SokuLib::subMode == SokuLib::BATTLE_SUBMODE_REPLAY) index = STRING_INDEX_LOADING_STORY_REPLAY; else index = STRING_INDEX_LOADING_STORY; return; case SokuLib::BATTLE_MODE_ARCADE: index = STRING_INDEX_LOADING_ARCADE; return; case SokuLib::BATTLE_MODE_TIME_TRIAL: index = STRING_INDEX_LOADING_TIMETRIAL; return; default: index = STRING_INDEX_LOADING_VSCOMPUTER; return; } case SokuLib::SCENE_LOADINGSV: case SokuLib::SCENE_LOADINGCL: state.host = 0; index = STRING_INDEX_LOADING_VSNETWORK; party = 2; return; case SokuLib::SCENE_LOADINGWATCH: state.host = 0; index = STRING_INDEX_LOADING_SPECTATOR; party = 2; return; case SokuLib::SCENE_BATTLE: state.host = 0; switch (SokuLib::mainMode) { case SokuLib::BATTLE_MODE_PRACTICE: index = STRING_INDEX_BATTLE_PRACTICE; return; case SokuLib::BATTLE_MODE_VSPLAYER: if (SokuLib::subMode == SokuLib::BATTLE_SUBMODE_REPLAY) index = STRING_INDEX_BATTLE_REPLAY; else index = STRING_INDEX_BATTLE_VSPLAYER; return; case SokuLib::BATTLE_MODE_STORY: if (SokuLib::subMode == SokuLib::BATTLE_SUBMODE_REPLAY) index = STRING_INDEX_BATTLE_STORY_REPLAY; else index = STRING_INDEX_BATTLE_STORY; return; case SokuLib::BATTLE_MODE_ARCADE: index = STRING_INDEX_BATTLE_ARCADE; return; case SokuLib::BATTLE_MODE_TIME_TRIAL: index = STRING_INDEX_BATTLE_TIMETRIAL; return; default: index = STRING_INDEX_BATTLE_VSCOMPUTER; return; } case SokuLib::SCENE_BATTLEWATCH: state.host = 0; index = STRING_INDEX_BATTLE_SPECTATOR; party = 2; return; case SokuLib::SCENE_BATTLESV: case SokuLib::SCENE_BATTLECL: state.host = 0; index = STRING_INDEX_BATTLE_VSNETWORK; party = 2; return; case SokuLib::SCENE_SELECTSCENARIO: state.host = 0; if (SokuLib::mainMode == SokuLib::BATTLE_MODE_ARCADE) index = STRING_INDEX_SELECT_ARCADE; else index = STRING_INDEX_SELECT_STORY; return; case SokuLib::SCENE_ENDING: state.host = 0; index = STRING_INDEX_ENDING; return; case SokuLib::SCENE_LOGO: state.host = 0; index = STRING_INDEX_LOGO; return; case SokuLib::SCENE_OPENING: state.host = 0; index = STRING_INDEX_OPENING; return; default: state.host = 0; return; case SokuLib::SCENE_TITLE: auto *menuObj = SokuLib::getMenuObj<SokuLib::MenuConnect>(); index = STRING_INDEX_TITLE; if (!SokuLib::MenuConnect::isInNetworkMenu()) { logMessage("We are not in a proper submenu\n"); return; } if ((menuObj->choice >= SokuLib::MenuConnect::CHOICE_ASSIGN_IP_CONNECT && menuObj->choice < SokuLib::MenuConnect::CHOICE_SELECT_PROFILE && menuObj->subchoice == 3) || (menuObj->choice >= SokuLib::MenuConnect::CHOICE_HOST && menuObj->choice < SokuLib::MenuConnect::CHOICE_SELECT_PROFILE && menuObj->subchoice == 255)) { if (state.host != 2) state.totalTimestamp = time(nullptr); state.host = 2; index = STRING_INDEX_CONNECTING; party = 2; } else if (menuObj->choice == SokuLib::MenuConnect::CHOICE_HOST && menuObj->subchoice == 2) { if (state.host != 1) state.totalTimestamp = time(nullptr); state.host = 1; index = STRING_INDEX_HOSTING; party = 1; } else state.host = 0; } } void titleScreenStateUpdate() { auto *menuObj = SokuLib::getMenuObj<SokuLib::MenuConnect>(); if (!SokuLib::MenuConnect::isInNetworkMenu()) { logMessage("We are not in a proper submenu\n"); return; } if ((menuObj->choice >= SokuLib::MenuConnect::CHOICE_ASSIGN_IP_CONNECT && menuObj->choice < SokuLib::MenuConnect::CHOICE_SELECT_PROFILE && menuObj->subchoice == 3) || (menuObj->choice >= SokuLib::MenuConnect::CHOICE_HOST && menuObj->choice < SokuLib::MenuConnect::CHOICE_SELECT_PROFILE && menuObj->subchoice == 255)) { if (state.roomIp.empty()) state.roomIp = menuObj->IPString + (":" + std::to_string(menuObj->port)); } else if (menuObj->choice == SokuLib::MenuConnect::CHOICE_HOST && menuObj->subchoice == 2) { if (state.roomIp.empty()) try { state.roomIp = getMyIp() + std::string(":") + std::to_string(menuObj->port); } catch (...) { } logMessagef("Hosting. Room ip is %s. Spectator are %sallowed\n", state.roomIp.c_str(), menuObj->spectate ? "" : "not "); } else if (!state.roomIp.empty()) state.roomIp.clear(); } void updateState() { switch (SokuLib::sceneId) { case SokuLib::SCENE_SELECT: case SokuLib::SCENE_SELECTSV: case SokuLib::SCENE_SELECTCL: case SokuLib::SCENE_LOADING: case SokuLib::SCENE_LOADINGSV: case SokuLib::SCENE_LOADINGCL: case SokuLib::SCENE_LOADINGWATCH: wins.first += state.won.first == 2; wins.second += state.won.second == 2; state.won = {0, 0}; break; case SokuLib::SCENE_TITLE: titleScreenStateUpdate(); case SokuLib::SCENE_SELECTSCENARIO: case SokuLib::SCENE_ENDING: case SokuLib::SCENE_LOGO: case SokuLib::SCENE_OPENING: state.gameTimestamp = time(nullptr); break; default: break; case SokuLib::SCENE_BATTLE: case SokuLib::SCENE_BATTLEWATCH: case SokuLib::SCENE_BATTLESV: case SokuLib::SCENE_BATTLECL: auto &battle = SokuLib::getBattleMgr(); if (SokuLib::mainMode == SokuLib::BATTLE_MODE_VSSERVER) { state.won.first = battle.rightCharacterManager.score; state.won.second = battle.leftCharacterManager.score; } else { state.won.first = battle.leftCharacterManager.score; state.won.second = battle.rightCharacterManager.score; } break; } } void tick() { StringIndex index; unsigned party = 0; updateState(); getActivityParams(index, party); logMessagef("Calling callback %u\n", index); updateActivity(index, party); } volatile long long discord_id; extern "C" __declspec(dllexport) long long DiscordId() { return discord_id; } class MyThread { private: bool _done = false; int _connectTimeout = 1; public: bool isDone() const { return this->_done; } static void onCurrentUserUpdate() { discord::User current; if (state.core->UserManager().GetCurrentUser(&current) == discord::Result::Ok) { discord_id = current.GetId(); } } static void onActivityJoin(const char *sec) { logMessagef("Got activity join with payload %s\n", sec); auto menuObj = SokuLib::getMenuObj<SokuLib::MenuConnect>(); std::string secret = sec; auto ip = secret.substr(4, secret.find_last_of(':') - 4); unsigned short port = std::stol(secret.substr(secret.find_last_of(':') + 1)); bool isSpec = secret.substr(0, 4) == "spec"; if (!SokuLib::MenuConnect::isInNetworkMenu()) { logMessage("Warping to connect screen.\n"); menuObj = &SokuLib::MenuConnect::moveToConnectMenu(); logMessage("Done.\n"); } else logMessage("Already in connect screen\n"); if (menuObj->choice >= SokuLib::MenuConnect::CHOICE_ASSIGN_IP_CONNECT && menuObj->choice < SokuLib::MenuConnect::CHOICE_SELECT_PROFILE && menuObj->subchoice == 3) return; if (menuObj->choice >= SokuLib::MenuConnect::CHOICE_HOST && menuObj->choice < SokuLib::MenuConnect::CHOICE_SELECT_PROFILE && menuObj->subchoice == 255) return; if (menuObj->choice == SokuLib::MenuConnect::CHOICE_HOST && menuObj->subchoice == 2) return; logMessagef("Connecting to %s:%u as %s\n", ip.c_str(), port, isSpec ? "spectator" : "player"); menuObj->joinHost(ip.c_str(), port, isSpec); state.roomIp = ip + ":" + std::to_string(port); } void init() { logMessage("Connecting to discord client...\n"); discord::Result result; do { result = discord::Core::Create(atoll(ClientID), DiscordCreateFlags_NoRequireDiscord, &state.core); if (result != discord::Result::Ok) { logMessagef("Error connecting to discord: %s\n", discordResultToString[static_cast<unsigned>(result)]); logMessagef("Retrying in %i seconds\n", this->_connectTimeout); std::this_thread::sleep_for(std::chrono::seconds(this->_connectTimeout)); if (this->_connectTimeout < 64) this->_connectTimeout *= 2; } } while (result != discord::Result::Ok); logMessage("Connected !\n"); state.core->UserManager().OnCurrentUserUpdate.Connect(MyThread::onCurrentUserUpdate); state.core->ActivityManager().OnActivityJoin.Connect(MyThread::onActivityJoin); } void run() const { logMessage("Entering loop\n"); while (!this->isDone()) { auto currentScene = SokuLib::sceneId; auto newScene = SokuLib::newSceneId; logMessagef("Current scene is %i vs new scene %i\n", currentScene, newScene); if (currentScene != newScene) state.totalTimestamp = time(nullptr); if (currentScene >= 0 && currentScene == newScene) { tick(); logMessage("Callback returned\n"); } else if (currentScene == SokuLib::SCENE_TITLE && (newScene == SokuLib::SCENE_SELECTSV || newScene == SokuLib::SCENE_SELECTCL)) updateActivity(STRING_INDEX_CONNECTING, 2); else logMessage("No callback call\n"); logMessage("Running discord callbacks\n"); state.core->RunCallbacks(); logMessagef("Waiting for next cycle (%llu ms)\n", config.refreshRate); std::this_thread::sleep_for(std::chrono::milliseconds(config.refreshRate)); } logMessage("Exit game\n"); } }; static MyThread updateThread; void loadJsonStrings(const std::string &path) { std::ifstream stream{path}; nlohmann::json value; logMessagef("Loading config file %s\n", path.c_str()); if (stream.fail()) throw std::invalid_argument(strerror(errno)); stream >> value; for (int i = 0; i < 21; i++) { logMessagef("Loading character %i %s\n", i, value["characters"][i].dump().c_str()); charactersNames[i].first = value["characters"][i]["short_name"]; charactersNames[i].second = value["characters"][i]["full_name"]; } logMessagef("Loading stages\n"); stagesNames = value["stages"].get<std::vector<std::string>>(); if (stagesNames.size() < 20) throw std::invalid_argument("Stage list is too small"); logMessagef("Loading submenus\n"); submenusNames = value["submenus"].get<std::vector<std::string>>(); if (submenusNames.size() < 7) throw std::invalid_argument("Submenus list is too small"); config.strings.clear(); config.strings.reserve(sizeof(allElems) / sizeof(*allElems)); for (auto &elem : allElems) { auto &val = value[elem]; StringConfig cfg; logMessagef("Loading elem %s %s\n", elem, val.dump().c_str()); cfg.timestamp = val.contains("has_timer") && val["has_timer"].get<bool>(); cfg.set_timestamp = val.contains("has_set_length_timer") && val["has_set_length_timer"].get<bool>(); cfg.title = val.contains("title") ? CompiledStringFactory::compileString(val["title"]) : nullptr; cfg.description = val.contains("description") ? CompiledStringFactory::compileString(val["description"]) : nullptr; cfg.large_image = val.contains("image") ? CompiledStringFactory::compileString(val["image"]) : nullptr; cfg.small_image = val.contains("small_image") ? CompiledStringFactory::compileString(val["small_image"]) : nullptr; cfg.large_text = val.contains("image_text") ? CompiledStringFactory::compileString(val["image_text"]) : nullptr; cfg.small_text = val.contains("small_image_text") ? CompiledStringFactory::compileString(val["small_image_text"]) : nullptr; config.strings.push_back(cfg); } } void loadSoku2CSV(LPWSTR path) { std::ifstream stream{path}; std::string line; if (stream.fail()) { logMessagef("%S: %s\n", path, strerror(errno)); return; } while (std::getline(stream, line)) { std::stringstream str{line}; unsigned id; std::string idStr; std::string codeName; std::string shortName; std::string fullName; std::getline(str, idStr, ';'); std::getline(str, codeName, ';'); std::getline(str, shortName, ';'); std::getline(str, fullName, ';'); if (str.fail()) { logMessagef("Skipping line %s: Stream failed\n", line.c_str()); continue; } try { id = std::stoi(idStr); } catch (...){ logMessagef("Skipping line %s: Invalid id\n", line.c_str()); continue; } charactersNames[id].first = shortName; charactersNames[id].second = fullName; charactersImg[id] = codeName; } } void loadSoku2Config() { logMessage("Looking for Soku2 config...\n"); int argc; wchar_t app_path[MAX_PATH]; wchar_t setting_path[MAX_PATH]; wchar_t **arg_list = CommandLineToArgvW(GetCommandLineW(), &argc); wcsncpy(app_path, arg_list[0], MAX_PATH); PathRemoveFileSpecW(app_path); if (GetEnvironmentVariableW(L"SWRSTOYS", setting_path, sizeof(setting_path)) <= 0) { if (arg_list && argc > 1 && StrStrIW(arg_list[1], L"ini")) { wcscpy(setting_path, arg_list[1]); LocalFree(arg_list); } else { wcscpy(setting_path, app_path); PathAppendW(setting_path, L"\\SWRSToys.ini"); } if (arg_list) { LocalFree(arg_list); } } logMessagef("Config file is %S\n", setting_path); wchar_t moduleKeys[1024]; wchar_t moduleValue[MAX_PATH]; GetPrivateProfileStringW(L"Module", nullptr, nullptr, moduleKeys, sizeof(moduleKeys), setting_path); for (wchar_t *key = moduleKeys; *key; key += wcslen(key) + 1) { wchar_t module_path[MAX_PATH]; GetPrivateProfileStringW(L"Module", key, nullptr, moduleValue, sizeof(moduleValue), setting_path); wchar_t *filename = wcsrchr(moduleValue, '/'); logMessagef("Check %S\n", moduleValue); if (!filename) filename = app_path; else filename++; for (int i = 0; filename[i]; i++) filename[i] = tolower(filename[i]); if (wcscmp(filename, L"soku2.dll") != 0) continue; hasSoku2 = true; wcscpy(module_path, app_path); PathAppendW(module_path, moduleValue); while (auto result = wcschr(module_path, '/')) *result = '\\'; PathRemoveFileSpecW(module_path); logMessagef("Found Soku2 module folder at %S\n", module_path); PathAppendW(module_path, L"\\config\\info\\characters.csv"); loadSoku2CSV(module_path); return; } } // �ݒ胍�[�h void LoadSettings(LPCSTR profilePath) { int i; char buffer[64]; char file[MAX_PATH]; char path[MAX_PATH]; char local[LOCALE_NAME_MAX_LENGTH]; wchar_t localw[LOCALE_NAME_MAX_LENGTH]; logMessage("Loading settings...\n"); config.refreshRate = GetPrivateProfileInt("DiscordIntegration", "RefreshTime", 1000, profilePath); auto ret = GetPrivateProfileString("DiscordIntegration", "InviteIp", "", buffer, sizeof(buffer), profilePath); if (inet_addr(buffer) != -1 && ret) myIp = strdup(buffer); ret = GetPrivateProfileString("DiscordIntegration", "StringFile", "", file, sizeof(file), profilePath); strcpy(path, profilePath); PathRemoveFileSpec(path); PathAppend(path, file); logMessagef("ClientID: %s\nInviteIp: %s\nFile: %s\n", ClientID, myIp, path); loadSoku2Config(); try { if (ret) { loadJsonStrings(path); return; } } catch (std::exception &e) { MessageBoxA( nullptr, ("Cannot load file " + std::string(path) + ": " + e.what() + "\nFalling back to default files...").c_str(), "Loading error", MB_ICONWARNING); } strcpy(path, profilePath); PathRemoveFileSpec(path); strcat(path, "\\langs\\"); GetUserDefaultLocaleName(localw, sizeof(localw)); for (i = 0; localw[i]; i++) local[i] = localw[i]; local[i] = 0; if (strchr(local, '-') != nullptr) *strchr(local, '-') = 0; strcat(path, local); strcat(path, ".json"); try { loadJsonStrings(path); return; } catch (std::exception &e) { logMessagef("%s: %s\n", path, e.what()); } strcpy(path, profilePath); PathRemoveFileSpec(path); PathAppend(path, "langs/en.json"); try { loadJsonStrings(path); } catch (std::exception &e) { MessageBoxA(nullptr, ("Cannot load file " + std::string(path) + ": " + e.what()).c_str(), "Loading error", MB_ICONERROR); abort(); } } void start(void *ignored) { updateThread.init(); updateThread.run(); } extern "C" __declspec(dllexport) bool CheckVersion(const BYTE hash[16]) { return true; } extern "C" __declspec(dllexport) bool Initialize(HMODULE hMyModule, HMODULE hParentModule) { char profilePath[1024 + MAX_PATH]; initLogger(); logMessage("Initializing...\n"); GetModuleFileName(hMyModule, profilePath, 1024); PathRemoveFileSpec(profilePath); PathAppend(profilePath, "DiscordIntegration.ini"); LoadSettings(profilePath); // DWORD old; //::VirtualProtect((PVOID)rdata_Offset, rdata_Size, PAGE_EXECUTE_WRITECOPY, &old); // s_origCLogo_OnProcess = TamperDword(vtbl_CLogo + 4, (DWORD)CLogo_OnProcess); // s_origCBattle_OnProcess = TamperDword(vtbl_CBattle + 4, (DWORD)CBattle_OnProcess); // s_origCBattleSV_OnProcess = TamperDword(vtbl_CBattleSV + 4, (DWORD)CBattleSV_OnProcess); // s_origCBattleCL_OnProcess = TamperDword(vtbl_CBattleCL + 4, (DWORD)CBattleCL_OnProcess); // s_origCTitle_OnProcess = TamperDword(vtbl_CTitle + 4, (DWORD)CTitle_OnProcess); // s_origCSelect_OnProcess = TamperDword(vtbl_CSelect + 4, (DWORD)CSelect_OnProcess); //::VirtualProtect((PVOID)rdata_Offset, rdata_Size, old, &old); //::FlushInstructionCache(GetCurrentProcess(), nullptr, 0); // can't use std::thread here beacause it deadlocks against DllMain DLL_THREAD_ATTACH in some circumstances _beginthread(start, 0, nullptr); logMessage("Done...\n"); return true; } extern "C" int APIENTRY DllMain(HMODULE hModule, DWORD fdwReason, LPVOID lpReserved) { return TRUE; }
29.376932
157
0.716061
[ "vector" ]
d73e6d83e14d4fdbd17beb005072d3eec6ee8c01
496,529
cc
C++
diplomacy_research/proto/diplomacy_tensorflow/compiler/xla/service/hlo.pb.cc
wwongkamjan/dipnet_press
787263c1b9484698904f525c8d78d0e333e1c0d9
[ "MIT" ]
39
2019-09-06T13:42:24.000Z
2022-03-18T18:38:43.000Z
diplomacy_research/proto/diplomacy_tensorflow/compiler/xla/service/hlo.pb.cc
wwongkamjan/dipnet_press
787263c1b9484698904f525c8d78d0e333e1c0d9
[ "MIT" ]
9
2019-09-19T22:35:32.000Z
2022-02-24T18:04:57.000Z
diplomacy_research/proto/diplomacy_tensorflow/compiler/xla/service/hlo.pb.cc
wwongkamjan/dipnet_press
787263c1b9484698904f525c8d78d0e333e1c0d9
[ "MIT" ]
8
2019-10-16T21:09:14.000Z
2022-02-23T05:20:37.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: diplomacy_tensorflow/compiler/xla/service/hlo.proto #include "diplomacy_tensorflow/compiler/xla/service/hlo.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // This is a temporary google only hack #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) namespace protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto { extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_BufferAllocationProto_Assigned; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_DynamicParameterBindingProto_Binding; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_HeapSimulatorTrace_Event; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_HloInputOutputAliasProto_AliasEntryProto; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_HloInstructionProto_SliceDimensions; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_HloScheduleProto_InstructionSequence; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_LogicalBufferProto_Location; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<14> scc_info_HloInstructionProto; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_BufferAllocationProto; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_BufferAssignmentProto_BufferAlias; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_DynamicParameterBindingProto; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_HeapSimulatorTrace; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_HloInputOutputAliasProto; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_HloScheduleProto; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_HloScheduleProto_SequencesEntry_DoNotUse; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_LogicalBufferProto; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_HloComputationProto; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_HloProto; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<4> scc_info_BufferAssignmentProto; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto ::google::protobuf::internal::SCCInfo<5> scc_info_HloModuleProto; } // namespace protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto namespace protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto { extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_ConvolutionDimensionNumbers; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_DotDimensionNumbers; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_GatherDimensionNumbers; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_OpMetadata; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_PrecisionConfig; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_ReplicaGroup; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_ScatterDimensionNumbers; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceTarget; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_LiteralProto; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_OpSharding; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_PaddingConfig; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ProgramShapeProto; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ShapeProto; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Window; } // namespace protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto namespace xla { class HloInstructionProto_SliceDimensionsDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HloInstructionProto_SliceDimensions> _instance; } _HloInstructionProto_SliceDimensions_default_instance_; class HloInstructionProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HloInstructionProto> _instance; } _HloInstructionProto_default_instance_; class HloComputationProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HloComputationProto> _instance; } _HloComputationProto_default_instance_; class HloScheduleProto_InstructionSequenceDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HloScheduleProto_InstructionSequence> _instance; } _HloScheduleProto_InstructionSequence_default_instance_; class HloScheduleProto_SequencesEntry_DoNotUseDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HloScheduleProto_SequencesEntry_DoNotUse> _instance; } _HloScheduleProto_SequencesEntry_DoNotUse_default_instance_; class HloScheduleProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HloScheduleProto> _instance; } _HloScheduleProto_default_instance_; class HloInputOutputAliasProto_AliasEntryProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HloInputOutputAliasProto_AliasEntryProto> _instance; } _HloInputOutputAliasProto_AliasEntryProto_default_instance_; class HloInputOutputAliasProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HloInputOutputAliasProto> _instance; } _HloInputOutputAliasProto_default_instance_; class DynamicParameterBindingProto_BindingDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<DynamicParameterBindingProto_Binding> _instance; } _DynamicParameterBindingProto_Binding_default_instance_; class DynamicParameterBindingProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<DynamicParameterBindingProto> _instance; } _DynamicParameterBindingProto_default_instance_; class HloModuleProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HloModuleProto> _instance; } _HloModuleProto_default_instance_; class LogicalBufferProto_LocationDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<LogicalBufferProto_Location> _instance; } _LogicalBufferProto_Location_default_instance_; class LogicalBufferProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<LogicalBufferProto> _instance; } _LogicalBufferProto_default_instance_; class BufferAllocationProto_AssignedDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<BufferAllocationProto_Assigned> _instance; } _BufferAllocationProto_Assigned_default_instance_; class BufferAllocationProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<BufferAllocationProto> _instance; } _BufferAllocationProto_default_instance_; class HeapSimulatorTrace_EventDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HeapSimulatorTrace_Event> _instance; } _HeapSimulatorTrace_Event_default_instance_; class HeapSimulatorTraceDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HeapSimulatorTrace> _instance; } _HeapSimulatorTrace_default_instance_; class HloModuleGroupProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HloModuleGroupProto> _instance; } _HloModuleGroupProto_default_instance_; class BufferAssignmentProto_BufferAliasDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<BufferAssignmentProto_BufferAlias> _instance; } _BufferAssignmentProto_BufferAlias_default_instance_; class BufferAssignmentProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<BufferAssignmentProto> _instance; } _BufferAssignmentProto_default_instance_; class HloProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HloProto> _instance; } _HloProto_default_instance_; class HloSnapshotDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HloSnapshot> _instance; } _HloSnapshot_default_instance_; } // namespace xla namespace protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto { static void InitDefaultsHloInstructionProto_SliceDimensions() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HloInstructionProto_SliceDimensions_default_instance_; new (ptr) ::xla::HloInstructionProto_SliceDimensions(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::HloInstructionProto_SliceDimensions::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_HloInstructionProto_SliceDimensions = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsHloInstructionProto_SliceDimensions}, {}}; static void InitDefaultsHloInstructionProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HloInstructionProto_default_instance_; new (ptr) ::xla::HloInstructionProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::HloInstructionProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<14> scc_info_HloInstructionProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 14, InitDefaultsHloInstructionProto}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_ShapeProto.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_OpMetadata.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_LiteralProto.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_Window.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_ConvolutionDimensionNumbers.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInstructionProto_SliceDimensions.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_PaddingConfig.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_DotDimensionNumbers.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_GatherDimensionNumbers.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_OpSharding.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_ReplicaGroup.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_ScatterDimensionNumbers.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_PrecisionConfig.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_SourceTarget.base,}}; static void InitDefaultsHloComputationProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HloComputationProto_default_instance_; new (ptr) ::xla::HloComputationProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::HloComputationProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<2> scc_info_HloComputationProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsHloComputationProto}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInstructionProto.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_ProgramShapeProto.base,}}; static void InitDefaultsHloScheduleProto_InstructionSequence() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HloScheduleProto_InstructionSequence_default_instance_; new (ptr) ::xla::HloScheduleProto_InstructionSequence(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::HloScheduleProto_InstructionSequence::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_HloScheduleProto_InstructionSequence = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsHloScheduleProto_InstructionSequence}, {}}; static void InitDefaultsHloScheduleProto_SequencesEntry_DoNotUse() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HloScheduleProto_SequencesEntry_DoNotUse_default_instance_; new (ptr) ::xla::HloScheduleProto_SequencesEntry_DoNotUse(); } ::xla::HloScheduleProto_SequencesEntry_DoNotUse::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_HloScheduleProto_SequencesEntry_DoNotUse = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsHloScheduleProto_SequencesEntry_DoNotUse}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloScheduleProto_InstructionSequence.base,}}; static void InitDefaultsHloScheduleProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HloScheduleProto_default_instance_; new (ptr) ::xla::HloScheduleProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::HloScheduleProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_HloScheduleProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsHloScheduleProto}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloScheduleProto_SequencesEntry_DoNotUse.base,}}; static void InitDefaultsHloInputOutputAliasProto_AliasEntryProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HloInputOutputAliasProto_AliasEntryProto_default_instance_; new (ptr) ::xla::HloInputOutputAliasProto_AliasEntryProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::HloInputOutputAliasProto_AliasEntryProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_HloInputOutputAliasProto_AliasEntryProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsHloInputOutputAliasProto_AliasEntryProto}, {}}; static void InitDefaultsHloInputOutputAliasProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HloInputOutputAliasProto_default_instance_; new (ptr) ::xla::HloInputOutputAliasProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::HloInputOutputAliasProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_HloInputOutputAliasProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsHloInputOutputAliasProto}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInputOutputAliasProto_AliasEntryProto.base,}}; static void InitDefaultsDynamicParameterBindingProto_Binding() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_DynamicParameterBindingProto_Binding_default_instance_; new (ptr) ::xla::DynamicParameterBindingProto_Binding(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::DynamicParameterBindingProto_Binding::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_DynamicParameterBindingProto_Binding = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDynamicParameterBindingProto_Binding}, {}}; static void InitDefaultsDynamicParameterBindingProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_DynamicParameterBindingProto_default_instance_; new (ptr) ::xla::DynamicParameterBindingProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::DynamicParameterBindingProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_DynamicParameterBindingProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsDynamicParameterBindingProto}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_DynamicParameterBindingProto_Binding.base,}}; static void InitDefaultsHloModuleProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HloModuleProto_default_instance_; new (ptr) ::xla::HloModuleProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::HloModuleProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<5> scc_info_HloModuleProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 5, InitDefaultsHloModuleProto}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloComputationProto.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_ProgramShapeProto.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloScheduleProto.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInputOutputAliasProto.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_DynamicParameterBindingProto.base,}}; static void InitDefaultsLogicalBufferProto_Location() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_LogicalBufferProto_Location_default_instance_; new (ptr) ::xla::LogicalBufferProto_Location(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::LogicalBufferProto_Location::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_LogicalBufferProto_Location = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsLogicalBufferProto_Location}, {}}; static void InitDefaultsLogicalBufferProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_LogicalBufferProto_default_instance_; new (ptr) ::xla::LogicalBufferProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::LogicalBufferProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_LogicalBufferProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsLogicalBufferProto}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_LogicalBufferProto_Location.base,}}; static void InitDefaultsBufferAllocationProto_Assigned() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_BufferAllocationProto_Assigned_default_instance_; new (ptr) ::xla::BufferAllocationProto_Assigned(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::BufferAllocationProto_Assigned::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_BufferAllocationProto_Assigned = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsBufferAllocationProto_Assigned}, {}}; static void InitDefaultsBufferAllocationProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_BufferAllocationProto_default_instance_; new (ptr) ::xla::BufferAllocationProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::BufferAllocationProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_BufferAllocationProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsBufferAllocationProto}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAllocationProto_Assigned.base,}}; static void InitDefaultsHeapSimulatorTrace_Event() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HeapSimulatorTrace_Event_default_instance_; new (ptr) ::xla::HeapSimulatorTrace_Event(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::HeapSimulatorTrace_Event::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_HeapSimulatorTrace_Event = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsHeapSimulatorTrace_Event}, {}}; static void InitDefaultsHeapSimulatorTrace() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HeapSimulatorTrace_default_instance_; new (ptr) ::xla::HeapSimulatorTrace(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::HeapSimulatorTrace::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_HeapSimulatorTrace = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsHeapSimulatorTrace}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HeapSimulatorTrace_Event.base,}}; static void InitDefaultsHloModuleGroupProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HloModuleGroupProto_default_instance_; new (ptr) ::xla::HloModuleGroupProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::HloModuleGroupProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_HloModuleGroupProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsHloModuleGroupProto}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloModuleProto.base,}}; static void InitDefaultsBufferAssignmentProto_BufferAlias() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_BufferAssignmentProto_BufferAlias_default_instance_; new (ptr) ::xla::BufferAssignmentProto_BufferAlias(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::BufferAssignmentProto_BufferAlias::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_BufferAssignmentProto_BufferAlias = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsBufferAssignmentProto_BufferAlias}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_LogicalBufferProto_Location.base,}}; static void InitDefaultsBufferAssignmentProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_BufferAssignmentProto_default_instance_; new (ptr) ::xla::BufferAssignmentProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::BufferAssignmentProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<4> scc_info_BufferAssignmentProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsBufferAssignmentProto}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_LogicalBufferProto.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAssignmentProto_BufferAlias.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAllocationProto.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HeapSimulatorTrace.base,}}; static void InitDefaultsHloProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HloProto_default_instance_; new (ptr) ::xla::HloProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::HloProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<2> scc_info_HloProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsHloProto}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloModuleProto.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAssignmentProto.base,}}; static void InitDefaultsHloSnapshot() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::xla::_HloSnapshot_default_instance_; new (ptr) ::xla::HloSnapshot(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::xla::HloSnapshot::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<2> scc_info_HloSnapshot = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsHloSnapshot}, { &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloProto.base, &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::scc_info_LiteralProto.base,}}; void InitDefaults() { ::google::protobuf::internal::InitSCC(&scc_info_HloInstructionProto_SliceDimensions.base); ::google::protobuf::internal::InitSCC(&scc_info_HloInstructionProto.base); ::google::protobuf::internal::InitSCC(&scc_info_HloComputationProto.base); ::google::protobuf::internal::InitSCC(&scc_info_HloScheduleProto_InstructionSequence.base); ::google::protobuf::internal::InitSCC(&scc_info_HloScheduleProto_SequencesEntry_DoNotUse.base); ::google::protobuf::internal::InitSCC(&scc_info_HloScheduleProto.base); ::google::protobuf::internal::InitSCC(&scc_info_HloInputOutputAliasProto_AliasEntryProto.base); ::google::protobuf::internal::InitSCC(&scc_info_HloInputOutputAliasProto.base); ::google::protobuf::internal::InitSCC(&scc_info_DynamicParameterBindingProto_Binding.base); ::google::protobuf::internal::InitSCC(&scc_info_DynamicParameterBindingProto.base); ::google::protobuf::internal::InitSCC(&scc_info_HloModuleProto.base); ::google::protobuf::internal::InitSCC(&scc_info_LogicalBufferProto_Location.base); ::google::protobuf::internal::InitSCC(&scc_info_LogicalBufferProto.base); ::google::protobuf::internal::InitSCC(&scc_info_BufferAllocationProto_Assigned.base); ::google::protobuf::internal::InitSCC(&scc_info_BufferAllocationProto.base); ::google::protobuf::internal::InitSCC(&scc_info_HeapSimulatorTrace_Event.base); ::google::protobuf::internal::InitSCC(&scc_info_HeapSimulatorTrace.base); ::google::protobuf::internal::InitSCC(&scc_info_HloModuleGroupProto.base); ::google::protobuf::internal::InitSCC(&scc_info_BufferAssignmentProto_BufferAlias.base); ::google::protobuf::internal::InitSCC(&scc_info_BufferAssignmentProto.base); ::google::protobuf::internal::InitSCC(&scc_info_HloProto.base); ::google::protobuf::internal::InitSCC(&scc_info_HloSnapshot.base); } ::google::protobuf::Metadata file_level_metadata[22]; const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[1]; const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto_SliceDimensions, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto_SliceDimensions, start_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto_SliceDimensions, limit_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto_SliceDimensions, stride_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, opcode_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, shape_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, metadata_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, literal_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, parameter_number_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, fusion_kind_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, tuple_index_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, dimensions_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, window_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, convolution_dimension_numbers_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, feature_group_count_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, slice_dimensions_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, exponent_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, mantissa_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, dynamic_slice_sizes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, padding_config_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, outfeed_config_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, distribution_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, epsilon_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, feature_index_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, channel_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, infeed_config_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, custom_call_target_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, custom_call_opaque_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, outfeed_shape_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, dot_dimension_numbers_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, fft_type_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, fft_length_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, gather_dimension_numbers_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, gather_slice_sizes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, channel_name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, cost_estimate_ns_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, operand_ids_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, control_predecessor_ids_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, called_computation_ids_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, sharding_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, backend_config_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, replica_groups_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, all_reduce_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, cross_replica_sum_barrier_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, is_host_transfer_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, scatter_dimension_numbers_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, precision_config_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, source_target_pairs_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, domain_entry_sharding_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, domain_exit_sharding_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, constrain_layout_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInstructionProto, operand_shapes_with_layout_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloComputationProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloComputationProto, name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloComputationProto, instructions_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloComputationProto, program_shape_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloComputationProto, id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloComputationProto, root_id_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloScheduleProto_InstructionSequence, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloScheduleProto_InstructionSequence, instruction_ids_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloScheduleProto_SequencesEntry_DoNotUse, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloScheduleProto_SequencesEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloScheduleProto_SequencesEntry_DoNotUse, key_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloScheduleProto_SequencesEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloScheduleProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloScheduleProto, sequences_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInputOutputAliasProto_AliasEntryProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInputOutputAliasProto_AliasEntryProto, output_shape_index_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInputOutputAliasProto_AliasEntryProto, parameter_number_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInputOutputAliasProto_AliasEntryProto, parameter_shape_index_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInputOutputAliasProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloInputOutputAliasProto, entries_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::DynamicParameterBindingProto_Binding, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::DynamicParameterBindingProto_Binding, dynamic_param_num_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::DynamicParameterBindingProto_Binding, dynamic_param_index_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::DynamicParameterBindingProto_Binding, target_param_num_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::DynamicParameterBindingProto_Binding, target_param_index_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::DynamicParameterBindingProto_Binding, target_param_dim_num_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::DynamicParameterBindingProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::DynamicParameterBindingProto, entries_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloModuleProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloModuleProto, name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloModuleProto, entry_computation_name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloModuleProto, entry_computation_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloModuleProto, computations_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloModuleProto, host_program_shape_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloModuleProto, id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloModuleProto, schedule_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloModuleProto, input_output_alias_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloModuleProto, dynamic_parameter_binding_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::LogicalBufferProto_Location, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::LogicalBufferProto_Location, computation_name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::LogicalBufferProto_Location, instruction_name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::LogicalBufferProto_Location, shape_index_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::LogicalBufferProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::LogicalBufferProto, id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::LogicalBufferProto, size_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::LogicalBufferProto, defined_at_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::LogicalBufferProto, color_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto_Assigned, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto_Assigned, logical_buffer_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto_Assigned, offset_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto_Assigned, size_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto, index_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto, size_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto, is_thread_local_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto, is_tuple_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto, is_entry_computation_parameter_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto, is_constant_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto, parameter_number_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto, parameter_shape_index_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto, maybe_live_out_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto, color_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAllocationProto, assigned_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HeapSimulatorTrace_Event, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HeapSimulatorTrace_Event, kind_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HeapSimulatorTrace_Event, buffer_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HeapSimulatorTrace_Event, computation_name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HeapSimulatorTrace_Event, instruction_name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HeapSimulatorTrace_Event, share_with_canonical_id_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HeapSimulatorTrace, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HeapSimulatorTrace, events_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HeapSimulatorTrace, whole_module_simulation_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloModuleGroupProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloModuleGroupProto, name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloModuleGroupProto, hlo_modules_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAssignmentProto_BufferAlias, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAssignmentProto_BufferAlias, source_buffer_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAssignmentProto_BufferAlias, location_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAssignmentProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAssignmentProto, logical_buffers_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAssignmentProto, buffer_aliases_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAssignmentProto, buffer_allocations_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::BufferAssignmentProto, heap_simulator_traces_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloProto, hlo_module_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloProto, buffer_assignment_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloSnapshot, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloSnapshot, hlo_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloSnapshot, arguments_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloSnapshot, result_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::xla::HloSnapshot, execution_platform_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::xla::HloInstructionProto_SliceDimensions)}, { 8, -1, sizeof(::xla::HloInstructionProto)}, { 63, -1, sizeof(::xla::HloComputationProto)}, { 73, -1, sizeof(::xla::HloScheduleProto_InstructionSequence)}, { 79, 86, sizeof(::xla::HloScheduleProto_SequencesEntry_DoNotUse)}, { 88, -1, sizeof(::xla::HloScheduleProto)}, { 94, -1, sizeof(::xla::HloInputOutputAliasProto_AliasEntryProto)}, { 102, -1, sizeof(::xla::HloInputOutputAliasProto)}, { 108, -1, sizeof(::xla::DynamicParameterBindingProto_Binding)}, { 118, -1, sizeof(::xla::DynamicParameterBindingProto)}, { 124, -1, sizeof(::xla::HloModuleProto)}, { 138, -1, sizeof(::xla::LogicalBufferProto_Location)}, { 146, -1, sizeof(::xla::LogicalBufferProto)}, { 155, -1, sizeof(::xla::BufferAllocationProto_Assigned)}, { 163, -1, sizeof(::xla::BufferAllocationProto)}, { 179, -1, sizeof(::xla::HeapSimulatorTrace_Event)}, { 189, -1, sizeof(::xla::HeapSimulatorTrace)}, { 196, -1, sizeof(::xla::HloModuleGroupProto)}, { 203, -1, sizeof(::xla::BufferAssignmentProto_BufferAlias)}, { 210, -1, sizeof(::xla::BufferAssignmentProto)}, { 219, -1, sizeof(::xla::HloProto)}, { 226, -1, sizeof(::xla::HloSnapshot)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HloInstructionProto_SliceDimensions_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HloInstructionProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HloComputationProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HloScheduleProto_InstructionSequence_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HloScheduleProto_SequencesEntry_DoNotUse_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HloScheduleProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HloInputOutputAliasProto_AliasEntryProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HloInputOutputAliasProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_DynamicParameterBindingProto_Binding_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_DynamicParameterBindingProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HloModuleProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_LogicalBufferProto_Location_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_LogicalBufferProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_BufferAllocationProto_Assigned_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_BufferAllocationProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HeapSimulatorTrace_Event_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HeapSimulatorTrace_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HloModuleGroupProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_BufferAssignmentProto_BufferAlias_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_BufferAssignmentProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HloProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::xla::_HloSnapshot_default_instance_), }; void protobuf_AssignDescriptors() { AddDescriptors(); AssignDescriptors( "diplomacy_tensorflow/compiler/xla/service/hlo.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, file_level_enum_descriptors, NULL); } void protobuf_AssignDescriptorsOnce() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 22); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n3diplomacy_tensorflow/compiler/xla/serv" "ice/hlo.proto\022\003xla\0320diplomacy_tensorflow" "/compiler/xla/xla_data.proto\"\371\016\n\023HloInst" "ructionProto\022\014\n\004name\030\001 \001(\t\022\016\n\006opcode\030\002 \001" "(\t\022\036\n\005shape\030\003 \001(\0132\017.xla.ShapeProto\022!\n\010me" "tadata\030\007 \001(\0132\017.xla.OpMetadata\022\"\n\007literal" "\030\010 \001(\0132\021.xla.LiteralProto\022\030\n\020parameter_n" "umber\030\t \001(\003\022\023\n\013fusion_kind\030\013 \001(\t\022\023\n\013tupl" "e_index\030\r \001(\003\022\022\n\ndimensions\030\016 \003(\003\022\033\n\006win" "dow\030\017 \001(\0132\013.xla.Window\022G\n\035convolution_di" "mension_numbers\030\020 \001(\0132 .xla.ConvolutionD" "imensionNumbers\022\033\n\023feature_group_count\0302" " \001(\003\022B\n\020slice_dimensions\030\021 \003(\0132(.xla.Hlo" "InstructionProto.SliceDimensions\022\025\n\rexpo" "nent_bits\030\022 \001(\005\022\025\n\rmantissa_bits\030\023 \001(\005\022\033" "\n\023dynamic_slice_sizes\030\024 \003(\003\022*\n\016padding_c" "onfig\030\025 \001(\0132\022.xla.PaddingConfig\022\026\n\016outfe" "ed_config\030\026 \001(\014\022-\n\014distribution\030\027 \001(\0162\027." "xla.RandomDistribution\022\017\n\007epsilon\030\030 \001(\002\022" "\025\n\rfeature_index\030\031 \001(\003\022\022\n\nchannel_id\030\032 \001" "(\003\022\025\n\rinfeed_config\030\033 \001(\014\022\032\n\022custom_call" "_target\030\034 \001(\t\022\032\n\022custom_call_opaque\0305 \001(" "\t\022&\n\routfeed_shape\030\035 \001(\0132\017.xla.ShapeProt" "o\0227\n\025dot_dimension_numbers\030\036 \001(\0132\030.xla.D" "otDimensionNumbers\022\036\n\010fft_type\030\037 \001(\0162\014.x" "la.FftType\022\022\n\nfft_length\030 \003(\003\022=\n\030gather" "_dimension_numbers\030! \001(\0132\033.xla.GatherDim" "ensionNumbers\022\032\n\022gather_slice_sizes\030\" \003(" "\003\022\024\n\014channel_name\030) \001(\t\022\030\n\020cost_estimate" "_ns\030* \001(\003\022\n\n\002id\030# \001(\003\022\023\n\013operand_ids\030$ \003" "(\003\022\037\n\027control_predecessor_ids\030% \003(\003\022\036\n\026c" "alled_computation_ids\030& \003(\003\022!\n\010sharding\030" "( \001(\0132\017.xla.OpSharding\022\026\n\016backend_config" "\030+ \001(\t\022)\n\016replica_groups\0301 \003(\0132\021.xla.Rep" "licaGroup\022\025\n\rall_reduce_id\030- \001(\003\022!\n\031cros" "s_replica_sum_barrier\030. \001(\t\022\030\n\020is_host_t" "ransfer\030/ \001(\010\022\?\n\031scatter_dimension_numbe" "rs\0300 \001(\0132\034.xla.ScatterDimensionNumbers\022." "\n\020precision_config\0303 \001(\0132\024.xla.Precision" "Config\022.\n\023source_target_pairs\0304 \003(\0132\021.xl" "a.SourceTarget\022.\n\025domain_entry_sharding\030" "6 \001(\0132\017.xla.OpSharding\022-\n\024domain_exit_sh" "arding\0307 \001(\0132\017.xla.OpSharding\022\030\n\020constra" "in_layout\0308 \001(\010\0223\n\032operand_shapes_with_l" "ayout\0309 \003(\0132\017.xla.ShapeProto\032\?\n\017SliceDim" "ensions\022\r\n\005start\030\001 \001(\003\022\r\n\005limit\030\002 \001(\003\022\016\n" "\006stride\030\003 \001(\003J\004\010\n\020\013J\004\010\014\020\rJ\004\010\004\020\005J\004\010\005\020\006J\004\010" "\006\020\007J\004\010,\020-R\016parameter_nameR\036fused_instruc" "tions_computationR\roperand_namesR\031contro" "l_predecessor_namesR\030called_computation_" "namesR\021replica_group_ids\"\260\001\n\023HloComputat" "ionProto\022\014\n\004name\030\001 \001(\t\022.\n\014instructions\030\002" " \003(\0132\030.xla.HloInstructionProto\022-\n\rprogra" "m_shape\030\004 \001(\0132\026.xla.ProgramShapeProto\022\n\n" "\002id\030\005 \001(\003\022\017\n\007root_id\030\006 \001(\003J\004\010\003\020\004R\troot_n" "ame\"\330\001\n\020HloScheduleProto\0227\n\tsequences\030\001 " "\003(\0132$.xla.HloScheduleProto.SequencesEntr" "y\032.\n\023InstructionSequence\022\027\n\017instruction_" "ids\030\001 \003(\003\032[\n\016SequencesEntry\022\013\n\003key\030\001 \001(\003" "\0228\n\005value\030\002 \001(\0132).xla.HloScheduleProto.I" "nstructionSequence:\0028\001\"\302\001\n\030HloInputOutpu" "tAliasProto\022>\n\007entries\030\001 \003(\0132-.xla.HloIn" "putOutputAliasProto.AliasEntryProto\032f\n\017A" "liasEntryProto\022\032\n\022output_shape_index\030\001 \003" "(\003\022\030\n\020parameter_number\030\002 \001(\003\022\035\n\025paramete" "r_shape_index\030\003 \003(\003\"\362\001\n\034DynamicParameter" "BindingProto\022:\n\007entries\030\001 \003(\0132).xla.Dyna" "micParameterBindingProto.Binding\032\225\001\n\007Bin" "ding\022\031\n\021dynamic_param_num\030\001 \001(\003\022\033\n\023dynam" "ic_param_index\030\002 \003(\003\022\030\n\020target_param_num" "\030\003 \001(\003\022\032\n\022target_param_index\030\004 \003(\003\022\034\n\024ta" "rget_param_dim_num\030\005 \001(\003\"\366\002\n\016HloModulePr" "oto\022\014\n\004name\030\001 \001(\t\022\036\n\026entry_computation_n" "ame\030\002 \001(\t\022\034\n\024entry_computation_id\030\006 \001(\003\022" ".\n\014computations\030\003 \003(\0132\030.xla.HloComputati" "onProto\0222\n\022host_program_shape\030\004 \001(\0132\026.xl" "a.ProgramShapeProto\022\n\n\002id\030\005 \001(\003\022\'\n\010sched" "ule\030\007 \001(\0132\025.xla.HloScheduleProto\0229\n\022inpu" "t_output_alias\030\010 \001(\0132\035.xla.HloInputOutpu" "tAliasProto\022D\n\031dynamic_parameter_binding" "\030\t \001(\0132!.xla.DynamicParameterBindingProt" "o\"\310\001\n\022LogicalBufferProto\022\n\n\002id\030\001 \001(\003\022\014\n\004" "size\030\002 \001(\003\0224\n\ndefined_at\030\003 \001(\0132 .xla.Log" "icalBufferProto.Location\022\r\n\005color\030\004 \001(\003\032" "S\n\010Location\022\030\n\020computation_name\030\001 \001(\t\022\030\n" "\020instruction_name\030\002 \001(\t\022\023\n\013shape_index\030\003" " \003(\003\"\370\002\n\025BufferAllocationProto\022\r\n\005index\030" "\001 \001(\003\022\014\n\004size\030\002 \001(\003\022\027\n\017is_thread_local\030\003" " \001(\010\022\020\n\010is_tuple\030\013 \001(\010\022&\n\036is_entry_compu" "tation_parameter\030\005 \001(\010\022\023\n\013is_constant\030\014 " "\001(\010\022\030\n\020parameter_number\030\006 \001(\003\022\035\n\025paramet" "er_shape_index\030\n \003(\003\022\026\n\016maybe_live_out\030\007" " \001(\010\022\r\n\005color\030\010 \001(\003\0225\n\010assigned\030\t \003(\0132#." "xla.BufferAllocationProto.Assigned\032C\n\010As" "signed\022\031\n\021logical_buffer_id\030\001 \001(\003\022\016\n\006off" "set\030\002 \001(\003\022\014\n\004size\030\003 \001(\003\"\265\002\n\022HeapSimulato" "rTrace\022-\n\006events\030\001 \003(\0132\035.xla.HeapSimulat" "orTrace.Event\022\037\n\027whole_module_simulation" "\030\002 \001(\010\032\316\001\n\005Event\0220\n\004kind\030\001 \001(\0162\".xla.Hea" "pSimulatorTrace.Event.Kind\022\021\n\tbuffer_id\030" "\002 \001(\003\022\030\n\020computation_name\030\003 \001(\t\022\030\n\020instr" "uction_name\030\004 \001(\t\022\037\n\027share_with_canonica" "l_id\030\005 \001(\003\"+\n\004Kind\022\t\n\005ALLOC\020\000\022\010\n\004FREE\020\001\022" "\016\n\nSHARE_WITH\020\002\"M\n\023HloModuleGroupProto\022\014" "\n\004name\030\001 \001(\t\022(\n\013hlo_modules\030\002 \003(\0132\023.xla." "HloModuleProto\"\326\002\n\025BufferAssignmentProto" "\0220\n\017logical_buffers\030\001 \003(\0132\027.xla.LogicalB" "ufferProto\022>\n\016buffer_aliases\030\002 \003(\0132&.xla" ".BufferAssignmentProto.BufferAlias\0226\n\022bu" "ffer_allocations\030\003 \003(\0132\032.xla.BufferAlloc" "ationProto\0226\n\025heap_simulator_traces\030\004 \003(" "\0132\027.xla.HeapSimulatorTrace\032[\n\013BufferAlia" "s\022\030\n\020source_buffer_id\030\001 \001(\003\0222\n\010location\030" "\002 \001(\0132 .xla.LogicalBufferProto.Location\"" "~\n\010HloProto\022\'\n\nhlo_module\030\001 \001(\0132\023.xla.Hl" "oModuleProto\0225\n\021buffer_assignment\030\003 \001(\0132" "\032.xla.BufferAssignmentProtoJ\004\010\002\020\003R\014hlo_o" "rdering\"\216\001\n\013HloSnapshot\022\032\n\003hlo\030\001 \001(\0132\r.x" "la.HloProto\022$\n\targuments\030\002 \003(\0132\021.xla.Lit" "eralProto\022!\n\006result\030\003 \001(\0132\021.xla.LiteralP" "roto\022\032\n\022execution_platform\030\004 \001(\tB\003\370\001\001b\006p" "roto3" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 4845); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "diplomacy_tensorflow/compiler/xla/service/hlo.proto", &protobuf_RegisterTypes); ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fxla_5fdata_2eproto::AddDescriptors(); } void AddDescriptors() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto namespace xla { const ::google::protobuf::EnumDescriptor* HeapSimulatorTrace_Event_Kind_descriptor() { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_enum_descriptors[0]; } bool HeapSimulatorTrace_Event_Kind_IsValid(int value) { switch (value) { case 0: case 1: case 2: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const HeapSimulatorTrace_Event_Kind HeapSimulatorTrace_Event::ALLOC; const HeapSimulatorTrace_Event_Kind HeapSimulatorTrace_Event::FREE; const HeapSimulatorTrace_Event_Kind HeapSimulatorTrace_Event::SHARE_WITH; const HeapSimulatorTrace_Event_Kind HeapSimulatorTrace_Event::Kind_MIN; const HeapSimulatorTrace_Event_Kind HeapSimulatorTrace_Event::Kind_MAX; const int HeapSimulatorTrace_Event::Kind_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 // =================================================================== void HloInstructionProto_SliceDimensions::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HloInstructionProto_SliceDimensions::kStartFieldNumber; const int HloInstructionProto_SliceDimensions::kLimitFieldNumber; const int HloInstructionProto_SliceDimensions::kStrideFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HloInstructionProto_SliceDimensions::HloInstructionProto_SliceDimensions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInstructionProto_SliceDimensions.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.HloInstructionProto.SliceDimensions) } HloInstructionProto_SliceDimensions::HloInstructionProto_SliceDimensions(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInstructionProto_SliceDimensions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.HloInstructionProto.SliceDimensions) } HloInstructionProto_SliceDimensions::HloInstructionProto_SliceDimensions(const HloInstructionProto_SliceDimensions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&start_, &from.start_, static_cast<size_t>(reinterpret_cast<char*>(&stride_) - reinterpret_cast<char*>(&start_)) + sizeof(stride_)); // @@protoc_insertion_point(copy_constructor:xla.HloInstructionProto.SliceDimensions) } void HloInstructionProto_SliceDimensions::SharedCtor() { ::memset(&start_, 0, static_cast<size_t>( reinterpret_cast<char*>(&stride_) - reinterpret_cast<char*>(&start_)) + sizeof(stride_)); } HloInstructionProto_SliceDimensions::~HloInstructionProto_SliceDimensions() { // @@protoc_insertion_point(destructor:xla.HloInstructionProto.SliceDimensions) SharedDtor(); } void HloInstructionProto_SliceDimensions::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void HloInstructionProto_SliceDimensions::ArenaDtor(void* object) { HloInstructionProto_SliceDimensions* _this = reinterpret_cast< HloInstructionProto_SliceDimensions* >(object); (void)_this; } void HloInstructionProto_SliceDimensions::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void HloInstructionProto_SliceDimensions::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HloInstructionProto_SliceDimensions::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HloInstructionProto_SliceDimensions& HloInstructionProto_SliceDimensions::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInstructionProto_SliceDimensions.base); return *internal_default_instance(); } void HloInstructionProto_SliceDimensions::Clear() { // @@protoc_insertion_point(message_clear_start:xla.HloInstructionProto.SliceDimensions) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; ::memset(&start_, 0, static_cast<size_t>( reinterpret_cast<char*>(&stride_) - reinterpret_cast<char*>(&start_)) + sizeof(stride_)); _internal_metadata_.Clear(); } bool HloInstructionProto_SliceDimensions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.HloInstructionProto.SliceDimensions) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int64 start = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &start_))); } else { goto handle_unusual; } break; } // int64 limit = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &limit_))); } else { goto handle_unusual; } break; } // int64 stride = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &stride_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.HloInstructionProto.SliceDimensions) return true; failure: // @@protoc_insertion_point(parse_failure:xla.HloInstructionProto.SliceDimensions) return false; #undef DO_ } void HloInstructionProto_SliceDimensions::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.HloInstructionProto.SliceDimensions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 start = 1; if (this->start() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->start(), output); } // int64 limit = 2; if (this->limit() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->limit(), output); } // int64 stride = 3; if (this->stride() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(3, this->stride(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.HloInstructionProto.SliceDimensions) } ::google::protobuf::uint8* HloInstructionProto_SliceDimensions::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.HloInstructionProto.SliceDimensions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 start = 1; if (this->start() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->start(), target); } // int64 limit = 2; if (this->limit() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(2, this->limit(), target); } // int64 stride = 3; if (this->stride() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(3, this->stride(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.HloInstructionProto.SliceDimensions) return target; } size_t HloInstructionProto_SliceDimensions::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.HloInstructionProto.SliceDimensions) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // int64 start = 1; if (this->start() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->start()); } // int64 limit = 2; if (this->limit() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->limit()); } // int64 stride = 3; if (this->stride() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->stride()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HloInstructionProto_SliceDimensions::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.HloInstructionProto.SliceDimensions) GOOGLE_DCHECK_NE(&from, this); const HloInstructionProto_SliceDimensions* source = ::google::protobuf::internal::DynamicCastToGenerated<const HloInstructionProto_SliceDimensions>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.HloInstructionProto.SliceDimensions) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.HloInstructionProto.SliceDimensions) MergeFrom(*source); } } void HloInstructionProto_SliceDimensions::MergeFrom(const HloInstructionProto_SliceDimensions& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.HloInstructionProto.SliceDimensions) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.start() != 0) { set_start(from.start()); } if (from.limit() != 0) { set_limit(from.limit()); } if (from.stride() != 0) { set_stride(from.stride()); } } void HloInstructionProto_SliceDimensions::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.HloInstructionProto.SliceDimensions) if (&from == this) return; Clear(); MergeFrom(from); } void HloInstructionProto_SliceDimensions::CopyFrom(const HloInstructionProto_SliceDimensions& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.HloInstructionProto.SliceDimensions) if (&from == this) return; Clear(); MergeFrom(from); } bool HloInstructionProto_SliceDimensions::IsInitialized() const { return true; } void HloInstructionProto_SliceDimensions::Swap(HloInstructionProto_SliceDimensions* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { HloInstructionProto_SliceDimensions* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void HloInstructionProto_SliceDimensions::UnsafeArenaSwap(HloInstructionProto_SliceDimensions* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void HloInstructionProto_SliceDimensions::InternalSwap(HloInstructionProto_SliceDimensions* other) { using std::swap; swap(start_, other->start_); swap(limit_, other->limit_); swap(stride_, other->stride_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HloInstructionProto_SliceDimensions::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void HloInstructionProto::InitAsDefaultInstance() { ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->shape_ = const_cast< ::xla::ShapeProto*>( ::xla::ShapeProto::internal_default_instance()); ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->metadata_ = const_cast< ::xla::OpMetadata*>( ::xla::OpMetadata::internal_default_instance()); ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->literal_ = const_cast< ::xla::LiteralProto*>( ::xla::LiteralProto::internal_default_instance()); ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->window_ = const_cast< ::xla::Window*>( ::xla::Window::internal_default_instance()); ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->convolution_dimension_numbers_ = const_cast< ::xla::ConvolutionDimensionNumbers*>( ::xla::ConvolutionDimensionNumbers::internal_default_instance()); ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->padding_config_ = const_cast< ::xla::PaddingConfig*>( ::xla::PaddingConfig::internal_default_instance()); ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->outfeed_shape_ = const_cast< ::xla::ShapeProto*>( ::xla::ShapeProto::internal_default_instance()); ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->dot_dimension_numbers_ = const_cast< ::xla::DotDimensionNumbers*>( ::xla::DotDimensionNumbers::internal_default_instance()); ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->gather_dimension_numbers_ = const_cast< ::xla::GatherDimensionNumbers*>( ::xla::GatherDimensionNumbers::internal_default_instance()); ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->sharding_ = const_cast< ::xla::OpSharding*>( ::xla::OpSharding::internal_default_instance()); ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->scatter_dimension_numbers_ = const_cast< ::xla::ScatterDimensionNumbers*>( ::xla::ScatterDimensionNumbers::internal_default_instance()); ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->precision_config_ = const_cast< ::xla::PrecisionConfig*>( ::xla::PrecisionConfig::internal_default_instance()); ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->domain_entry_sharding_ = const_cast< ::xla::OpSharding*>( ::xla::OpSharding::internal_default_instance()); ::xla::_HloInstructionProto_default_instance_._instance.get_mutable()->domain_exit_sharding_ = const_cast< ::xla::OpSharding*>( ::xla::OpSharding::internal_default_instance()); } void HloInstructionProto::unsafe_arena_set_allocated_shape( ::xla::ShapeProto* shape) { if (GetArenaNoVirtual() == NULL) { delete shape_; } shape_ = shape; if (shape) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.shape) } void HloInstructionProto::clear_shape() { if (GetArenaNoVirtual() == NULL && shape_ != NULL) { delete shape_; } shape_ = NULL; } void HloInstructionProto::unsafe_arena_set_allocated_metadata( ::xla::OpMetadata* metadata) { if (GetArenaNoVirtual() == NULL) { delete metadata_; } metadata_ = metadata; if (metadata) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.metadata) } void HloInstructionProto::clear_metadata() { if (GetArenaNoVirtual() == NULL && metadata_ != NULL) { delete metadata_; } metadata_ = NULL; } void HloInstructionProto::unsafe_arena_set_allocated_literal( ::xla::LiteralProto* literal) { if (GetArenaNoVirtual() == NULL) { delete literal_; } literal_ = literal; if (literal) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.literal) } void HloInstructionProto::clear_literal() { if (GetArenaNoVirtual() == NULL && literal_ != NULL) { delete literal_; } literal_ = NULL; } void HloInstructionProto::unsafe_arena_set_allocated_window( ::xla::Window* window) { if (GetArenaNoVirtual() == NULL) { delete window_; } window_ = window; if (window) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.window) } void HloInstructionProto::clear_window() { if (GetArenaNoVirtual() == NULL && window_ != NULL) { delete window_; } window_ = NULL; } void HloInstructionProto::unsafe_arena_set_allocated_convolution_dimension_numbers( ::xla::ConvolutionDimensionNumbers* convolution_dimension_numbers) { if (GetArenaNoVirtual() == NULL) { delete convolution_dimension_numbers_; } convolution_dimension_numbers_ = convolution_dimension_numbers; if (convolution_dimension_numbers) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.convolution_dimension_numbers) } void HloInstructionProto::clear_convolution_dimension_numbers() { if (GetArenaNoVirtual() == NULL && convolution_dimension_numbers_ != NULL) { delete convolution_dimension_numbers_; } convolution_dimension_numbers_ = NULL; } void HloInstructionProto::unsafe_arena_set_allocated_padding_config( ::xla::PaddingConfig* padding_config) { if (GetArenaNoVirtual() == NULL) { delete padding_config_; } padding_config_ = padding_config; if (padding_config) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.padding_config) } void HloInstructionProto::clear_padding_config() { if (GetArenaNoVirtual() == NULL && padding_config_ != NULL) { delete padding_config_; } padding_config_ = NULL; } void HloInstructionProto::unsafe_arena_set_allocated_outfeed_shape( ::xla::ShapeProto* outfeed_shape) { if (GetArenaNoVirtual() == NULL) { delete outfeed_shape_; } outfeed_shape_ = outfeed_shape; if (outfeed_shape) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.outfeed_shape) } void HloInstructionProto::clear_outfeed_shape() { if (GetArenaNoVirtual() == NULL && outfeed_shape_ != NULL) { delete outfeed_shape_; } outfeed_shape_ = NULL; } void HloInstructionProto::unsafe_arena_set_allocated_dot_dimension_numbers( ::xla::DotDimensionNumbers* dot_dimension_numbers) { if (GetArenaNoVirtual() == NULL) { delete dot_dimension_numbers_; } dot_dimension_numbers_ = dot_dimension_numbers; if (dot_dimension_numbers) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.dot_dimension_numbers) } void HloInstructionProto::clear_dot_dimension_numbers() { if (GetArenaNoVirtual() == NULL && dot_dimension_numbers_ != NULL) { delete dot_dimension_numbers_; } dot_dimension_numbers_ = NULL; } void HloInstructionProto::unsafe_arena_set_allocated_gather_dimension_numbers( ::xla::GatherDimensionNumbers* gather_dimension_numbers) { if (GetArenaNoVirtual() == NULL) { delete gather_dimension_numbers_; } gather_dimension_numbers_ = gather_dimension_numbers; if (gather_dimension_numbers) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.gather_dimension_numbers) } void HloInstructionProto::clear_gather_dimension_numbers() { if (GetArenaNoVirtual() == NULL && gather_dimension_numbers_ != NULL) { delete gather_dimension_numbers_; } gather_dimension_numbers_ = NULL; } void HloInstructionProto::unsafe_arena_set_allocated_sharding( ::xla::OpSharding* sharding) { if (GetArenaNoVirtual() == NULL) { delete sharding_; } sharding_ = sharding; if (sharding) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.sharding) } void HloInstructionProto::clear_sharding() { if (GetArenaNoVirtual() == NULL && sharding_ != NULL) { delete sharding_; } sharding_ = NULL; } void HloInstructionProto::clear_replica_groups() { replica_groups_.Clear(); } void HloInstructionProto::unsafe_arena_set_allocated_scatter_dimension_numbers( ::xla::ScatterDimensionNumbers* scatter_dimension_numbers) { if (GetArenaNoVirtual() == NULL) { delete scatter_dimension_numbers_; } scatter_dimension_numbers_ = scatter_dimension_numbers; if (scatter_dimension_numbers) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.scatter_dimension_numbers) } void HloInstructionProto::clear_scatter_dimension_numbers() { if (GetArenaNoVirtual() == NULL && scatter_dimension_numbers_ != NULL) { delete scatter_dimension_numbers_; } scatter_dimension_numbers_ = NULL; } void HloInstructionProto::unsafe_arena_set_allocated_precision_config( ::xla::PrecisionConfig* precision_config) { if (GetArenaNoVirtual() == NULL) { delete precision_config_; } precision_config_ = precision_config; if (precision_config) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.precision_config) } void HloInstructionProto::clear_precision_config() { if (GetArenaNoVirtual() == NULL && precision_config_ != NULL) { delete precision_config_; } precision_config_ = NULL; } void HloInstructionProto::clear_source_target_pairs() { source_target_pairs_.Clear(); } void HloInstructionProto::unsafe_arena_set_allocated_domain_entry_sharding( ::xla::OpSharding* domain_entry_sharding) { if (GetArenaNoVirtual() == NULL) { delete domain_entry_sharding_; } domain_entry_sharding_ = domain_entry_sharding; if (domain_entry_sharding) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.domain_entry_sharding) } void HloInstructionProto::clear_domain_entry_sharding() { if (GetArenaNoVirtual() == NULL && domain_entry_sharding_ != NULL) { delete domain_entry_sharding_; } domain_entry_sharding_ = NULL; } void HloInstructionProto::unsafe_arena_set_allocated_domain_exit_sharding( ::xla::OpSharding* domain_exit_sharding) { if (GetArenaNoVirtual() == NULL) { delete domain_exit_sharding_; } domain_exit_sharding_ = domain_exit_sharding; if (domain_exit_sharding) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.domain_exit_sharding) } void HloInstructionProto::clear_domain_exit_sharding() { if (GetArenaNoVirtual() == NULL && domain_exit_sharding_ != NULL) { delete domain_exit_sharding_; } domain_exit_sharding_ = NULL; } void HloInstructionProto::clear_operand_shapes_with_layout() { operand_shapes_with_layout_.Clear(); } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HloInstructionProto::kNameFieldNumber; const int HloInstructionProto::kOpcodeFieldNumber; const int HloInstructionProto::kShapeFieldNumber; const int HloInstructionProto::kMetadataFieldNumber; const int HloInstructionProto::kLiteralFieldNumber; const int HloInstructionProto::kParameterNumberFieldNumber; const int HloInstructionProto::kFusionKindFieldNumber; const int HloInstructionProto::kTupleIndexFieldNumber; const int HloInstructionProto::kDimensionsFieldNumber; const int HloInstructionProto::kWindowFieldNumber; const int HloInstructionProto::kConvolutionDimensionNumbersFieldNumber; const int HloInstructionProto::kFeatureGroupCountFieldNumber; const int HloInstructionProto::kSliceDimensionsFieldNumber; const int HloInstructionProto::kExponentBitsFieldNumber; const int HloInstructionProto::kMantissaBitsFieldNumber; const int HloInstructionProto::kDynamicSliceSizesFieldNumber; const int HloInstructionProto::kPaddingConfigFieldNumber; const int HloInstructionProto::kOutfeedConfigFieldNumber; const int HloInstructionProto::kDistributionFieldNumber; const int HloInstructionProto::kEpsilonFieldNumber; const int HloInstructionProto::kFeatureIndexFieldNumber; const int HloInstructionProto::kChannelIdFieldNumber; const int HloInstructionProto::kInfeedConfigFieldNumber; const int HloInstructionProto::kCustomCallTargetFieldNumber; const int HloInstructionProto::kCustomCallOpaqueFieldNumber; const int HloInstructionProto::kOutfeedShapeFieldNumber; const int HloInstructionProto::kDotDimensionNumbersFieldNumber; const int HloInstructionProto::kFftTypeFieldNumber; const int HloInstructionProto::kFftLengthFieldNumber; const int HloInstructionProto::kGatherDimensionNumbersFieldNumber; const int HloInstructionProto::kGatherSliceSizesFieldNumber; const int HloInstructionProto::kChannelNameFieldNumber; const int HloInstructionProto::kCostEstimateNsFieldNumber; const int HloInstructionProto::kIdFieldNumber; const int HloInstructionProto::kOperandIdsFieldNumber; const int HloInstructionProto::kControlPredecessorIdsFieldNumber; const int HloInstructionProto::kCalledComputationIdsFieldNumber; const int HloInstructionProto::kShardingFieldNumber; const int HloInstructionProto::kBackendConfigFieldNumber; const int HloInstructionProto::kReplicaGroupsFieldNumber; const int HloInstructionProto::kAllReduceIdFieldNumber; const int HloInstructionProto::kCrossReplicaSumBarrierFieldNumber; const int HloInstructionProto::kIsHostTransferFieldNumber; const int HloInstructionProto::kScatterDimensionNumbersFieldNumber; const int HloInstructionProto::kPrecisionConfigFieldNumber; const int HloInstructionProto::kSourceTargetPairsFieldNumber; const int HloInstructionProto::kDomainEntryShardingFieldNumber; const int HloInstructionProto::kDomainExitShardingFieldNumber; const int HloInstructionProto::kConstrainLayoutFieldNumber; const int HloInstructionProto::kOperandShapesWithLayoutFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HloInstructionProto::HloInstructionProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInstructionProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.HloInstructionProto) } HloInstructionProto::HloInstructionProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), dimensions_(arena), slice_dimensions_(arena), dynamic_slice_sizes_(arena), fft_length_(arena), gather_slice_sizes_(arena), operand_ids_(arena), control_predecessor_ids_(arena), called_computation_ids_(arena), replica_groups_(arena), source_target_pairs_(arena), operand_shapes_with_layout_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInstructionProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.HloInstructionProto) } HloInstructionProto::HloInstructionProto(const HloInstructionProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), dimensions_(from.dimensions_), slice_dimensions_(from.slice_dimensions_), dynamic_slice_sizes_(from.dynamic_slice_sizes_), fft_length_(from.fft_length_), gather_slice_sizes_(from.gather_slice_sizes_), operand_ids_(from.operand_ids_), control_predecessor_ids_(from.control_predecessor_ids_), called_computation_ids_(from.called_computation_ids_), replica_groups_(from.replica_groups_), source_target_pairs_(from.source_target_pairs_), operand_shapes_with_layout_(from.operand_shapes_with_layout_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(), GetArenaNoVirtual()); } opcode_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.opcode().size() > 0) { opcode_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.opcode(), GetArenaNoVirtual()); } fusion_kind_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.fusion_kind().size() > 0) { fusion_kind_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.fusion_kind(), GetArenaNoVirtual()); } outfeed_config_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.outfeed_config().size() > 0) { outfeed_config_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.outfeed_config(), GetArenaNoVirtual()); } infeed_config_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.infeed_config().size() > 0) { infeed_config_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.infeed_config(), GetArenaNoVirtual()); } custom_call_target_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.custom_call_target().size() > 0) { custom_call_target_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.custom_call_target(), GetArenaNoVirtual()); } channel_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.channel_name().size() > 0) { channel_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.channel_name(), GetArenaNoVirtual()); } backend_config_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.backend_config().size() > 0) { backend_config_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.backend_config(), GetArenaNoVirtual()); } cross_replica_sum_barrier_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.cross_replica_sum_barrier().size() > 0) { cross_replica_sum_barrier_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.cross_replica_sum_barrier(), GetArenaNoVirtual()); } custom_call_opaque_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.custom_call_opaque().size() > 0) { custom_call_opaque_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.custom_call_opaque(), GetArenaNoVirtual()); } if (from.has_shape()) { shape_ = new ::xla::ShapeProto(*from.shape_); } else { shape_ = NULL; } if (from.has_metadata()) { metadata_ = new ::xla::OpMetadata(*from.metadata_); } else { metadata_ = NULL; } if (from.has_literal()) { literal_ = new ::xla::LiteralProto(*from.literal_); } else { literal_ = NULL; } if (from.has_window()) { window_ = new ::xla::Window(*from.window_); } else { window_ = NULL; } if (from.has_convolution_dimension_numbers()) { convolution_dimension_numbers_ = new ::xla::ConvolutionDimensionNumbers(*from.convolution_dimension_numbers_); } else { convolution_dimension_numbers_ = NULL; } if (from.has_padding_config()) { padding_config_ = new ::xla::PaddingConfig(*from.padding_config_); } else { padding_config_ = NULL; } if (from.has_outfeed_shape()) { outfeed_shape_ = new ::xla::ShapeProto(*from.outfeed_shape_); } else { outfeed_shape_ = NULL; } if (from.has_dot_dimension_numbers()) { dot_dimension_numbers_ = new ::xla::DotDimensionNumbers(*from.dot_dimension_numbers_); } else { dot_dimension_numbers_ = NULL; } if (from.has_gather_dimension_numbers()) { gather_dimension_numbers_ = new ::xla::GatherDimensionNumbers(*from.gather_dimension_numbers_); } else { gather_dimension_numbers_ = NULL; } if (from.has_sharding()) { sharding_ = new ::xla::OpSharding(*from.sharding_); } else { sharding_ = NULL; } if (from.has_scatter_dimension_numbers()) { scatter_dimension_numbers_ = new ::xla::ScatterDimensionNumbers(*from.scatter_dimension_numbers_); } else { scatter_dimension_numbers_ = NULL; } if (from.has_precision_config()) { precision_config_ = new ::xla::PrecisionConfig(*from.precision_config_); } else { precision_config_ = NULL; } if (from.has_domain_entry_sharding()) { domain_entry_sharding_ = new ::xla::OpSharding(*from.domain_entry_sharding_); } else { domain_entry_sharding_ = NULL; } if (from.has_domain_exit_sharding()) { domain_exit_sharding_ = new ::xla::OpSharding(*from.domain_exit_sharding_); } else { domain_exit_sharding_ = NULL; } ::memcpy(&parameter_number_, &from.parameter_number_, static_cast<size_t>(reinterpret_cast<char*>(&feature_group_count_) - reinterpret_cast<char*>(&parameter_number_)) + sizeof(feature_group_count_)); // @@protoc_insertion_point(copy_constructor:xla.HloInstructionProto) } void HloInstructionProto::SharedCtor() { name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); opcode_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); fusion_kind_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); outfeed_config_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); infeed_config_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); custom_call_target_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); channel_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); backend_config_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); cross_replica_sum_barrier_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); custom_call_opaque_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&shape_, 0, static_cast<size_t>( reinterpret_cast<char*>(&feature_group_count_) - reinterpret_cast<char*>(&shape_)) + sizeof(feature_group_count_)); } HloInstructionProto::~HloInstructionProto() { // @@protoc_insertion_point(destructor:xla.HloInstructionProto) SharedDtor(); } void HloInstructionProto::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); opcode_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); fusion_kind_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); outfeed_config_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); infeed_config_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); custom_call_target_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); channel_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); backend_config_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); cross_replica_sum_barrier_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); custom_call_opaque_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete shape_; if (this != internal_default_instance()) delete metadata_; if (this != internal_default_instance()) delete literal_; if (this != internal_default_instance()) delete window_; if (this != internal_default_instance()) delete convolution_dimension_numbers_; if (this != internal_default_instance()) delete padding_config_; if (this != internal_default_instance()) delete outfeed_shape_; if (this != internal_default_instance()) delete dot_dimension_numbers_; if (this != internal_default_instance()) delete gather_dimension_numbers_; if (this != internal_default_instance()) delete sharding_; if (this != internal_default_instance()) delete scatter_dimension_numbers_; if (this != internal_default_instance()) delete precision_config_; if (this != internal_default_instance()) delete domain_entry_sharding_; if (this != internal_default_instance()) delete domain_exit_sharding_; } void HloInstructionProto::ArenaDtor(void* object) { HloInstructionProto* _this = reinterpret_cast< HloInstructionProto* >(object); (void)_this; } void HloInstructionProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void HloInstructionProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HloInstructionProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HloInstructionProto& HloInstructionProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInstructionProto.base); return *internal_default_instance(); } void HloInstructionProto::Clear() { // @@protoc_insertion_point(message_clear_start:xla.HloInstructionProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; dimensions_.Clear(); slice_dimensions_.Clear(); dynamic_slice_sizes_.Clear(); fft_length_.Clear(); gather_slice_sizes_.Clear(); operand_ids_.Clear(); control_predecessor_ids_.Clear(); called_computation_ids_.Clear(); replica_groups_.Clear(); source_target_pairs_.Clear(); operand_shapes_with_layout_.Clear(); name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); opcode_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); fusion_kind_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); outfeed_config_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); infeed_config_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); custom_call_target_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); channel_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); backend_config_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); cross_replica_sum_barrier_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); custom_call_opaque_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); if (GetArenaNoVirtual() == NULL && shape_ != NULL) { delete shape_; } shape_ = NULL; if (GetArenaNoVirtual() == NULL && metadata_ != NULL) { delete metadata_; } metadata_ = NULL; if (GetArenaNoVirtual() == NULL && literal_ != NULL) { delete literal_; } literal_ = NULL; if (GetArenaNoVirtual() == NULL && window_ != NULL) { delete window_; } window_ = NULL; if (GetArenaNoVirtual() == NULL && convolution_dimension_numbers_ != NULL) { delete convolution_dimension_numbers_; } convolution_dimension_numbers_ = NULL; if (GetArenaNoVirtual() == NULL && padding_config_ != NULL) { delete padding_config_; } padding_config_ = NULL; if (GetArenaNoVirtual() == NULL && outfeed_shape_ != NULL) { delete outfeed_shape_; } outfeed_shape_ = NULL; if (GetArenaNoVirtual() == NULL && dot_dimension_numbers_ != NULL) { delete dot_dimension_numbers_; } dot_dimension_numbers_ = NULL; if (GetArenaNoVirtual() == NULL && gather_dimension_numbers_ != NULL) { delete gather_dimension_numbers_; } gather_dimension_numbers_ = NULL; if (GetArenaNoVirtual() == NULL && sharding_ != NULL) { delete sharding_; } sharding_ = NULL; if (GetArenaNoVirtual() == NULL && scatter_dimension_numbers_ != NULL) { delete scatter_dimension_numbers_; } scatter_dimension_numbers_ = NULL; if (GetArenaNoVirtual() == NULL && precision_config_ != NULL) { delete precision_config_; } precision_config_ = NULL; if (GetArenaNoVirtual() == NULL && domain_entry_sharding_ != NULL) { delete domain_entry_sharding_; } domain_entry_sharding_ = NULL; if (GetArenaNoVirtual() == NULL && domain_exit_sharding_ != NULL) { delete domain_exit_sharding_; } domain_exit_sharding_ = NULL; ::memset(&parameter_number_, 0, static_cast<size_t>( reinterpret_cast<char*>(&feature_group_count_) - reinterpret_cast<char*>(&parameter_number_)) + sizeof(feature_group_count_)); _internal_metadata_.Clear(); } bool HloInstructionProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.HloInstructionProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string name = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HloInstructionProto.name")); } else { goto handle_unusual; } break; } // string opcode = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_opcode())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->opcode().data(), static_cast<int>(this->opcode().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HloInstructionProto.opcode")); } else { goto handle_unusual; } break; } // .xla.ShapeProto shape = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_shape())); } else { goto handle_unusual; } break; } // .xla.OpMetadata metadata = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_metadata())); } else { goto handle_unusual; } break; } // .xla.LiteralProto literal = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_literal())); } else { goto handle_unusual; } break; } // int64 parameter_number = 9; case 9: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(72u /* 72 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &parameter_number_))); } else { goto handle_unusual; } break; } // string fusion_kind = 11; case 11: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(90u /* 90 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_fusion_kind())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->fusion_kind().data(), static_cast<int>(this->fusion_kind().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HloInstructionProto.fusion_kind")); } else { goto handle_unusual; } break; } // int64 tuple_index = 13; case 13: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(104u /* 104 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &tuple_index_))); } else { goto handle_unusual; } break; } // repeated int64 dimensions = 14; case 14: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(114u /* 114 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_dimensions()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(112u /* 112 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 1, 114u, input, this->mutable_dimensions()))); } else { goto handle_unusual; } break; } // .xla.Window window = 15; case 15: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_window())); } else { goto handle_unusual; } break; } // .xla.ConvolutionDimensionNumbers convolution_dimension_numbers = 16; case 16: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(130u /* 130 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_convolution_dimension_numbers())); } else { goto handle_unusual; } break; } // repeated .xla.HloInstructionProto.SliceDimensions slice_dimensions = 17; case 17: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(138u /* 138 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_slice_dimensions())); } else { goto handle_unusual; } break; } // int32 exponent_bits = 18; case 18: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(144u /* 144 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &exponent_bits_))); } else { goto handle_unusual; } break; } // int32 mantissa_bits = 19; case 19: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(152u /* 152 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &mantissa_bits_))); } else { goto handle_unusual; } break; } // repeated int64 dynamic_slice_sizes = 20; case 20: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(162u /* 162 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_dynamic_slice_sizes()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(160u /* 160 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 2, 162u, input, this->mutable_dynamic_slice_sizes()))); } else { goto handle_unusual; } break; } // .xla.PaddingConfig padding_config = 21; case 21: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(170u /* 170 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_padding_config())); } else { goto handle_unusual; } break; } // bytes outfeed_config = 22; case 22: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(178u /* 178 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_outfeed_config())); } else { goto handle_unusual; } break; } // .xla.RandomDistribution distribution = 23; case 23: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(184u /* 184 & 0xFF */)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_distribution(static_cast< ::xla::RandomDistribution >(value)); } else { goto handle_unusual; } break; } // float epsilon = 24; case 24: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(197u /* 197 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &epsilon_))); } else { goto handle_unusual; } break; } // int64 feature_index = 25; case 25: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(200u /* 200 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &feature_index_))); } else { goto handle_unusual; } break; } // int64 channel_id = 26; case 26: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(208u /* 208 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &channel_id_))); } else { goto handle_unusual; } break; } // bytes infeed_config = 27; case 27: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(218u /* 218 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_infeed_config())); } else { goto handle_unusual; } break; } // string custom_call_target = 28; case 28: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(226u /* 226 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_custom_call_target())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->custom_call_target().data(), static_cast<int>(this->custom_call_target().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HloInstructionProto.custom_call_target")); } else { goto handle_unusual; } break; } // .xla.ShapeProto outfeed_shape = 29; case 29: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(234u /* 234 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_outfeed_shape())); } else { goto handle_unusual; } break; } // .xla.DotDimensionNumbers dot_dimension_numbers = 30; case 30: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(242u /* 242 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_dot_dimension_numbers())); } else { goto handle_unusual; } break; } // .xla.FftType fft_type = 31; case 31: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(248u /* 248 & 0xFF */)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_fft_type(static_cast< ::xla::FftType >(value)); } else { goto handle_unusual; } break; } // repeated int64 fft_length = 32; case 32: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(2u /* 258 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_fft_length()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(0u /* 256 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 2, 258u, input, this->mutable_fft_length()))); } else { goto handle_unusual; } break; } // .xla.GatherDimensionNumbers gather_dimension_numbers = 33; case 33: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 266 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_gather_dimension_numbers())); } else { goto handle_unusual; } break; } // repeated int64 gather_slice_sizes = 34; case 34: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 274 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_gather_slice_sizes()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 272 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 2, 274u, input, this->mutable_gather_slice_sizes()))); } else { goto handle_unusual; } break; } // int64 id = 35; case 35: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 280 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &id_))); } else { goto handle_unusual; } break; } // repeated int64 operand_ids = 36; case 36: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 290 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_operand_ids()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u /* 288 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 2, 290u, input, this->mutable_operand_ids()))); } else { goto handle_unusual; } break; } // repeated int64 control_predecessor_ids = 37; case 37: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(42u /* 298 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_control_predecessor_ids()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 296 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 2, 298u, input, this->mutable_control_predecessor_ids()))); } else { goto handle_unusual; } break; } // repeated int64 called_computation_ids = 38; case 38: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(50u /* 306 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_called_computation_ids()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(48u /* 304 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 2, 306u, input, this->mutable_called_computation_ids()))); } else { goto handle_unusual; } break; } // .xla.OpSharding sharding = 40; case 40: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(66u /* 322 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_sharding())); } else { goto handle_unusual; } break; } // string channel_name = 41; case 41: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(74u /* 330 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_channel_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->channel_name().data(), static_cast<int>(this->channel_name().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HloInstructionProto.channel_name")); } else { goto handle_unusual; } break; } // int64 cost_estimate_ns = 42; case 42: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(80u /* 336 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &cost_estimate_ns_))); } else { goto handle_unusual; } break; } // string backend_config = 43; case 43: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(90u /* 346 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_backend_config())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->backend_config().data(), static_cast<int>(this->backend_config().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HloInstructionProto.backend_config")); } else { goto handle_unusual; } break; } // int64 all_reduce_id = 45; case 45: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(104u /* 360 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &all_reduce_id_))); } else { goto handle_unusual; } break; } // string cross_replica_sum_barrier = 46; case 46: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(114u /* 370 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_cross_replica_sum_barrier())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->cross_replica_sum_barrier().data(), static_cast<int>(this->cross_replica_sum_barrier().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HloInstructionProto.cross_replica_sum_barrier")); } else { goto handle_unusual; } break; } // bool is_host_transfer = 47; case 47: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(120u /* 376 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &is_host_transfer_))); } else { goto handle_unusual; } break; } // .xla.ScatterDimensionNumbers scatter_dimension_numbers = 48; case 48: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(130u /* 386 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_scatter_dimension_numbers())); } else { goto handle_unusual; } break; } // repeated .xla.ReplicaGroup replica_groups = 49; case 49: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(138u /* 394 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_replica_groups())); } else { goto handle_unusual; } break; } // int64 feature_group_count = 50; case 50: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(144u /* 400 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &feature_group_count_))); } else { goto handle_unusual; } break; } // .xla.PrecisionConfig precision_config = 51; case 51: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(154u /* 410 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_precision_config())); } else { goto handle_unusual; } break; } // repeated .xla.SourceTarget source_target_pairs = 52; case 52: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(162u /* 418 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_source_target_pairs())); } else { goto handle_unusual; } break; } // string custom_call_opaque = 53; case 53: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(170u /* 426 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_custom_call_opaque())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->custom_call_opaque().data(), static_cast<int>(this->custom_call_opaque().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HloInstructionProto.custom_call_opaque")); } else { goto handle_unusual; } break; } // .xla.OpSharding domain_entry_sharding = 54; case 54: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(178u /* 434 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_domain_entry_sharding())); } else { goto handle_unusual; } break; } // .xla.OpSharding domain_exit_sharding = 55; case 55: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(186u /* 442 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_domain_exit_sharding())); } else { goto handle_unusual; } break; } // bool constrain_layout = 56; case 56: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(192u /* 448 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &constrain_layout_))); } else { goto handle_unusual; } break; } // repeated .xla.ShapeProto operand_shapes_with_layout = 57; case 57: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(202u /* 458 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_operand_shapes_with_layout())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.HloInstructionProto) return true; failure: // @@protoc_insertion_point(parse_failure:xla.HloInstructionProto) return false; #undef DO_ } void HloInstructionProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.HloInstructionProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // string opcode = 2; if (this->opcode().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->opcode().data(), static_cast<int>(this->opcode().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.opcode"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->opcode(), output); } // .xla.ShapeProto shape = 3; if (this->has_shape()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->_internal_shape(), output); } // .xla.OpMetadata metadata = 7; if (this->has_metadata()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 7, this->_internal_metadata(), output); } // .xla.LiteralProto literal = 8; if (this->has_literal()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 8, this->_internal_literal(), output); } // int64 parameter_number = 9; if (this->parameter_number() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(9, this->parameter_number(), output); } // string fusion_kind = 11; if (this->fusion_kind().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->fusion_kind().data(), static_cast<int>(this->fusion_kind().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.fusion_kind"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 11, this->fusion_kind(), output); } // int64 tuple_index = 13; if (this->tuple_index() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(13, this->tuple_index(), output); } // repeated int64 dimensions = 14; if (this->dimensions_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(14, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _dimensions_cached_byte_size_)); } for (int i = 0, n = this->dimensions_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->dimensions(i), output); } // .xla.Window window = 15; if (this->has_window()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 15, this->_internal_window(), output); } // .xla.ConvolutionDimensionNumbers convolution_dimension_numbers = 16; if (this->has_convolution_dimension_numbers()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 16, this->_internal_convolution_dimension_numbers(), output); } // repeated .xla.HloInstructionProto.SliceDimensions slice_dimensions = 17; for (unsigned int i = 0, n = static_cast<unsigned int>(this->slice_dimensions_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 17, this->slice_dimensions(static_cast<int>(i)), output); } // int32 exponent_bits = 18; if (this->exponent_bits() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(18, this->exponent_bits(), output); } // int32 mantissa_bits = 19; if (this->mantissa_bits() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(19, this->mantissa_bits(), output); } // repeated int64 dynamic_slice_sizes = 20; if (this->dynamic_slice_sizes_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(20, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _dynamic_slice_sizes_cached_byte_size_)); } for (int i = 0, n = this->dynamic_slice_sizes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->dynamic_slice_sizes(i), output); } // .xla.PaddingConfig padding_config = 21; if (this->has_padding_config()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 21, this->_internal_padding_config(), output); } // bytes outfeed_config = 22; if (this->outfeed_config().size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 22, this->outfeed_config(), output); } // .xla.RandomDistribution distribution = 23; if (this->distribution() != 0) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 23, this->distribution(), output); } // float epsilon = 24; if (this->epsilon() != 0) { ::google::protobuf::internal::WireFormatLite::WriteFloat(24, this->epsilon(), output); } // int64 feature_index = 25; if (this->feature_index() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(25, this->feature_index(), output); } // int64 channel_id = 26; if (this->channel_id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(26, this->channel_id(), output); } // bytes infeed_config = 27; if (this->infeed_config().size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 27, this->infeed_config(), output); } // string custom_call_target = 28; if (this->custom_call_target().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->custom_call_target().data(), static_cast<int>(this->custom_call_target().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.custom_call_target"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 28, this->custom_call_target(), output); } // .xla.ShapeProto outfeed_shape = 29; if (this->has_outfeed_shape()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 29, this->_internal_outfeed_shape(), output); } // .xla.DotDimensionNumbers dot_dimension_numbers = 30; if (this->has_dot_dimension_numbers()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 30, this->_internal_dot_dimension_numbers(), output); } // .xla.FftType fft_type = 31; if (this->fft_type() != 0) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 31, this->fft_type(), output); } // repeated int64 fft_length = 32; if (this->fft_length_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(32, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _fft_length_cached_byte_size_)); } for (int i = 0, n = this->fft_length_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->fft_length(i), output); } // .xla.GatherDimensionNumbers gather_dimension_numbers = 33; if (this->has_gather_dimension_numbers()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 33, this->_internal_gather_dimension_numbers(), output); } // repeated int64 gather_slice_sizes = 34; if (this->gather_slice_sizes_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(34, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _gather_slice_sizes_cached_byte_size_)); } for (int i = 0, n = this->gather_slice_sizes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->gather_slice_sizes(i), output); } // int64 id = 35; if (this->id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(35, this->id(), output); } // repeated int64 operand_ids = 36; if (this->operand_ids_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(36, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _operand_ids_cached_byte_size_)); } for (int i = 0, n = this->operand_ids_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->operand_ids(i), output); } // repeated int64 control_predecessor_ids = 37; if (this->control_predecessor_ids_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(37, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _control_predecessor_ids_cached_byte_size_)); } for (int i = 0, n = this->control_predecessor_ids_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->control_predecessor_ids(i), output); } // repeated int64 called_computation_ids = 38; if (this->called_computation_ids_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(38, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _called_computation_ids_cached_byte_size_)); } for (int i = 0, n = this->called_computation_ids_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->called_computation_ids(i), output); } // .xla.OpSharding sharding = 40; if (this->has_sharding()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 40, this->_internal_sharding(), output); } // string channel_name = 41; if (this->channel_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->channel_name().data(), static_cast<int>(this->channel_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.channel_name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 41, this->channel_name(), output); } // int64 cost_estimate_ns = 42; if (this->cost_estimate_ns() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(42, this->cost_estimate_ns(), output); } // string backend_config = 43; if (this->backend_config().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->backend_config().data(), static_cast<int>(this->backend_config().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.backend_config"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 43, this->backend_config(), output); } // int64 all_reduce_id = 45; if (this->all_reduce_id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(45, this->all_reduce_id(), output); } // string cross_replica_sum_barrier = 46; if (this->cross_replica_sum_barrier().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->cross_replica_sum_barrier().data(), static_cast<int>(this->cross_replica_sum_barrier().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.cross_replica_sum_barrier"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 46, this->cross_replica_sum_barrier(), output); } // bool is_host_transfer = 47; if (this->is_host_transfer() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(47, this->is_host_transfer(), output); } // .xla.ScatterDimensionNumbers scatter_dimension_numbers = 48; if (this->has_scatter_dimension_numbers()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 48, this->_internal_scatter_dimension_numbers(), output); } // repeated .xla.ReplicaGroup replica_groups = 49; for (unsigned int i = 0, n = static_cast<unsigned int>(this->replica_groups_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 49, this->replica_groups(static_cast<int>(i)), output); } // int64 feature_group_count = 50; if (this->feature_group_count() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(50, this->feature_group_count(), output); } // .xla.PrecisionConfig precision_config = 51; if (this->has_precision_config()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 51, this->_internal_precision_config(), output); } // repeated .xla.SourceTarget source_target_pairs = 52; for (unsigned int i = 0, n = static_cast<unsigned int>(this->source_target_pairs_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 52, this->source_target_pairs(static_cast<int>(i)), output); } // string custom_call_opaque = 53; if (this->custom_call_opaque().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->custom_call_opaque().data(), static_cast<int>(this->custom_call_opaque().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.custom_call_opaque"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 53, this->custom_call_opaque(), output); } // .xla.OpSharding domain_entry_sharding = 54; if (this->has_domain_entry_sharding()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 54, this->_internal_domain_entry_sharding(), output); } // .xla.OpSharding domain_exit_sharding = 55; if (this->has_domain_exit_sharding()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 55, this->_internal_domain_exit_sharding(), output); } // bool constrain_layout = 56; if (this->constrain_layout() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(56, this->constrain_layout(), output); } // repeated .xla.ShapeProto operand_shapes_with_layout = 57; for (unsigned int i = 0, n = static_cast<unsigned int>(this->operand_shapes_with_layout_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 57, this->operand_shapes_with_layout(static_cast<int>(i)), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.HloInstructionProto) } ::google::protobuf::uint8* HloInstructionProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.HloInstructionProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // string opcode = 2; if (this->opcode().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->opcode().data(), static_cast<int>(this->opcode().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.opcode"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->opcode(), target); } // .xla.ShapeProto shape = 3; if (this->has_shape()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, this->_internal_shape(), deterministic, target); } // .xla.OpMetadata metadata = 7; if (this->has_metadata()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 7, this->_internal_metadata(), deterministic, target); } // .xla.LiteralProto literal = 8; if (this->has_literal()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 8, this->_internal_literal(), deterministic, target); } // int64 parameter_number = 9; if (this->parameter_number() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(9, this->parameter_number(), target); } // string fusion_kind = 11; if (this->fusion_kind().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->fusion_kind().data(), static_cast<int>(this->fusion_kind().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.fusion_kind"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 11, this->fusion_kind(), target); } // int64 tuple_index = 13; if (this->tuple_index() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(13, this->tuple_index(), target); } // repeated int64 dimensions = 14; if (this->dimensions_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 14, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _dimensions_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->dimensions_, target); } // .xla.Window window = 15; if (this->has_window()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 15, this->_internal_window(), deterministic, target); } // .xla.ConvolutionDimensionNumbers convolution_dimension_numbers = 16; if (this->has_convolution_dimension_numbers()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 16, this->_internal_convolution_dimension_numbers(), deterministic, target); } // repeated .xla.HloInstructionProto.SliceDimensions slice_dimensions = 17; for (unsigned int i = 0, n = static_cast<unsigned int>(this->slice_dimensions_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 17, this->slice_dimensions(static_cast<int>(i)), deterministic, target); } // int32 exponent_bits = 18; if (this->exponent_bits() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(18, this->exponent_bits(), target); } // int32 mantissa_bits = 19; if (this->mantissa_bits() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(19, this->mantissa_bits(), target); } // repeated int64 dynamic_slice_sizes = 20; if (this->dynamic_slice_sizes_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 20, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _dynamic_slice_sizes_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->dynamic_slice_sizes_, target); } // .xla.PaddingConfig padding_config = 21; if (this->has_padding_config()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 21, this->_internal_padding_config(), deterministic, target); } // bytes outfeed_config = 22; if (this->outfeed_config().size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 22, this->outfeed_config(), target); } // .xla.RandomDistribution distribution = 23; if (this->distribution() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 23, this->distribution(), target); } // float epsilon = 24; if (this->epsilon() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(24, this->epsilon(), target); } // int64 feature_index = 25; if (this->feature_index() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(25, this->feature_index(), target); } // int64 channel_id = 26; if (this->channel_id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(26, this->channel_id(), target); } // bytes infeed_config = 27; if (this->infeed_config().size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 27, this->infeed_config(), target); } // string custom_call_target = 28; if (this->custom_call_target().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->custom_call_target().data(), static_cast<int>(this->custom_call_target().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.custom_call_target"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 28, this->custom_call_target(), target); } // .xla.ShapeProto outfeed_shape = 29; if (this->has_outfeed_shape()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 29, this->_internal_outfeed_shape(), deterministic, target); } // .xla.DotDimensionNumbers dot_dimension_numbers = 30; if (this->has_dot_dimension_numbers()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 30, this->_internal_dot_dimension_numbers(), deterministic, target); } // .xla.FftType fft_type = 31; if (this->fft_type() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 31, this->fft_type(), target); } // repeated int64 fft_length = 32; if (this->fft_length_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 32, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _fft_length_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->fft_length_, target); } // .xla.GatherDimensionNumbers gather_dimension_numbers = 33; if (this->has_gather_dimension_numbers()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 33, this->_internal_gather_dimension_numbers(), deterministic, target); } // repeated int64 gather_slice_sizes = 34; if (this->gather_slice_sizes_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 34, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _gather_slice_sizes_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->gather_slice_sizes_, target); } // int64 id = 35; if (this->id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(35, this->id(), target); } // repeated int64 operand_ids = 36; if (this->operand_ids_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 36, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _operand_ids_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->operand_ids_, target); } // repeated int64 control_predecessor_ids = 37; if (this->control_predecessor_ids_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 37, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _control_predecessor_ids_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->control_predecessor_ids_, target); } // repeated int64 called_computation_ids = 38; if (this->called_computation_ids_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 38, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _called_computation_ids_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->called_computation_ids_, target); } // .xla.OpSharding sharding = 40; if (this->has_sharding()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 40, this->_internal_sharding(), deterministic, target); } // string channel_name = 41; if (this->channel_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->channel_name().data(), static_cast<int>(this->channel_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.channel_name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 41, this->channel_name(), target); } // int64 cost_estimate_ns = 42; if (this->cost_estimate_ns() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(42, this->cost_estimate_ns(), target); } // string backend_config = 43; if (this->backend_config().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->backend_config().data(), static_cast<int>(this->backend_config().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.backend_config"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 43, this->backend_config(), target); } // int64 all_reduce_id = 45; if (this->all_reduce_id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(45, this->all_reduce_id(), target); } // string cross_replica_sum_barrier = 46; if (this->cross_replica_sum_barrier().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->cross_replica_sum_barrier().data(), static_cast<int>(this->cross_replica_sum_barrier().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.cross_replica_sum_barrier"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 46, this->cross_replica_sum_barrier(), target); } // bool is_host_transfer = 47; if (this->is_host_transfer() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(47, this->is_host_transfer(), target); } // .xla.ScatterDimensionNumbers scatter_dimension_numbers = 48; if (this->has_scatter_dimension_numbers()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 48, this->_internal_scatter_dimension_numbers(), deterministic, target); } // repeated .xla.ReplicaGroup replica_groups = 49; for (unsigned int i = 0, n = static_cast<unsigned int>(this->replica_groups_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 49, this->replica_groups(static_cast<int>(i)), deterministic, target); } // int64 feature_group_count = 50; if (this->feature_group_count() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(50, this->feature_group_count(), target); } // .xla.PrecisionConfig precision_config = 51; if (this->has_precision_config()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 51, this->_internal_precision_config(), deterministic, target); } // repeated .xla.SourceTarget source_target_pairs = 52; for (unsigned int i = 0, n = static_cast<unsigned int>(this->source_target_pairs_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 52, this->source_target_pairs(static_cast<int>(i)), deterministic, target); } // string custom_call_opaque = 53; if (this->custom_call_opaque().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->custom_call_opaque().data(), static_cast<int>(this->custom_call_opaque().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloInstructionProto.custom_call_opaque"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 53, this->custom_call_opaque(), target); } // .xla.OpSharding domain_entry_sharding = 54; if (this->has_domain_entry_sharding()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 54, this->_internal_domain_entry_sharding(), deterministic, target); } // .xla.OpSharding domain_exit_sharding = 55; if (this->has_domain_exit_sharding()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 55, this->_internal_domain_exit_sharding(), deterministic, target); } // bool constrain_layout = 56; if (this->constrain_layout() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(56, this->constrain_layout(), target); } // repeated .xla.ShapeProto operand_shapes_with_layout = 57; for (unsigned int i = 0, n = static_cast<unsigned int>(this->operand_shapes_with_layout_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 57, this->operand_shapes_with_layout(static_cast<int>(i)), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.HloInstructionProto) return target; } size_t HloInstructionProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.HloInstructionProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated int64 dimensions = 14; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->dimensions_); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _dimensions_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated .xla.HloInstructionProto.SliceDimensions slice_dimensions = 17; { unsigned int count = static_cast<unsigned int>(this->slice_dimensions_size()); total_size += 2UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->slice_dimensions(static_cast<int>(i))); } } // repeated int64 dynamic_slice_sizes = 20; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->dynamic_slice_sizes_); if (data_size > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _dynamic_slice_sizes_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated int64 fft_length = 32; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->fft_length_); if (data_size > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _fft_length_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated int64 gather_slice_sizes = 34; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->gather_slice_sizes_); if (data_size > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _gather_slice_sizes_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated int64 operand_ids = 36; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->operand_ids_); if (data_size > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _operand_ids_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated int64 control_predecessor_ids = 37; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->control_predecessor_ids_); if (data_size > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _control_predecessor_ids_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated int64 called_computation_ids = 38; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->called_computation_ids_); if (data_size > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _called_computation_ids_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated .xla.ReplicaGroup replica_groups = 49; { unsigned int count = static_cast<unsigned int>(this->replica_groups_size()); total_size += 2UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->replica_groups(static_cast<int>(i))); } } // repeated .xla.SourceTarget source_target_pairs = 52; { unsigned int count = static_cast<unsigned int>(this->source_target_pairs_size()); total_size += 2UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->source_target_pairs(static_cast<int>(i))); } } // repeated .xla.ShapeProto operand_shapes_with_layout = 57; { unsigned int count = static_cast<unsigned int>(this->operand_shapes_with_layout_size()); total_size += 2UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->operand_shapes_with_layout(static_cast<int>(i))); } } // string name = 1; if (this->name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->name()); } // string opcode = 2; if (this->opcode().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->opcode()); } // string fusion_kind = 11; if (this->fusion_kind().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->fusion_kind()); } // bytes outfeed_config = 22; if (this->outfeed_config().size() > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->outfeed_config()); } // bytes infeed_config = 27; if (this->infeed_config().size() > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->infeed_config()); } // string custom_call_target = 28; if (this->custom_call_target().size() > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::StringSize( this->custom_call_target()); } // string channel_name = 41; if (this->channel_name().size() > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::StringSize( this->channel_name()); } // string backend_config = 43; if (this->backend_config().size() > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::StringSize( this->backend_config()); } // string cross_replica_sum_barrier = 46; if (this->cross_replica_sum_barrier().size() > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::StringSize( this->cross_replica_sum_barrier()); } // string custom_call_opaque = 53; if (this->custom_call_opaque().size() > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::StringSize( this->custom_call_opaque()); } // .xla.ShapeProto shape = 3; if (this->has_shape()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *shape_); } // .xla.OpMetadata metadata = 7; if (this->has_metadata()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *metadata_); } // .xla.LiteralProto literal = 8; if (this->has_literal()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *literal_); } // .xla.Window window = 15; if (this->has_window()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *window_); } // .xla.ConvolutionDimensionNumbers convolution_dimension_numbers = 16; if (this->has_convolution_dimension_numbers()) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::MessageSize( *convolution_dimension_numbers_); } // .xla.PaddingConfig padding_config = 21; if (this->has_padding_config()) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::MessageSize( *padding_config_); } // .xla.ShapeProto outfeed_shape = 29; if (this->has_outfeed_shape()) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::MessageSize( *outfeed_shape_); } // .xla.DotDimensionNumbers dot_dimension_numbers = 30; if (this->has_dot_dimension_numbers()) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::MessageSize( *dot_dimension_numbers_); } // .xla.GatherDimensionNumbers gather_dimension_numbers = 33; if (this->has_gather_dimension_numbers()) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::MessageSize( *gather_dimension_numbers_); } // .xla.OpSharding sharding = 40; if (this->has_sharding()) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::MessageSize( *sharding_); } // .xla.ScatterDimensionNumbers scatter_dimension_numbers = 48; if (this->has_scatter_dimension_numbers()) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::MessageSize( *scatter_dimension_numbers_); } // .xla.PrecisionConfig precision_config = 51; if (this->has_precision_config()) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::MessageSize( *precision_config_); } // .xla.OpSharding domain_entry_sharding = 54; if (this->has_domain_entry_sharding()) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::MessageSize( *domain_entry_sharding_); } // .xla.OpSharding domain_exit_sharding = 55; if (this->has_domain_exit_sharding()) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::MessageSize( *domain_exit_sharding_); } // int64 parameter_number = 9; if (this->parameter_number() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->parameter_number()); } // int64 tuple_index = 13; if (this->tuple_index() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->tuple_index()); } // int32 exponent_bits = 18; if (this->exponent_bits() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->exponent_bits()); } // int32 mantissa_bits = 19; if (this->mantissa_bits() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->mantissa_bits()); } // .xla.RandomDistribution distribution = 23; if (this->distribution() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->distribution()); } // float epsilon = 24; if (this->epsilon() != 0) { total_size += 2 + 4; } // int64 feature_index = 25; if (this->feature_index() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->feature_index()); } // int64 channel_id = 26; if (this->channel_id() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->channel_id()); } // int64 id = 35; if (this->id() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->id()); } // int64 cost_estimate_ns = 42; if (this->cost_estimate_ns() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->cost_estimate_ns()); } // .xla.FftType fft_type = 31; if (this->fft_type() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->fft_type()); } // bool is_host_transfer = 47; if (this->is_host_transfer() != 0) { total_size += 2 + 1; } // bool constrain_layout = 56; if (this->constrain_layout() != 0) { total_size += 2 + 1; } // int64 all_reduce_id = 45; if (this->all_reduce_id() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->all_reduce_id()); } // int64 feature_group_count = 50; if (this->feature_group_count() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->feature_group_count()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HloInstructionProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.HloInstructionProto) GOOGLE_DCHECK_NE(&from, this); const HloInstructionProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const HloInstructionProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.HloInstructionProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.HloInstructionProto) MergeFrom(*source); } } void HloInstructionProto::MergeFrom(const HloInstructionProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.HloInstructionProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; dimensions_.MergeFrom(from.dimensions_); slice_dimensions_.MergeFrom(from.slice_dimensions_); dynamic_slice_sizes_.MergeFrom(from.dynamic_slice_sizes_); fft_length_.MergeFrom(from.fft_length_); gather_slice_sizes_.MergeFrom(from.gather_slice_sizes_); operand_ids_.MergeFrom(from.operand_ids_); control_predecessor_ids_.MergeFrom(from.control_predecessor_ids_); called_computation_ids_.MergeFrom(from.called_computation_ids_); replica_groups_.MergeFrom(from.replica_groups_); source_target_pairs_.MergeFrom(from.source_target_pairs_); operand_shapes_with_layout_.MergeFrom(from.operand_shapes_with_layout_); if (from.name().size() > 0) { set_name(from.name()); } if (from.opcode().size() > 0) { set_opcode(from.opcode()); } if (from.fusion_kind().size() > 0) { set_fusion_kind(from.fusion_kind()); } if (from.outfeed_config().size() > 0) { set_outfeed_config(from.outfeed_config()); } if (from.infeed_config().size() > 0) { set_infeed_config(from.infeed_config()); } if (from.custom_call_target().size() > 0) { set_custom_call_target(from.custom_call_target()); } if (from.channel_name().size() > 0) { set_channel_name(from.channel_name()); } if (from.backend_config().size() > 0) { set_backend_config(from.backend_config()); } if (from.cross_replica_sum_barrier().size() > 0) { set_cross_replica_sum_barrier(from.cross_replica_sum_barrier()); } if (from.custom_call_opaque().size() > 0) { set_custom_call_opaque(from.custom_call_opaque()); } if (from.has_shape()) { mutable_shape()->::xla::ShapeProto::MergeFrom(from.shape()); } if (from.has_metadata()) { mutable_metadata()->::xla::OpMetadata::MergeFrom(from.metadata()); } if (from.has_literal()) { mutable_literal()->::xla::LiteralProto::MergeFrom(from.literal()); } if (from.has_window()) { mutable_window()->::xla::Window::MergeFrom(from.window()); } if (from.has_convolution_dimension_numbers()) { mutable_convolution_dimension_numbers()->::xla::ConvolutionDimensionNumbers::MergeFrom(from.convolution_dimension_numbers()); } if (from.has_padding_config()) { mutable_padding_config()->::xla::PaddingConfig::MergeFrom(from.padding_config()); } if (from.has_outfeed_shape()) { mutable_outfeed_shape()->::xla::ShapeProto::MergeFrom(from.outfeed_shape()); } if (from.has_dot_dimension_numbers()) { mutable_dot_dimension_numbers()->::xla::DotDimensionNumbers::MergeFrom(from.dot_dimension_numbers()); } if (from.has_gather_dimension_numbers()) { mutable_gather_dimension_numbers()->::xla::GatherDimensionNumbers::MergeFrom(from.gather_dimension_numbers()); } if (from.has_sharding()) { mutable_sharding()->::xla::OpSharding::MergeFrom(from.sharding()); } if (from.has_scatter_dimension_numbers()) { mutable_scatter_dimension_numbers()->::xla::ScatterDimensionNumbers::MergeFrom(from.scatter_dimension_numbers()); } if (from.has_precision_config()) { mutable_precision_config()->::xla::PrecisionConfig::MergeFrom(from.precision_config()); } if (from.has_domain_entry_sharding()) { mutable_domain_entry_sharding()->::xla::OpSharding::MergeFrom(from.domain_entry_sharding()); } if (from.has_domain_exit_sharding()) { mutable_domain_exit_sharding()->::xla::OpSharding::MergeFrom(from.domain_exit_sharding()); } if (from.parameter_number() != 0) { set_parameter_number(from.parameter_number()); } if (from.tuple_index() != 0) { set_tuple_index(from.tuple_index()); } if (from.exponent_bits() != 0) { set_exponent_bits(from.exponent_bits()); } if (from.mantissa_bits() != 0) { set_mantissa_bits(from.mantissa_bits()); } if (from.distribution() != 0) { set_distribution(from.distribution()); } if (from.epsilon() != 0) { set_epsilon(from.epsilon()); } if (from.feature_index() != 0) { set_feature_index(from.feature_index()); } if (from.channel_id() != 0) { set_channel_id(from.channel_id()); } if (from.id() != 0) { set_id(from.id()); } if (from.cost_estimate_ns() != 0) { set_cost_estimate_ns(from.cost_estimate_ns()); } if (from.fft_type() != 0) { set_fft_type(from.fft_type()); } if (from.is_host_transfer() != 0) { set_is_host_transfer(from.is_host_transfer()); } if (from.constrain_layout() != 0) { set_constrain_layout(from.constrain_layout()); } if (from.all_reduce_id() != 0) { set_all_reduce_id(from.all_reduce_id()); } if (from.feature_group_count() != 0) { set_feature_group_count(from.feature_group_count()); } } void HloInstructionProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.HloInstructionProto) if (&from == this) return; Clear(); MergeFrom(from); } void HloInstructionProto::CopyFrom(const HloInstructionProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.HloInstructionProto) if (&from == this) return; Clear(); MergeFrom(from); } bool HloInstructionProto::IsInitialized() const { return true; } void HloInstructionProto::Swap(HloInstructionProto* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { HloInstructionProto* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void HloInstructionProto::UnsafeArenaSwap(HloInstructionProto* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void HloInstructionProto::InternalSwap(HloInstructionProto* other) { using std::swap; dimensions_.InternalSwap(&other->dimensions_); CastToBase(&slice_dimensions_)->InternalSwap(CastToBase(&other->slice_dimensions_)); dynamic_slice_sizes_.InternalSwap(&other->dynamic_slice_sizes_); fft_length_.InternalSwap(&other->fft_length_); gather_slice_sizes_.InternalSwap(&other->gather_slice_sizes_); operand_ids_.InternalSwap(&other->operand_ids_); control_predecessor_ids_.InternalSwap(&other->control_predecessor_ids_); called_computation_ids_.InternalSwap(&other->called_computation_ids_); CastToBase(&replica_groups_)->InternalSwap(CastToBase(&other->replica_groups_)); CastToBase(&source_target_pairs_)->InternalSwap(CastToBase(&other->source_target_pairs_)); CastToBase(&operand_shapes_with_layout_)->InternalSwap(CastToBase(&other->operand_shapes_with_layout_)); name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); opcode_.Swap(&other->opcode_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); fusion_kind_.Swap(&other->fusion_kind_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); outfeed_config_.Swap(&other->outfeed_config_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); infeed_config_.Swap(&other->infeed_config_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); custom_call_target_.Swap(&other->custom_call_target_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); channel_name_.Swap(&other->channel_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); backend_config_.Swap(&other->backend_config_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); cross_replica_sum_barrier_.Swap(&other->cross_replica_sum_barrier_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); custom_call_opaque_.Swap(&other->custom_call_opaque_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(shape_, other->shape_); swap(metadata_, other->metadata_); swap(literal_, other->literal_); swap(window_, other->window_); swap(convolution_dimension_numbers_, other->convolution_dimension_numbers_); swap(padding_config_, other->padding_config_); swap(outfeed_shape_, other->outfeed_shape_); swap(dot_dimension_numbers_, other->dot_dimension_numbers_); swap(gather_dimension_numbers_, other->gather_dimension_numbers_); swap(sharding_, other->sharding_); swap(scatter_dimension_numbers_, other->scatter_dimension_numbers_); swap(precision_config_, other->precision_config_); swap(domain_entry_sharding_, other->domain_entry_sharding_); swap(domain_exit_sharding_, other->domain_exit_sharding_); swap(parameter_number_, other->parameter_number_); swap(tuple_index_, other->tuple_index_); swap(exponent_bits_, other->exponent_bits_); swap(mantissa_bits_, other->mantissa_bits_); swap(distribution_, other->distribution_); swap(epsilon_, other->epsilon_); swap(feature_index_, other->feature_index_); swap(channel_id_, other->channel_id_); swap(id_, other->id_); swap(cost_estimate_ns_, other->cost_estimate_ns_); swap(fft_type_, other->fft_type_); swap(is_host_transfer_, other->is_host_transfer_); swap(constrain_layout_, other->constrain_layout_); swap(all_reduce_id_, other->all_reduce_id_); swap(feature_group_count_, other->feature_group_count_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HloInstructionProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void HloComputationProto::InitAsDefaultInstance() { ::xla::_HloComputationProto_default_instance_._instance.get_mutable()->program_shape_ = const_cast< ::xla::ProgramShapeProto*>( ::xla::ProgramShapeProto::internal_default_instance()); } void HloComputationProto::unsafe_arena_set_allocated_program_shape( ::xla::ProgramShapeProto* program_shape) { if (GetArenaNoVirtual() == NULL) { delete program_shape_; } program_shape_ = program_shape; if (program_shape) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloComputationProto.program_shape) } void HloComputationProto::clear_program_shape() { if (GetArenaNoVirtual() == NULL && program_shape_ != NULL) { delete program_shape_; } program_shape_ = NULL; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HloComputationProto::kNameFieldNumber; const int HloComputationProto::kInstructionsFieldNumber; const int HloComputationProto::kProgramShapeFieldNumber; const int HloComputationProto::kIdFieldNumber; const int HloComputationProto::kRootIdFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HloComputationProto::HloComputationProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloComputationProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.HloComputationProto) } HloComputationProto::HloComputationProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), instructions_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloComputationProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.HloComputationProto) } HloComputationProto::HloComputationProto(const HloComputationProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), instructions_(from.instructions_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(), GetArenaNoVirtual()); } if (from.has_program_shape()) { program_shape_ = new ::xla::ProgramShapeProto(*from.program_shape_); } else { program_shape_ = NULL; } ::memcpy(&id_, &from.id_, static_cast<size_t>(reinterpret_cast<char*>(&root_id_) - reinterpret_cast<char*>(&id_)) + sizeof(root_id_)); // @@protoc_insertion_point(copy_constructor:xla.HloComputationProto) } void HloComputationProto::SharedCtor() { name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&program_shape_, 0, static_cast<size_t>( reinterpret_cast<char*>(&root_id_) - reinterpret_cast<char*>(&program_shape_)) + sizeof(root_id_)); } HloComputationProto::~HloComputationProto() { // @@protoc_insertion_point(destructor:xla.HloComputationProto) SharedDtor(); } void HloComputationProto::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete program_shape_; } void HloComputationProto::ArenaDtor(void* object) { HloComputationProto* _this = reinterpret_cast< HloComputationProto* >(object); (void)_this; } void HloComputationProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void HloComputationProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HloComputationProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HloComputationProto& HloComputationProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloComputationProto.base); return *internal_default_instance(); } void HloComputationProto::Clear() { // @@protoc_insertion_point(message_clear_start:xla.HloComputationProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; instructions_.Clear(); name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); if (GetArenaNoVirtual() == NULL && program_shape_ != NULL) { delete program_shape_; } program_shape_ = NULL; ::memset(&id_, 0, static_cast<size_t>( reinterpret_cast<char*>(&root_id_) - reinterpret_cast<char*>(&id_)) + sizeof(root_id_)); _internal_metadata_.Clear(); } bool HloComputationProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.HloComputationProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string name = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HloComputationProto.name")); } else { goto handle_unusual; } break; } // repeated .xla.HloInstructionProto instructions = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_instructions())); } else { goto handle_unusual; } break; } // .xla.ProgramShapeProto program_shape = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_program_shape())); } else { goto handle_unusual; } break; } // int64 id = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &id_))); } else { goto handle_unusual; } break; } // int64 root_id = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &root_id_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.HloComputationProto) return true; failure: // @@protoc_insertion_point(parse_failure:xla.HloComputationProto) return false; #undef DO_ } void HloComputationProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.HloComputationProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloComputationProto.name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // repeated .xla.HloInstructionProto instructions = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->instructions_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->instructions(static_cast<int>(i)), output); } // .xla.ProgramShapeProto program_shape = 4; if (this->has_program_shape()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->_internal_program_shape(), output); } // int64 id = 5; if (this->id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(5, this->id(), output); } // int64 root_id = 6; if (this->root_id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(6, this->root_id(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.HloComputationProto) } ::google::protobuf::uint8* HloComputationProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.HloComputationProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloComputationProto.name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // repeated .xla.HloInstructionProto instructions = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->instructions_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, this->instructions(static_cast<int>(i)), deterministic, target); } // .xla.ProgramShapeProto program_shape = 4; if (this->has_program_shape()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 4, this->_internal_program_shape(), deterministic, target); } // int64 id = 5; if (this->id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(5, this->id(), target); } // int64 root_id = 6; if (this->root_id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(6, this->root_id(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.HloComputationProto) return target; } size_t HloComputationProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.HloComputationProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated .xla.HloInstructionProto instructions = 2; { unsigned int count = static_cast<unsigned int>(this->instructions_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->instructions(static_cast<int>(i))); } } // string name = 1; if (this->name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->name()); } // .xla.ProgramShapeProto program_shape = 4; if (this->has_program_shape()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *program_shape_); } // int64 id = 5; if (this->id() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->id()); } // int64 root_id = 6; if (this->root_id() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->root_id()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HloComputationProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.HloComputationProto) GOOGLE_DCHECK_NE(&from, this); const HloComputationProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const HloComputationProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.HloComputationProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.HloComputationProto) MergeFrom(*source); } } void HloComputationProto::MergeFrom(const HloComputationProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.HloComputationProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; instructions_.MergeFrom(from.instructions_); if (from.name().size() > 0) { set_name(from.name()); } if (from.has_program_shape()) { mutable_program_shape()->::xla::ProgramShapeProto::MergeFrom(from.program_shape()); } if (from.id() != 0) { set_id(from.id()); } if (from.root_id() != 0) { set_root_id(from.root_id()); } } void HloComputationProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.HloComputationProto) if (&from == this) return; Clear(); MergeFrom(from); } void HloComputationProto::CopyFrom(const HloComputationProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.HloComputationProto) if (&from == this) return; Clear(); MergeFrom(from); } bool HloComputationProto::IsInitialized() const { return true; } void HloComputationProto::Swap(HloComputationProto* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { HloComputationProto* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void HloComputationProto::UnsafeArenaSwap(HloComputationProto* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void HloComputationProto::InternalSwap(HloComputationProto* other) { using std::swap; CastToBase(&instructions_)->InternalSwap(CastToBase(&other->instructions_)); name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(program_shape_, other->program_shape_); swap(id_, other->id_); swap(root_id_, other->root_id_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HloComputationProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void HloScheduleProto_InstructionSequence::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HloScheduleProto_InstructionSequence::kInstructionIdsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HloScheduleProto_InstructionSequence::HloScheduleProto_InstructionSequence() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloScheduleProto_InstructionSequence.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.HloScheduleProto.InstructionSequence) } HloScheduleProto_InstructionSequence::HloScheduleProto_InstructionSequence(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), instruction_ids_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloScheduleProto_InstructionSequence.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.HloScheduleProto.InstructionSequence) } HloScheduleProto_InstructionSequence::HloScheduleProto_InstructionSequence(const HloScheduleProto_InstructionSequence& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), instruction_ids_(from.instruction_ids_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:xla.HloScheduleProto.InstructionSequence) } void HloScheduleProto_InstructionSequence::SharedCtor() { } HloScheduleProto_InstructionSequence::~HloScheduleProto_InstructionSequence() { // @@protoc_insertion_point(destructor:xla.HloScheduleProto.InstructionSequence) SharedDtor(); } void HloScheduleProto_InstructionSequence::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void HloScheduleProto_InstructionSequence::ArenaDtor(void* object) { HloScheduleProto_InstructionSequence* _this = reinterpret_cast< HloScheduleProto_InstructionSequence* >(object); (void)_this; } void HloScheduleProto_InstructionSequence::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void HloScheduleProto_InstructionSequence::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HloScheduleProto_InstructionSequence::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HloScheduleProto_InstructionSequence& HloScheduleProto_InstructionSequence::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloScheduleProto_InstructionSequence.base); return *internal_default_instance(); } void HloScheduleProto_InstructionSequence::Clear() { // @@protoc_insertion_point(message_clear_start:xla.HloScheduleProto.InstructionSequence) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; instruction_ids_.Clear(); _internal_metadata_.Clear(); } bool HloScheduleProto_InstructionSequence::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.HloScheduleProto.InstructionSequence) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated int64 instruction_ids = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_instruction_ids()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 1, 10u, input, this->mutable_instruction_ids()))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.HloScheduleProto.InstructionSequence) return true; failure: // @@protoc_insertion_point(parse_failure:xla.HloScheduleProto.InstructionSequence) return false; #undef DO_ } void HloScheduleProto_InstructionSequence::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.HloScheduleProto.InstructionSequence) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated int64 instruction_ids = 1; if (this->instruction_ids_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _instruction_ids_cached_byte_size_)); } for (int i = 0, n = this->instruction_ids_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->instruction_ids(i), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.HloScheduleProto.InstructionSequence) } ::google::protobuf::uint8* HloScheduleProto_InstructionSequence::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.HloScheduleProto.InstructionSequence) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated int64 instruction_ids = 1; if (this->instruction_ids_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _instruction_ids_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->instruction_ids_, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.HloScheduleProto.InstructionSequence) return target; } size_t HloScheduleProto_InstructionSequence::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.HloScheduleProto.InstructionSequence) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated int64 instruction_ids = 1; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->instruction_ids_); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _instruction_ids_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HloScheduleProto_InstructionSequence::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.HloScheduleProto.InstructionSequence) GOOGLE_DCHECK_NE(&from, this); const HloScheduleProto_InstructionSequence* source = ::google::protobuf::internal::DynamicCastToGenerated<const HloScheduleProto_InstructionSequence>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.HloScheduleProto.InstructionSequence) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.HloScheduleProto.InstructionSequence) MergeFrom(*source); } } void HloScheduleProto_InstructionSequence::MergeFrom(const HloScheduleProto_InstructionSequence& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.HloScheduleProto.InstructionSequence) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; instruction_ids_.MergeFrom(from.instruction_ids_); } void HloScheduleProto_InstructionSequence::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.HloScheduleProto.InstructionSequence) if (&from == this) return; Clear(); MergeFrom(from); } void HloScheduleProto_InstructionSequence::CopyFrom(const HloScheduleProto_InstructionSequence& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.HloScheduleProto.InstructionSequence) if (&from == this) return; Clear(); MergeFrom(from); } bool HloScheduleProto_InstructionSequence::IsInitialized() const { return true; } void HloScheduleProto_InstructionSequence::Swap(HloScheduleProto_InstructionSequence* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { HloScheduleProto_InstructionSequence* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void HloScheduleProto_InstructionSequence::UnsafeArenaSwap(HloScheduleProto_InstructionSequence* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void HloScheduleProto_InstructionSequence::InternalSwap(HloScheduleProto_InstructionSequence* other) { using std::swap; instruction_ids_.InternalSwap(&other->instruction_ids_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HloScheduleProto_InstructionSequence::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== HloScheduleProto_SequencesEntry_DoNotUse::HloScheduleProto_SequencesEntry_DoNotUse() {} HloScheduleProto_SequencesEntry_DoNotUse::HloScheduleProto_SequencesEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {} void HloScheduleProto_SequencesEntry_DoNotUse::MergeFrom(const HloScheduleProto_SequencesEntry_DoNotUse& other) { MergeFromInternal(other); } ::google::protobuf::Metadata HloScheduleProto_SequencesEntry_DoNotUse::GetMetadata() const { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[4]; } void HloScheduleProto_SequencesEntry_DoNotUse::MergeFrom( const ::google::protobuf::Message& other) { ::google::protobuf::Message::MergeFrom(other); } // =================================================================== void HloScheduleProto::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HloScheduleProto::kSequencesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HloScheduleProto::HloScheduleProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloScheduleProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.HloScheduleProto) } HloScheduleProto::HloScheduleProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), sequences_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloScheduleProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.HloScheduleProto) } HloScheduleProto::HloScheduleProto(const HloScheduleProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); sequences_.MergeFrom(from.sequences_); // @@protoc_insertion_point(copy_constructor:xla.HloScheduleProto) } void HloScheduleProto::SharedCtor() { } HloScheduleProto::~HloScheduleProto() { // @@protoc_insertion_point(destructor:xla.HloScheduleProto) SharedDtor(); } void HloScheduleProto::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void HloScheduleProto::ArenaDtor(void* object) { HloScheduleProto* _this = reinterpret_cast< HloScheduleProto* >(object); (void)_this; } void HloScheduleProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void HloScheduleProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HloScheduleProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HloScheduleProto& HloScheduleProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloScheduleProto.base); return *internal_default_instance(); } void HloScheduleProto::Clear() { // @@protoc_insertion_point(message_clear_start:xla.HloScheduleProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; sequences_.Clear(); _internal_metadata_.Clear(); } bool HloScheduleProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.HloScheduleProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // map<int64, .xla.HloScheduleProto.InstructionSequence> sequences = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { HloScheduleProto_SequencesEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField< HloScheduleProto_SequencesEntry_DoNotUse, ::google::protobuf::int64, ::xla::HloScheduleProto_InstructionSequence, ::google::protobuf::internal::WireFormatLite::TYPE_INT64, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 >, ::google::protobuf::Map< ::google::protobuf::int64, ::xla::HloScheduleProto_InstructionSequence > > parser(&sequences_); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, &parser)); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.HloScheduleProto) return true; failure: // @@protoc_insertion_point(parse_failure:xla.HloScheduleProto) return false; #undef DO_ } void HloScheduleProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.HloScheduleProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<int64, .xla.HloScheduleProto.InstructionSequence> sequences = 1; if (!this->sequences().empty()) { typedef ::google::protobuf::Map< ::google::protobuf::int64, ::xla::HloScheduleProto_InstructionSequence >::const_pointer ConstPtr; typedef ::google::protobuf::internal::SortItem< ::google::protobuf::int64, ConstPtr > SortItem; typedef ::google::protobuf::internal::CompareByFirstField<SortItem> Less; if (output->IsSerializationDeterministic() && this->sequences().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->sequences().size()]); typedef ::google::protobuf::Map< ::google::protobuf::int64, ::xla::HloScheduleProto_InstructionSequence >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::google::protobuf::int64, ::xla::HloScheduleProto_InstructionSequence >::const_iterator it = this->sequences().begin(); it != this->sequences().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<HloScheduleProto_SequencesEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(sequences_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)].second->first, items[static_cast<ptrdiff_t>(i)].second->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); if (entry->GetArena() != NULL) { entry.release(); } } } else { ::std::unique_ptr<HloScheduleProto_SequencesEntry_DoNotUse> entry; for (::google::protobuf::Map< ::google::protobuf::int64, ::xla::HloScheduleProto_InstructionSequence >::const_iterator it = this->sequences().begin(); it != this->sequences().end(); ++it) { entry.reset(sequences_.NewEntryWrapper( it->first, it->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); if (entry->GetArena() != NULL) { entry.release(); } } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.HloScheduleProto) } ::google::protobuf::uint8* HloScheduleProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.HloScheduleProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<int64, .xla.HloScheduleProto.InstructionSequence> sequences = 1; if (!this->sequences().empty()) { typedef ::google::protobuf::Map< ::google::protobuf::int64, ::xla::HloScheduleProto_InstructionSequence >::const_pointer ConstPtr; typedef ::google::protobuf::internal::SortItem< ::google::protobuf::int64, ConstPtr > SortItem; typedef ::google::protobuf::internal::CompareByFirstField<SortItem> Less; if (deterministic && this->sequences().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->sequences().size()]); typedef ::google::protobuf::Map< ::google::protobuf::int64, ::xla::HloScheduleProto_InstructionSequence >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::google::protobuf::int64, ::xla::HloScheduleProto_InstructionSequence >::const_iterator it = this->sequences().begin(); it != this->sequences().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<HloScheduleProto_SequencesEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(sequences_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)].second->first, items[static_cast<ptrdiff_t>(i)].second->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; if (entry->GetArena() != NULL) { entry.release(); } } } else { ::std::unique_ptr<HloScheduleProto_SequencesEntry_DoNotUse> entry; for (::google::protobuf::Map< ::google::protobuf::int64, ::xla::HloScheduleProto_InstructionSequence >::const_iterator it = this->sequences().begin(); it != this->sequences().end(); ++it) { entry.reset(sequences_.NewEntryWrapper( it->first, it->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; if (entry->GetArena() != NULL) { entry.release(); } } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.HloScheduleProto) return target; } size_t HloScheduleProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.HloScheduleProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // map<int64, .xla.HloScheduleProto.InstructionSequence> sequences = 1; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->sequences_size()); { ::std::unique_ptr<HloScheduleProto_SequencesEntry_DoNotUse> entry; for (::google::protobuf::Map< ::google::protobuf::int64, ::xla::HloScheduleProto_InstructionSequence >::const_iterator it = this->sequences().begin(); it != this->sequences().end(); ++it) { if (entry.get() != NULL && entry->GetArena() != NULL) { entry.release(); } entry.reset(sequences_.NewEntryWrapper(it->first, it->second)); total_size += ::google::protobuf::internal::WireFormatLite:: MessageSizeNoVirtual(*entry); } if (entry.get() != NULL && entry->GetArena() != NULL) { entry.release(); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HloScheduleProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.HloScheduleProto) GOOGLE_DCHECK_NE(&from, this); const HloScheduleProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const HloScheduleProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.HloScheduleProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.HloScheduleProto) MergeFrom(*source); } } void HloScheduleProto::MergeFrom(const HloScheduleProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.HloScheduleProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; sequences_.MergeFrom(from.sequences_); } void HloScheduleProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.HloScheduleProto) if (&from == this) return; Clear(); MergeFrom(from); } void HloScheduleProto::CopyFrom(const HloScheduleProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.HloScheduleProto) if (&from == this) return; Clear(); MergeFrom(from); } bool HloScheduleProto::IsInitialized() const { return true; } void HloScheduleProto::Swap(HloScheduleProto* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { HloScheduleProto* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void HloScheduleProto::UnsafeArenaSwap(HloScheduleProto* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void HloScheduleProto::InternalSwap(HloScheduleProto* other) { using std::swap; sequences_.Swap(&other->sequences_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HloScheduleProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void HloInputOutputAliasProto_AliasEntryProto::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HloInputOutputAliasProto_AliasEntryProto::kOutputShapeIndexFieldNumber; const int HloInputOutputAliasProto_AliasEntryProto::kParameterNumberFieldNumber; const int HloInputOutputAliasProto_AliasEntryProto::kParameterShapeIndexFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HloInputOutputAliasProto_AliasEntryProto::HloInputOutputAliasProto_AliasEntryProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInputOutputAliasProto_AliasEntryProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.HloInputOutputAliasProto.AliasEntryProto) } HloInputOutputAliasProto_AliasEntryProto::HloInputOutputAliasProto_AliasEntryProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), output_shape_index_(arena), parameter_shape_index_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInputOutputAliasProto_AliasEntryProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.HloInputOutputAliasProto.AliasEntryProto) } HloInputOutputAliasProto_AliasEntryProto::HloInputOutputAliasProto_AliasEntryProto(const HloInputOutputAliasProto_AliasEntryProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), output_shape_index_(from.output_shape_index_), parameter_shape_index_(from.parameter_shape_index_) { _internal_metadata_.MergeFrom(from._internal_metadata_); parameter_number_ = from.parameter_number_; // @@protoc_insertion_point(copy_constructor:xla.HloInputOutputAliasProto.AliasEntryProto) } void HloInputOutputAliasProto_AliasEntryProto::SharedCtor() { parameter_number_ = GOOGLE_LONGLONG(0); } HloInputOutputAliasProto_AliasEntryProto::~HloInputOutputAliasProto_AliasEntryProto() { // @@protoc_insertion_point(destructor:xla.HloInputOutputAliasProto.AliasEntryProto) SharedDtor(); } void HloInputOutputAliasProto_AliasEntryProto::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void HloInputOutputAliasProto_AliasEntryProto::ArenaDtor(void* object) { HloInputOutputAliasProto_AliasEntryProto* _this = reinterpret_cast< HloInputOutputAliasProto_AliasEntryProto* >(object); (void)_this; } void HloInputOutputAliasProto_AliasEntryProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void HloInputOutputAliasProto_AliasEntryProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HloInputOutputAliasProto_AliasEntryProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HloInputOutputAliasProto_AliasEntryProto& HloInputOutputAliasProto_AliasEntryProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInputOutputAliasProto_AliasEntryProto.base); return *internal_default_instance(); } void HloInputOutputAliasProto_AliasEntryProto::Clear() { // @@protoc_insertion_point(message_clear_start:xla.HloInputOutputAliasProto.AliasEntryProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; output_shape_index_.Clear(); parameter_shape_index_.Clear(); parameter_number_ = GOOGLE_LONGLONG(0); _internal_metadata_.Clear(); } bool HloInputOutputAliasProto_AliasEntryProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.HloInputOutputAliasProto.AliasEntryProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated int64 output_shape_index = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_output_shape_index()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 1, 10u, input, this->mutable_output_shape_index()))); } else { goto handle_unusual; } break; } // int64 parameter_number = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &parameter_number_))); } else { goto handle_unusual; } break; } // repeated int64 parameter_shape_index = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_parameter_shape_index()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 1, 26u, input, this->mutable_parameter_shape_index()))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.HloInputOutputAliasProto.AliasEntryProto) return true; failure: // @@protoc_insertion_point(parse_failure:xla.HloInputOutputAliasProto.AliasEntryProto) return false; #undef DO_ } void HloInputOutputAliasProto_AliasEntryProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.HloInputOutputAliasProto.AliasEntryProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated int64 output_shape_index = 1; if (this->output_shape_index_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _output_shape_index_cached_byte_size_)); } for (int i = 0, n = this->output_shape_index_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->output_shape_index(i), output); } // int64 parameter_number = 2; if (this->parameter_number() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->parameter_number(), output); } // repeated int64 parameter_shape_index = 3; if (this->parameter_shape_index_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(3, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _parameter_shape_index_cached_byte_size_)); } for (int i = 0, n = this->parameter_shape_index_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->parameter_shape_index(i), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.HloInputOutputAliasProto.AliasEntryProto) } ::google::protobuf::uint8* HloInputOutputAliasProto_AliasEntryProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.HloInputOutputAliasProto.AliasEntryProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated int64 output_shape_index = 1; if (this->output_shape_index_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _output_shape_index_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->output_shape_index_, target); } // int64 parameter_number = 2; if (this->parameter_number() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(2, this->parameter_number(), target); } // repeated int64 parameter_shape_index = 3; if (this->parameter_shape_index_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 3, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _parameter_shape_index_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->parameter_shape_index_, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.HloInputOutputAliasProto.AliasEntryProto) return target; } size_t HloInputOutputAliasProto_AliasEntryProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.HloInputOutputAliasProto.AliasEntryProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated int64 output_shape_index = 1; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->output_shape_index_); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _output_shape_index_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated int64 parameter_shape_index = 3; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->parameter_shape_index_); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _parameter_shape_index_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // int64 parameter_number = 2; if (this->parameter_number() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->parameter_number()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HloInputOutputAliasProto_AliasEntryProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.HloInputOutputAliasProto.AliasEntryProto) GOOGLE_DCHECK_NE(&from, this); const HloInputOutputAliasProto_AliasEntryProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const HloInputOutputAliasProto_AliasEntryProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.HloInputOutputAliasProto.AliasEntryProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.HloInputOutputAliasProto.AliasEntryProto) MergeFrom(*source); } } void HloInputOutputAliasProto_AliasEntryProto::MergeFrom(const HloInputOutputAliasProto_AliasEntryProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.HloInputOutputAliasProto.AliasEntryProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; output_shape_index_.MergeFrom(from.output_shape_index_); parameter_shape_index_.MergeFrom(from.parameter_shape_index_); if (from.parameter_number() != 0) { set_parameter_number(from.parameter_number()); } } void HloInputOutputAliasProto_AliasEntryProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.HloInputOutputAliasProto.AliasEntryProto) if (&from == this) return; Clear(); MergeFrom(from); } void HloInputOutputAliasProto_AliasEntryProto::CopyFrom(const HloInputOutputAliasProto_AliasEntryProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.HloInputOutputAliasProto.AliasEntryProto) if (&from == this) return; Clear(); MergeFrom(from); } bool HloInputOutputAliasProto_AliasEntryProto::IsInitialized() const { return true; } void HloInputOutputAliasProto_AliasEntryProto::Swap(HloInputOutputAliasProto_AliasEntryProto* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { HloInputOutputAliasProto_AliasEntryProto* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void HloInputOutputAliasProto_AliasEntryProto::UnsafeArenaSwap(HloInputOutputAliasProto_AliasEntryProto* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void HloInputOutputAliasProto_AliasEntryProto::InternalSwap(HloInputOutputAliasProto_AliasEntryProto* other) { using std::swap; output_shape_index_.InternalSwap(&other->output_shape_index_); parameter_shape_index_.InternalSwap(&other->parameter_shape_index_); swap(parameter_number_, other->parameter_number_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HloInputOutputAliasProto_AliasEntryProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void HloInputOutputAliasProto::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HloInputOutputAliasProto::kEntriesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HloInputOutputAliasProto::HloInputOutputAliasProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInputOutputAliasProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.HloInputOutputAliasProto) } HloInputOutputAliasProto::HloInputOutputAliasProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), entries_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInputOutputAliasProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.HloInputOutputAliasProto) } HloInputOutputAliasProto::HloInputOutputAliasProto(const HloInputOutputAliasProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), entries_(from.entries_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:xla.HloInputOutputAliasProto) } void HloInputOutputAliasProto::SharedCtor() { } HloInputOutputAliasProto::~HloInputOutputAliasProto() { // @@protoc_insertion_point(destructor:xla.HloInputOutputAliasProto) SharedDtor(); } void HloInputOutputAliasProto::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void HloInputOutputAliasProto::ArenaDtor(void* object) { HloInputOutputAliasProto* _this = reinterpret_cast< HloInputOutputAliasProto* >(object); (void)_this; } void HloInputOutputAliasProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void HloInputOutputAliasProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HloInputOutputAliasProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HloInputOutputAliasProto& HloInputOutputAliasProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloInputOutputAliasProto.base); return *internal_default_instance(); } void HloInputOutputAliasProto::Clear() { // @@protoc_insertion_point(message_clear_start:xla.HloInputOutputAliasProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; entries_.Clear(); _internal_metadata_.Clear(); } bool HloInputOutputAliasProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.HloInputOutputAliasProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .xla.HloInputOutputAliasProto.AliasEntryProto entries = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_entries())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.HloInputOutputAliasProto) return true; failure: // @@protoc_insertion_point(parse_failure:xla.HloInputOutputAliasProto) return false; #undef DO_ } void HloInputOutputAliasProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.HloInputOutputAliasProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .xla.HloInputOutputAliasProto.AliasEntryProto entries = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->entries_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->entries(static_cast<int>(i)), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.HloInputOutputAliasProto) } ::google::protobuf::uint8* HloInputOutputAliasProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.HloInputOutputAliasProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .xla.HloInputOutputAliasProto.AliasEntryProto entries = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->entries_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, this->entries(static_cast<int>(i)), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.HloInputOutputAliasProto) return target; } size_t HloInputOutputAliasProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.HloInputOutputAliasProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated .xla.HloInputOutputAliasProto.AliasEntryProto entries = 1; { unsigned int count = static_cast<unsigned int>(this->entries_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->entries(static_cast<int>(i))); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HloInputOutputAliasProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.HloInputOutputAliasProto) GOOGLE_DCHECK_NE(&from, this); const HloInputOutputAliasProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const HloInputOutputAliasProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.HloInputOutputAliasProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.HloInputOutputAliasProto) MergeFrom(*source); } } void HloInputOutputAliasProto::MergeFrom(const HloInputOutputAliasProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.HloInputOutputAliasProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; entries_.MergeFrom(from.entries_); } void HloInputOutputAliasProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.HloInputOutputAliasProto) if (&from == this) return; Clear(); MergeFrom(from); } void HloInputOutputAliasProto::CopyFrom(const HloInputOutputAliasProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.HloInputOutputAliasProto) if (&from == this) return; Clear(); MergeFrom(from); } bool HloInputOutputAliasProto::IsInitialized() const { return true; } void HloInputOutputAliasProto::Swap(HloInputOutputAliasProto* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { HloInputOutputAliasProto* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void HloInputOutputAliasProto::UnsafeArenaSwap(HloInputOutputAliasProto* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void HloInputOutputAliasProto::InternalSwap(HloInputOutputAliasProto* other) { using std::swap; CastToBase(&entries_)->InternalSwap(CastToBase(&other->entries_)); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HloInputOutputAliasProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void DynamicParameterBindingProto_Binding::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int DynamicParameterBindingProto_Binding::kDynamicParamNumFieldNumber; const int DynamicParameterBindingProto_Binding::kDynamicParamIndexFieldNumber; const int DynamicParameterBindingProto_Binding::kTargetParamNumFieldNumber; const int DynamicParameterBindingProto_Binding::kTargetParamIndexFieldNumber; const int DynamicParameterBindingProto_Binding::kTargetParamDimNumFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 DynamicParameterBindingProto_Binding::DynamicParameterBindingProto_Binding() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_DynamicParameterBindingProto_Binding.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.DynamicParameterBindingProto.Binding) } DynamicParameterBindingProto_Binding::DynamicParameterBindingProto_Binding(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), dynamic_param_index_(arena), target_param_index_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_DynamicParameterBindingProto_Binding.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.DynamicParameterBindingProto.Binding) } DynamicParameterBindingProto_Binding::DynamicParameterBindingProto_Binding(const DynamicParameterBindingProto_Binding& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), dynamic_param_index_(from.dynamic_param_index_), target_param_index_(from.target_param_index_) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&dynamic_param_num_, &from.dynamic_param_num_, static_cast<size_t>(reinterpret_cast<char*>(&target_param_dim_num_) - reinterpret_cast<char*>(&dynamic_param_num_)) + sizeof(target_param_dim_num_)); // @@protoc_insertion_point(copy_constructor:xla.DynamicParameterBindingProto.Binding) } void DynamicParameterBindingProto_Binding::SharedCtor() { ::memset(&dynamic_param_num_, 0, static_cast<size_t>( reinterpret_cast<char*>(&target_param_dim_num_) - reinterpret_cast<char*>(&dynamic_param_num_)) + sizeof(target_param_dim_num_)); } DynamicParameterBindingProto_Binding::~DynamicParameterBindingProto_Binding() { // @@protoc_insertion_point(destructor:xla.DynamicParameterBindingProto.Binding) SharedDtor(); } void DynamicParameterBindingProto_Binding::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void DynamicParameterBindingProto_Binding::ArenaDtor(void* object) { DynamicParameterBindingProto_Binding* _this = reinterpret_cast< DynamicParameterBindingProto_Binding* >(object); (void)_this; } void DynamicParameterBindingProto_Binding::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void DynamicParameterBindingProto_Binding::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* DynamicParameterBindingProto_Binding::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const DynamicParameterBindingProto_Binding& DynamicParameterBindingProto_Binding::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_DynamicParameterBindingProto_Binding.base); return *internal_default_instance(); } void DynamicParameterBindingProto_Binding::Clear() { // @@protoc_insertion_point(message_clear_start:xla.DynamicParameterBindingProto.Binding) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; dynamic_param_index_.Clear(); target_param_index_.Clear(); ::memset(&dynamic_param_num_, 0, static_cast<size_t>( reinterpret_cast<char*>(&target_param_dim_num_) - reinterpret_cast<char*>(&dynamic_param_num_)) + sizeof(target_param_dim_num_)); _internal_metadata_.Clear(); } bool DynamicParameterBindingProto_Binding::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.DynamicParameterBindingProto.Binding) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int64 dynamic_param_num = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &dynamic_param_num_))); } else { goto handle_unusual; } break; } // repeated int64 dynamic_param_index = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_dynamic_param_index()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 1, 18u, input, this->mutable_dynamic_param_index()))); } else { goto handle_unusual; } break; } // int64 target_param_num = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &target_param_num_))); } else { goto handle_unusual; } break; } // repeated int64 target_param_index = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_target_param_index()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 1, 34u, input, this->mutable_target_param_index()))); } else { goto handle_unusual; } break; } // int64 target_param_dim_num = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &target_param_dim_num_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.DynamicParameterBindingProto.Binding) return true; failure: // @@protoc_insertion_point(parse_failure:xla.DynamicParameterBindingProto.Binding) return false; #undef DO_ } void DynamicParameterBindingProto_Binding::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.DynamicParameterBindingProto.Binding) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 dynamic_param_num = 1; if (this->dynamic_param_num() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->dynamic_param_num(), output); } // repeated int64 dynamic_param_index = 2; if (this->dynamic_param_index_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _dynamic_param_index_cached_byte_size_)); } for (int i = 0, n = this->dynamic_param_index_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->dynamic_param_index(i), output); } // int64 target_param_num = 3; if (this->target_param_num() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(3, this->target_param_num(), output); } // repeated int64 target_param_index = 4; if (this->target_param_index_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(4, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _target_param_index_cached_byte_size_)); } for (int i = 0, n = this->target_param_index_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->target_param_index(i), output); } // int64 target_param_dim_num = 5; if (this->target_param_dim_num() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(5, this->target_param_dim_num(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.DynamicParameterBindingProto.Binding) } ::google::protobuf::uint8* DynamicParameterBindingProto_Binding::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.DynamicParameterBindingProto.Binding) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 dynamic_param_num = 1; if (this->dynamic_param_num() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->dynamic_param_num(), target); } // repeated int64 dynamic_param_index = 2; if (this->dynamic_param_index_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _dynamic_param_index_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->dynamic_param_index_, target); } // int64 target_param_num = 3; if (this->target_param_num() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(3, this->target_param_num(), target); } // repeated int64 target_param_index = 4; if (this->target_param_index_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 4, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _target_param_index_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->target_param_index_, target); } // int64 target_param_dim_num = 5; if (this->target_param_dim_num() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(5, this->target_param_dim_num(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.DynamicParameterBindingProto.Binding) return target; } size_t DynamicParameterBindingProto_Binding::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.DynamicParameterBindingProto.Binding) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated int64 dynamic_param_index = 2; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->dynamic_param_index_); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _dynamic_param_index_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated int64 target_param_index = 4; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->target_param_index_); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _target_param_index_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // int64 dynamic_param_num = 1; if (this->dynamic_param_num() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->dynamic_param_num()); } // int64 target_param_num = 3; if (this->target_param_num() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->target_param_num()); } // int64 target_param_dim_num = 5; if (this->target_param_dim_num() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->target_param_dim_num()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void DynamicParameterBindingProto_Binding::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.DynamicParameterBindingProto.Binding) GOOGLE_DCHECK_NE(&from, this); const DynamicParameterBindingProto_Binding* source = ::google::protobuf::internal::DynamicCastToGenerated<const DynamicParameterBindingProto_Binding>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.DynamicParameterBindingProto.Binding) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.DynamicParameterBindingProto.Binding) MergeFrom(*source); } } void DynamicParameterBindingProto_Binding::MergeFrom(const DynamicParameterBindingProto_Binding& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.DynamicParameterBindingProto.Binding) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; dynamic_param_index_.MergeFrom(from.dynamic_param_index_); target_param_index_.MergeFrom(from.target_param_index_); if (from.dynamic_param_num() != 0) { set_dynamic_param_num(from.dynamic_param_num()); } if (from.target_param_num() != 0) { set_target_param_num(from.target_param_num()); } if (from.target_param_dim_num() != 0) { set_target_param_dim_num(from.target_param_dim_num()); } } void DynamicParameterBindingProto_Binding::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.DynamicParameterBindingProto.Binding) if (&from == this) return; Clear(); MergeFrom(from); } void DynamicParameterBindingProto_Binding::CopyFrom(const DynamicParameterBindingProto_Binding& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.DynamicParameterBindingProto.Binding) if (&from == this) return; Clear(); MergeFrom(from); } bool DynamicParameterBindingProto_Binding::IsInitialized() const { return true; } void DynamicParameterBindingProto_Binding::Swap(DynamicParameterBindingProto_Binding* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { DynamicParameterBindingProto_Binding* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void DynamicParameterBindingProto_Binding::UnsafeArenaSwap(DynamicParameterBindingProto_Binding* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void DynamicParameterBindingProto_Binding::InternalSwap(DynamicParameterBindingProto_Binding* other) { using std::swap; dynamic_param_index_.InternalSwap(&other->dynamic_param_index_); target_param_index_.InternalSwap(&other->target_param_index_); swap(dynamic_param_num_, other->dynamic_param_num_); swap(target_param_num_, other->target_param_num_); swap(target_param_dim_num_, other->target_param_dim_num_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata DynamicParameterBindingProto_Binding::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void DynamicParameterBindingProto::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int DynamicParameterBindingProto::kEntriesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 DynamicParameterBindingProto::DynamicParameterBindingProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_DynamicParameterBindingProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.DynamicParameterBindingProto) } DynamicParameterBindingProto::DynamicParameterBindingProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), entries_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_DynamicParameterBindingProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.DynamicParameterBindingProto) } DynamicParameterBindingProto::DynamicParameterBindingProto(const DynamicParameterBindingProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), entries_(from.entries_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:xla.DynamicParameterBindingProto) } void DynamicParameterBindingProto::SharedCtor() { } DynamicParameterBindingProto::~DynamicParameterBindingProto() { // @@protoc_insertion_point(destructor:xla.DynamicParameterBindingProto) SharedDtor(); } void DynamicParameterBindingProto::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void DynamicParameterBindingProto::ArenaDtor(void* object) { DynamicParameterBindingProto* _this = reinterpret_cast< DynamicParameterBindingProto* >(object); (void)_this; } void DynamicParameterBindingProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void DynamicParameterBindingProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* DynamicParameterBindingProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const DynamicParameterBindingProto& DynamicParameterBindingProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_DynamicParameterBindingProto.base); return *internal_default_instance(); } void DynamicParameterBindingProto::Clear() { // @@protoc_insertion_point(message_clear_start:xla.DynamicParameterBindingProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; entries_.Clear(); _internal_metadata_.Clear(); } bool DynamicParameterBindingProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.DynamicParameterBindingProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .xla.DynamicParameterBindingProto.Binding entries = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_entries())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.DynamicParameterBindingProto) return true; failure: // @@protoc_insertion_point(parse_failure:xla.DynamicParameterBindingProto) return false; #undef DO_ } void DynamicParameterBindingProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.DynamicParameterBindingProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .xla.DynamicParameterBindingProto.Binding entries = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->entries_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->entries(static_cast<int>(i)), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.DynamicParameterBindingProto) } ::google::protobuf::uint8* DynamicParameterBindingProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.DynamicParameterBindingProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .xla.DynamicParameterBindingProto.Binding entries = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->entries_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, this->entries(static_cast<int>(i)), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.DynamicParameterBindingProto) return target; } size_t DynamicParameterBindingProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.DynamicParameterBindingProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated .xla.DynamicParameterBindingProto.Binding entries = 1; { unsigned int count = static_cast<unsigned int>(this->entries_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->entries(static_cast<int>(i))); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void DynamicParameterBindingProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.DynamicParameterBindingProto) GOOGLE_DCHECK_NE(&from, this); const DynamicParameterBindingProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const DynamicParameterBindingProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.DynamicParameterBindingProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.DynamicParameterBindingProto) MergeFrom(*source); } } void DynamicParameterBindingProto::MergeFrom(const DynamicParameterBindingProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.DynamicParameterBindingProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; entries_.MergeFrom(from.entries_); } void DynamicParameterBindingProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.DynamicParameterBindingProto) if (&from == this) return; Clear(); MergeFrom(from); } void DynamicParameterBindingProto::CopyFrom(const DynamicParameterBindingProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.DynamicParameterBindingProto) if (&from == this) return; Clear(); MergeFrom(from); } bool DynamicParameterBindingProto::IsInitialized() const { return true; } void DynamicParameterBindingProto::Swap(DynamicParameterBindingProto* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { DynamicParameterBindingProto* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void DynamicParameterBindingProto::UnsafeArenaSwap(DynamicParameterBindingProto* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void DynamicParameterBindingProto::InternalSwap(DynamicParameterBindingProto* other) { using std::swap; CastToBase(&entries_)->InternalSwap(CastToBase(&other->entries_)); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata DynamicParameterBindingProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void HloModuleProto::InitAsDefaultInstance() { ::xla::_HloModuleProto_default_instance_._instance.get_mutable()->host_program_shape_ = const_cast< ::xla::ProgramShapeProto*>( ::xla::ProgramShapeProto::internal_default_instance()); ::xla::_HloModuleProto_default_instance_._instance.get_mutable()->schedule_ = const_cast< ::xla::HloScheduleProto*>( ::xla::HloScheduleProto::internal_default_instance()); ::xla::_HloModuleProto_default_instance_._instance.get_mutable()->input_output_alias_ = const_cast< ::xla::HloInputOutputAliasProto*>( ::xla::HloInputOutputAliasProto::internal_default_instance()); ::xla::_HloModuleProto_default_instance_._instance.get_mutable()->dynamic_parameter_binding_ = const_cast< ::xla::DynamicParameterBindingProto*>( ::xla::DynamicParameterBindingProto::internal_default_instance()); } void HloModuleProto::unsafe_arena_set_allocated_host_program_shape( ::xla::ProgramShapeProto* host_program_shape) { if (GetArenaNoVirtual() == NULL) { delete host_program_shape_; } host_program_shape_ = host_program_shape; if (host_program_shape) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloModuleProto.host_program_shape) } void HloModuleProto::clear_host_program_shape() { if (GetArenaNoVirtual() == NULL && host_program_shape_ != NULL) { delete host_program_shape_; } host_program_shape_ = NULL; } void HloModuleProto::unsafe_arena_set_allocated_schedule( ::xla::HloScheduleProto* schedule) { if (GetArenaNoVirtual() == NULL) { delete schedule_; } schedule_ = schedule; if (schedule) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloModuleProto.schedule) } void HloModuleProto::unsafe_arena_set_allocated_input_output_alias( ::xla::HloInputOutputAliasProto* input_output_alias) { if (GetArenaNoVirtual() == NULL) { delete input_output_alias_; } input_output_alias_ = input_output_alias; if (input_output_alias) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloModuleProto.input_output_alias) } void HloModuleProto::unsafe_arena_set_allocated_dynamic_parameter_binding( ::xla::DynamicParameterBindingProto* dynamic_parameter_binding) { if (GetArenaNoVirtual() == NULL) { delete dynamic_parameter_binding_; } dynamic_parameter_binding_ = dynamic_parameter_binding; if (dynamic_parameter_binding) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloModuleProto.dynamic_parameter_binding) } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HloModuleProto::kNameFieldNumber; const int HloModuleProto::kEntryComputationNameFieldNumber; const int HloModuleProto::kEntryComputationIdFieldNumber; const int HloModuleProto::kComputationsFieldNumber; const int HloModuleProto::kHostProgramShapeFieldNumber; const int HloModuleProto::kIdFieldNumber; const int HloModuleProto::kScheduleFieldNumber; const int HloModuleProto::kInputOutputAliasFieldNumber; const int HloModuleProto::kDynamicParameterBindingFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HloModuleProto::HloModuleProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloModuleProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.HloModuleProto) } HloModuleProto::HloModuleProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), computations_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloModuleProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.HloModuleProto) } HloModuleProto::HloModuleProto(const HloModuleProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), computations_(from.computations_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(), GetArenaNoVirtual()); } entry_computation_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.entry_computation_name().size() > 0) { entry_computation_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.entry_computation_name(), GetArenaNoVirtual()); } if (from.has_host_program_shape()) { host_program_shape_ = new ::xla::ProgramShapeProto(*from.host_program_shape_); } else { host_program_shape_ = NULL; } if (from.has_schedule()) { schedule_ = new ::xla::HloScheduleProto(*from.schedule_); } else { schedule_ = NULL; } if (from.has_input_output_alias()) { input_output_alias_ = new ::xla::HloInputOutputAliasProto(*from.input_output_alias_); } else { input_output_alias_ = NULL; } if (from.has_dynamic_parameter_binding()) { dynamic_parameter_binding_ = new ::xla::DynamicParameterBindingProto(*from.dynamic_parameter_binding_); } else { dynamic_parameter_binding_ = NULL; } ::memcpy(&id_, &from.id_, static_cast<size_t>(reinterpret_cast<char*>(&entry_computation_id_) - reinterpret_cast<char*>(&id_)) + sizeof(entry_computation_id_)); // @@protoc_insertion_point(copy_constructor:xla.HloModuleProto) } void HloModuleProto::SharedCtor() { name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); entry_computation_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&host_program_shape_, 0, static_cast<size_t>( reinterpret_cast<char*>(&entry_computation_id_) - reinterpret_cast<char*>(&host_program_shape_)) + sizeof(entry_computation_id_)); } HloModuleProto::~HloModuleProto() { // @@protoc_insertion_point(destructor:xla.HloModuleProto) SharedDtor(); } void HloModuleProto::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); entry_computation_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete host_program_shape_; if (this != internal_default_instance()) delete schedule_; if (this != internal_default_instance()) delete input_output_alias_; if (this != internal_default_instance()) delete dynamic_parameter_binding_; } void HloModuleProto::ArenaDtor(void* object) { HloModuleProto* _this = reinterpret_cast< HloModuleProto* >(object); (void)_this; } void HloModuleProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void HloModuleProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HloModuleProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HloModuleProto& HloModuleProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloModuleProto.base); return *internal_default_instance(); } void HloModuleProto::Clear() { // @@protoc_insertion_point(message_clear_start:xla.HloModuleProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; computations_.Clear(); name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); entry_computation_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); if (GetArenaNoVirtual() == NULL && host_program_shape_ != NULL) { delete host_program_shape_; } host_program_shape_ = NULL; if (GetArenaNoVirtual() == NULL && schedule_ != NULL) { delete schedule_; } schedule_ = NULL; if (GetArenaNoVirtual() == NULL && input_output_alias_ != NULL) { delete input_output_alias_; } input_output_alias_ = NULL; if (GetArenaNoVirtual() == NULL && dynamic_parameter_binding_ != NULL) { delete dynamic_parameter_binding_; } dynamic_parameter_binding_ = NULL; ::memset(&id_, 0, static_cast<size_t>( reinterpret_cast<char*>(&entry_computation_id_) - reinterpret_cast<char*>(&id_)) + sizeof(entry_computation_id_)); _internal_metadata_.Clear(); } bool HloModuleProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.HloModuleProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string name = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HloModuleProto.name")); } else { goto handle_unusual; } break; } // string entry_computation_name = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_entry_computation_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->entry_computation_name().data(), static_cast<int>(this->entry_computation_name().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HloModuleProto.entry_computation_name")); } else { goto handle_unusual; } break; } // repeated .xla.HloComputationProto computations = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_computations())); } else { goto handle_unusual; } break; } // .xla.ProgramShapeProto host_program_shape = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_host_program_shape())); } else { goto handle_unusual; } break; } // int64 id = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &id_))); } else { goto handle_unusual; } break; } // int64 entry_computation_id = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &entry_computation_id_))); } else { goto handle_unusual; } break; } // .xla.HloScheduleProto schedule = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_schedule())); } else { goto handle_unusual; } break; } // .xla.HloInputOutputAliasProto input_output_alias = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_input_output_alias())); } else { goto handle_unusual; } break; } // .xla.DynamicParameterBindingProto dynamic_parameter_binding = 9; case 9: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_dynamic_parameter_binding())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.HloModuleProto) return true; failure: // @@protoc_insertion_point(parse_failure:xla.HloModuleProto) return false; #undef DO_ } void HloModuleProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.HloModuleProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloModuleProto.name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // string entry_computation_name = 2; if (this->entry_computation_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->entry_computation_name().data(), static_cast<int>(this->entry_computation_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloModuleProto.entry_computation_name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->entry_computation_name(), output); } // repeated .xla.HloComputationProto computations = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->computations_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->computations(static_cast<int>(i)), output); } // .xla.ProgramShapeProto host_program_shape = 4; if (this->has_host_program_shape()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->_internal_host_program_shape(), output); } // int64 id = 5; if (this->id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(5, this->id(), output); } // int64 entry_computation_id = 6; if (this->entry_computation_id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(6, this->entry_computation_id(), output); } // .xla.HloScheduleProto schedule = 7; if (this->has_schedule()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 7, this->_internal_schedule(), output); } // .xla.HloInputOutputAliasProto input_output_alias = 8; if (this->has_input_output_alias()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 8, this->_internal_input_output_alias(), output); } // .xla.DynamicParameterBindingProto dynamic_parameter_binding = 9; if (this->has_dynamic_parameter_binding()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 9, this->_internal_dynamic_parameter_binding(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.HloModuleProto) } ::google::protobuf::uint8* HloModuleProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.HloModuleProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloModuleProto.name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // string entry_computation_name = 2; if (this->entry_computation_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->entry_computation_name().data(), static_cast<int>(this->entry_computation_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloModuleProto.entry_computation_name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->entry_computation_name(), target); } // repeated .xla.HloComputationProto computations = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->computations_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, this->computations(static_cast<int>(i)), deterministic, target); } // .xla.ProgramShapeProto host_program_shape = 4; if (this->has_host_program_shape()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 4, this->_internal_host_program_shape(), deterministic, target); } // int64 id = 5; if (this->id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(5, this->id(), target); } // int64 entry_computation_id = 6; if (this->entry_computation_id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(6, this->entry_computation_id(), target); } // .xla.HloScheduleProto schedule = 7; if (this->has_schedule()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 7, this->_internal_schedule(), deterministic, target); } // .xla.HloInputOutputAliasProto input_output_alias = 8; if (this->has_input_output_alias()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 8, this->_internal_input_output_alias(), deterministic, target); } // .xla.DynamicParameterBindingProto dynamic_parameter_binding = 9; if (this->has_dynamic_parameter_binding()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 9, this->_internal_dynamic_parameter_binding(), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.HloModuleProto) return target; } size_t HloModuleProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.HloModuleProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated .xla.HloComputationProto computations = 3; { unsigned int count = static_cast<unsigned int>(this->computations_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->computations(static_cast<int>(i))); } } // string name = 1; if (this->name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->name()); } // string entry_computation_name = 2; if (this->entry_computation_name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->entry_computation_name()); } // .xla.ProgramShapeProto host_program_shape = 4; if (this->has_host_program_shape()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *host_program_shape_); } // .xla.HloScheduleProto schedule = 7; if (this->has_schedule()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *schedule_); } // .xla.HloInputOutputAliasProto input_output_alias = 8; if (this->has_input_output_alias()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *input_output_alias_); } // .xla.DynamicParameterBindingProto dynamic_parameter_binding = 9; if (this->has_dynamic_parameter_binding()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *dynamic_parameter_binding_); } // int64 id = 5; if (this->id() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->id()); } // int64 entry_computation_id = 6; if (this->entry_computation_id() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->entry_computation_id()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HloModuleProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.HloModuleProto) GOOGLE_DCHECK_NE(&from, this); const HloModuleProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const HloModuleProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.HloModuleProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.HloModuleProto) MergeFrom(*source); } } void HloModuleProto::MergeFrom(const HloModuleProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.HloModuleProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; computations_.MergeFrom(from.computations_); if (from.name().size() > 0) { set_name(from.name()); } if (from.entry_computation_name().size() > 0) { set_entry_computation_name(from.entry_computation_name()); } if (from.has_host_program_shape()) { mutable_host_program_shape()->::xla::ProgramShapeProto::MergeFrom(from.host_program_shape()); } if (from.has_schedule()) { mutable_schedule()->::xla::HloScheduleProto::MergeFrom(from.schedule()); } if (from.has_input_output_alias()) { mutable_input_output_alias()->::xla::HloInputOutputAliasProto::MergeFrom(from.input_output_alias()); } if (from.has_dynamic_parameter_binding()) { mutable_dynamic_parameter_binding()->::xla::DynamicParameterBindingProto::MergeFrom(from.dynamic_parameter_binding()); } if (from.id() != 0) { set_id(from.id()); } if (from.entry_computation_id() != 0) { set_entry_computation_id(from.entry_computation_id()); } } void HloModuleProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.HloModuleProto) if (&from == this) return; Clear(); MergeFrom(from); } void HloModuleProto::CopyFrom(const HloModuleProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.HloModuleProto) if (&from == this) return; Clear(); MergeFrom(from); } bool HloModuleProto::IsInitialized() const { return true; } void HloModuleProto::Swap(HloModuleProto* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { HloModuleProto* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void HloModuleProto::UnsafeArenaSwap(HloModuleProto* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void HloModuleProto::InternalSwap(HloModuleProto* other) { using std::swap; CastToBase(&computations_)->InternalSwap(CastToBase(&other->computations_)); name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); entry_computation_name_.Swap(&other->entry_computation_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(host_program_shape_, other->host_program_shape_); swap(schedule_, other->schedule_); swap(input_output_alias_, other->input_output_alias_); swap(dynamic_parameter_binding_, other->dynamic_parameter_binding_); swap(id_, other->id_); swap(entry_computation_id_, other->entry_computation_id_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HloModuleProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void LogicalBufferProto_Location::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int LogicalBufferProto_Location::kComputationNameFieldNumber; const int LogicalBufferProto_Location::kInstructionNameFieldNumber; const int LogicalBufferProto_Location::kShapeIndexFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 LogicalBufferProto_Location::LogicalBufferProto_Location() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_LogicalBufferProto_Location.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.LogicalBufferProto.Location) } LogicalBufferProto_Location::LogicalBufferProto_Location(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), shape_index_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_LogicalBufferProto_Location.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.LogicalBufferProto.Location) } LogicalBufferProto_Location::LogicalBufferProto_Location(const LogicalBufferProto_Location& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), shape_index_(from.shape_index_) { _internal_metadata_.MergeFrom(from._internal_metadata_); computation_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.computation_name().size() > 0) { computation_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.computation_name(), GetArenaNoVirtual()); } instruction_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.instruction_name().size() > 0) { instruction_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.instruction_name(), GetArenaNoVirtual()); } // @@protoc_insertion_point(copy_constructor:xla.LogicalBufferProto.Location) } void LogicalBufferProto_Location::SharedCtor() { computation_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); instruction_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } LogicalBufferProto_Location::~LogicalBufferProto_Location() { // @@protoc_insertion_point(destructor:xla.LogicalBufferProto.Location) SharedDtor(); } void LogicalBufferProto_Location::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); computation_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); instruction_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void LogicalBufferProto_Location::ArenaDtor(void* object) { LogicalBufferProto_Location* _this = reinterpret_cast< LogicalBufferProto_Location* >(object); (void)_this; } void LogicalBufferProto_Location::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void LogicalBufferProto_Location::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* LogicalBufferProto_Location::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const LogicalBufferProto_Location& LogicalBufferProto_Location::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_LogicalBufferProto_Location.base); return *internal_default_instance(); } void LogicalBufferProto_Location::Clear() { // @@protoc_insertion_point(message_clear_start:xla.LogicalBufferProto.Location) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; shape_index_.Clear(); computation_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); instruction_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _internal_metadata_.Clear(); } bool LogicalBufferProto_Location::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.LogicalBufferProto.Location) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string computation_name = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_computation_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->computation_name().data(), static_cast<int>(this->computation_name().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.LogicalBufferProto.Location.computation_name")); } else { goto handle_unusual; } break; } // string instruction_name = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_instruction_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->instruction_name().data(), static_cast<int>(this->instruction_name().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.LogicalBufferProto.Location.instruction_name")); } else { goto handle_unusual; } break; } // repeated int64 shape_index = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_shape_index()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 1, 26u, input, this->mutable_shape_index()))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.LogicalBufferProto.Location) return true; failure: // @@protoc_insertion_point(parse_failure:xla.LogicalBufferProto.Location) return false; #undef DO_ } void LogicalBufferProto_Location::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.LogicalBufferProto.Location) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string computation_name = 1; if (this->computation_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->computation_name().data(), static_cast<int>(this->computation_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.LogicalBufferProto.Location.computation_name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->computation_name(), output); } // string instruction_name = 2; if (this->instruction_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->instruction_name().data(), static_cast<int>(this->instruction_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.LogicalBufferProto.Location.instruction_name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->instruction_name(), output); } // repeated int64 shape_index = 3; if (this->shape_index_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(3, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _shape_index_cached_byte_size_)); } for (int i = 0, n = this->shape_index_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->shape_index(i), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.LogicalBufferProto.Location) } ::google::protobuf::uint8* LogicalBufferProto_Location::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.LogicalBufferProto.Location) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string computation_name = 1; if (this->computation_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->computation_name().data(), static_cast<int>(this->computation_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.LogicalBufferProto.Location.computation_name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->computation_name(), target); } // string instruction_name = 2; if (this->instruction_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->instruction_name().data(), static_cast<int>(this->instruction_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.LogicalBufferProto.Location.instruction_name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->instruction_name(), target); } // repeated int64 shape_index = 3; if (this->shape_index_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 3, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _shape_index_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->shape_index_, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.LogicalBufferProto.Location) return target; } size_t LogicalBufferProto_Location::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.LogicalBufferProto.Location) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated int64 shape_index = 3; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->shape_index_); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _shape_index_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // string computation_name = 1; if (this->computation_name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->computation_name()); } // string instruction_name = 2; if (this->instruction_name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->instruction_name()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void LogicalBufferProto_Location::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.LogicalBufferProto.Location) GOOGLE_DCHECK_NE(&from, this); const LogicalBufferProto_Location* source = ::google::protobuf::internal::DynamicCastToGenerated<const LogicalBufferProto_Location>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.LogicalBufferProto.Location) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.LogicalBufferProto.Location) MergeFrom(*source); } } void LogicalBufferProto_Location::MergeFrom(const LogicalBufferProto_Location& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.LogicalBufferProto.Location) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; shape_index_.MergeFrom(from.shape_index_); if (from.computation_name().size() > 0) { set_computation_name(from.computation_name()); } if (from.instruction_name().size() > 0) { set_instruction_name(from.instruction_name()); } } void LogicalBufferProto_Location::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.LogicalBufferProto.Location) if (&from == this) return; Clear(); MergeFrom(from); } void LogicalBufferProto_Location::CopyFrom(const LogicalBufferProto_Location& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.LogicalBufferProto.Location) if (&from == this) return; Clear(); MergeFrom(from); } bool LogicalBufferProto_Location::IsInitialized() const { return true; } void LogicalBufferProto_Location::Swap(LogicalBufferProto_Location* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { LogicalBufferProto_Location* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void LogicalBufferProto_Location::UnsafeArenaSwap(LogicalBufferProto_Location* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void LogicalBufferProto_Location::InternalSwap(LogicalBufferProto_Location* other) { using std::swap; shape_index_.InternalSwap(&other->shape_index_); computation_name_.Swap(&other->computation_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); instruction_name_.Swap(&other->instruction_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata LogicalBufferProto_Location::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void LogicalBufferProto::InitAsDefaultInstance() { ::xla::_LogicalBufferProto_default_instance_._instance.get_mutable()->defined_at_ = const_cast< ::xla::LogicalBufferProto_Location*>( ::xla::LogicalBufferProto_Location::internal_default_instance()); } void LogicalBufferProto::unsafe_arena_set_allocated_defined_at( ::xla::LogicalBufferProto_Location* defined_at) { if (GetArenaNoVirtual() == NULL) { delete defined_at_; } defined_at_ = defined_at; if (defined_at) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.LogicalBufferProto.defined_at) } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int LogicalBufferProto::kIdFieldNumber; const int LogicalBufferProto::kSizeFieldNumber; const int LogicalBufferProto::kDefinedAtFieldNumber; const int LogicalBufferProto::kColorFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 LogicalBufferProto::LogicalBufferProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_LogicalBufferProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.LogicalBufferProto) } LogicalBufferProto::LogicalBufferProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_LogicalBufferProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.LogicalBufferProto) } LogicalBufferProto::LogicalBufferProto(const LogicalBufferProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_defined_at()) { defined_at_ = new ::xla::LogicalBufferProto_Location(*from.defined_at_); } else { defined_at_ = NULL; } ::memcpy(&id_, &from.id_, static_cast<size_t>(reinterpret_cast<char*>(&color_) - reinterpret_cast<char*>(&id_)) + sizeof(color_)); // @@protoc_insertion_point(copy_constructor:xla.LogicalBufferProto) } void LogicalBufferProto::SharedCtor() { ::memset(&defined_at_, 0, static_cast<size_t>( reinterpret_cast<char*>(&color_) - reinterpret_cast<char*>(&defined_at_)) + sizeof(color_)); } LogicalBufferProto::~LogicalBufferProto() { // @@protoc_insertion_point(destructor:xla.LogicalBufferProto) SharedDtor(); } void LogicalBufferProto::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); if (this != internal_default_instance()) delete defined_at_; } void LogicalBufferProto::ArenaDtor(void* object) { LogicalBufferProto* _this = reinterpret_cast< LogicalBufferProto* >(object); (void)_this; } void LogicalBufferProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void LogicalBufferProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* LogicalBufferProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const LogicalBufferProto& LogicalBufferProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_LogicalBufferProto.base); return *internal_default_instance(); } void LogicalBufferProto::Clear() { // @@protoc_insertion_point(message_clear_start:xla.LogicalBufferProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (GetArenaNoVirtual() == NULL && defined_at_ != NULL) { delete defined_at_; } defined_at_ = NULL; ::memset(&id_, 0, static_cast<size_t>( reinterpret_cast<char*>(&color_) - reinterpret_cast<char*>(&id_)) + sizeof(color_)); _internal_metadata_.Clear(); } bool LogicalBufferProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.LogicalBufferProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int64 id = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &id_))); } else { goto handle_unusual; } break; } // int64 size = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &size_))); } else { goto handle_unusual; } break; } // .xla.LogicalBufferProto.Location defined_at = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_defined_at())); } else { goto handle_unusual; } break; } // int64 color = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &color_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.LogicalBufferProto) return true; failure: // @@protoc_insertion_point(parse_failure:xla.LogicalBufferProto) return false; #undef DO_ } void LogicalBufferProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.LogicalBufferProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 id = 1; if (this->id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->id(), output); } // int64 size = 2; if (this->size() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->size(), output); } // .xla.LogicalBufferProto.Location defined_at = 3; if (this->has_defined_at()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->_internal_defined_at(), output); } // int64 color = 4; if (this->color() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(4, this->color(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.LogicalBufferProto) } ::google::protobuf::uint8* LogicalBufferProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.LogicalBufferProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 id = 1; if (this->id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->id(), target); } // int64 size = 2; if (this->size() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(2, this->size(), target); } // .xla.LogicalBufferProto.Location defined_at = 3; if (this->has_defined_at()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, this->_internal_defined_at(), deterministic, target); } // int64 color = 4; if (this->color() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(4, this->color(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.LogicalBufferProto) return target; } size_t LogicalBufferProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.LogicalBufferProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // .xla.LogicalBufferProto.Location defined_at = 3; if (this->has_defined_at()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *defined_at_); } // int64 id = 1; if (this->id() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->id()); } // int64 size = 2; if (this->size() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->size()); } // int64 color = 4; if (this->color() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->color()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void LogicalBufferProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.LogicalBufferProto) GOOGLE_DCHECK_NE(&from, this); const LogicalBufferProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const LogicalBufferProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.LogicalBufferProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.LogicalBufferProto) MergeFrom(*source); } } void LogicalBufferProto::MergeFrom(const LogicalBufferProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.LogicalBufferProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.has_defined_at()) { mutable_defined_at()->::xla::LogicalBufferProto_Location::MergeFrom(from.defined_at()); } if (from.id() != 0) { set_id(from.id()); } if (from.size() != 0) { set_size(from.size()); } if (from.color() != 0) { set_color(from.color()); } } void LogicalBufferProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.LogicalBufferProto) if (&from == this) return; Clear(); MergeFrom(from); } void LogicalBufferProto::CopyFrom(const LogicalBufferProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.LogicalBufferProto) if (&from == this) return; Clear(); MergeFrom(from); } bool LogicalBufferProto::IsInitialized() const { return true; } void LogicalBufferProto::Swap(LogicalBufferProto* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { LogicalBufferProto* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void LogicalBufferProto::UnsafeArenaSwap(LogicalBufferProto* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void LogicalBufferProto::InternalSwap(LogicalBufferProto* other) { using std::swap; swap(defined_at_, other->defined_at_); swap(id_, other->id_); swap(size_, other->size_); swap(color_, other->color_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata LogicalBufferProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void BufferAllocationProto_Assigned::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int BufferAllocationProto_Assigned::kLogicalBufferIdFieldNumber; const int BufferAllocationProto_Assigned::kOffsetFieldNumber; const int BufferAllocationProto_Assigned::kSizeFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 BufferAllocationProto_Assigned::BufferAllocationProto_Assigned() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAllocationProto_Assigned.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.BufferAllocationProto.Assigned) } BufferAllocationProto_Assigned::BufferAllocationProto_Assigned(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAllocationProto_Assigned.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.BufferAllocationProto.Assigned) } BufferAllocationProto_Assigned::BufferAllocationProto_Assigned(const BufferAllocationProto_Assigned& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&logical_buffer_id_, &from.logical_buffer_id_, static_cast<size_t>(reinterpret_cast<char*>(&size_) - reinterpret_cast<char*>(&logical_buffer_id_)) + sizeof(size_)); // @@protoc_insertion_point(copy_constructor:xla.BufferAllocationProto.Assigned) } void BufferAllocationProto_Assigned::SharedCtor() { ::memset(&logical_buffer_id_, 0, static_cast<size_t>( reinterpret_cast<char*>(&size_) - reinterpret_cast<char*>(&logical_buffer_id_)) + sizeof(size_)); } BufferAllocationProto_Assigned::~BufferAllocationProto_Assigned() { // @@protoc_insertion_point(destructor:xla.BufferAllocationProto.Assigned) SharedDtor(); } void BufferAllocationProto_Assigned::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void BufferAllocationProto_Assigned::ArenaDtor(void* object) { BufferAllocationProto_Assigned* _this = reinterpret_cast< BufferAllocationProto_Assigned* >(object); (void)_this; } void BufferAllocationProto_Assigned::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void BufferAllocationProto_Assigned::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* BufferAllocationProto_Assigned::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const BufferAllocationProto_Assigned& BufferAllocationProto_Assigned::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAllocationProto_Assigned.base); return *internal_default_instance(); } void BufferAllocationProto_Assigned::Clear() { // @@protoc_insertion_point(message_clear_start:xla.BufferAllocationProto.Assigned) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; ::memset(&logical_buffer_id_, 0, static_cast<size_t>( reinterpret_cast<char*>(&size_) - reinterpret_cast<char*>(&logical_buffer_id_)) + sizeof(size_)); _internal_metadata_.Clear(); } bool BufferAllocationProto_Assigned::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.BufferAllocationProto.Assigned) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int64 logical_buffer_id = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &logical_buffer_id_))); } else { goto handle_unusual; } break; } // int64 offset = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &offset_))); } else { goto handle_unusual; } break; } // int64 size = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &size_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.BufferAllocationProto.Assigned) return true; failure: // @@protoc_insertion_point(parse_failure:xla.BufferAllocationProto.Assigned) return false; #undef DO_ } void BufferAllocationProto_Assigned::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.BufferAllocationProto.Assigned) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 logical_buffer_id = 1; if (this->logical_buffer_id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->logical_buffer_id(), output); } // int64 offset = 2; if (this->offset() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->offset(), output); } // int64 size = 3; if (this->size() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(3, this->size(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.BufferAllocationProto.Assigned) } ::google::protobuf::uint8* BufferAllocationProto_Assigned::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.BufferAllocationProto.Assigned) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 logical_buffer_id = 1; if (this->logical_buffer_id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->logical_buffer_id(), target); } // int64 offset = 2; if (this->offset() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(2, this->offset(), target); } // int64 size = 3; if (this->size() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(3, this->size(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.BufferAllocationProto.Assigned) return target; } size_t BufferAllocationProto_Assigned::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.BufferAllocationProto.Assigned) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // int64 logical_buffer_id = 1; if (this->logical_buffer_id() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->logical_buffer_id()); } // int64 offset = 2; if (this->offset() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->offset()); } // int64 size = 3; if (this->size() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->size()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BufferAllocationProto_Assigned::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.BufferAllocationProto.Assigned) GOOGLE_DCHECK_NE(&from, this); const BufferAllocationProto_Assigned* source = ::google::protobuf::internal::DynamicCastToGenerated<const BufferAllocationProto_Assigned>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.BufferAllocationProto.Assigned) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.BufferAllocationProto.Assigned) MergeFrom(*source); } } void BufferAllocationProto_Assigned::MergeFrom(const BufferAllocationProto_Assigned& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.BufferAllocationProto.Assigned) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.logical_buffer_id() != 0) { set_logical_buffer_id(from.logical_buffer_id()); } if (from.offset() != 0) { set_offset(from.offset()); } if (from.size() != 0) { set_size(from.size()); } } void BufferAllocationProto_Assigned::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.BufferAllocationProto.Assigned) if (&from == this) return; Clear(); MergeFrom(from); } void BufferAllocationProto_Assigned::CopyFrom(const BufferAllocationProto_Assigned& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.BufferAllocationProto.Assigned) if (&from == this) return; Clear(); MergeFrom(from); } bool BufferAllocationProto_Assigned::IsInitialized() const { return true; } void BufferAllocationProto_Assigned::Swap(BufferAllocationProto_Assigned* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { BufferAllocationProto_Assigned* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void BufferAllocationProto_Assigned::UnsafeArenaSwap(BufferAllocationProto_Assigned* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void BufferAllocationProto_Assigned::InternalSwap(BufferAllocationProto_Assigned* other) { using std::swap; swap(logical_buffer_id_, other->logical_buffer_id_); swap(offset_, other->offset_); swap(size_, other->size_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata BufferAllocationProto_Assigned::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void BufferAllocationProto::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int BufferAllocationProto::kIndexFieldNumber; const int BufferAllocationProto::kSizeFieldNumber; const int BufferAllocationProto::kIsThreadLocalFieldNumber; const int BufferAllocationProto::kIsTupleFieldNumber; const int BufferAllocationProto::kIsEntryComputationParameterFieldNumber; const int BufferAllocationProto::kIsConstantFieldNumber; const int BufferAllocationProto::kParameterNumberFieldNumber; const int BufferAllocationProto::kParameterShapeIndexFieldNumber; const int BufferAllocationProto::kMaybeLiveOutFieldNumber; const int BufferAllocationProto::kColorFieldNumber; const int BufferAllocationProto::kAssignedFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 BufferAllocationProto::BufferAllocationProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAllocationProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.BufferAllocationProto) } BufferAllocationProto::BufferAllocationProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), assigned_(arena), parameter_shape_index_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAllocationProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.BufferAllocationProto) } BufferAllocationProto::BufferAllocationProto(const BufferAllocationProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), assigned_(from.assigned_), parameter_shape_index_(from.parameter_shape_index_) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&index_, &from.index_, static_cast<size_t>(reinterpret_cast<char*>(&color_) - reinterpret_cast<char*>(&index_)) + sizeof(color_)); // @@protoc_insertion_point(copy_constructor:xla.BufferAllocationProto) } void BufferAllocationProto::SharedCtor() { ::memset(&index_, 0, static_cast<size_t>( reinterpret_cast<char*>(&color_) - reinterpret_cast<char*>(&index_)) + sizeof(color_)); } BufferAllocationProto::~BufferAllocationProto() { // @@protoc_insertion_point(destructor:xla.BufferAllocationProto) SharedDtor(); } void BufferAllocationProto::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void BufferAllocationProto::ArenaDtor(void* object) { BufferAllocationProto* _this = reinterpret_cast< BufferAllocationProto* >(object); (void)_this; } void BufferAllocationProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void BufferAllocationProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* BufferAllocationProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const BufferAllocationProto& BufferAllocationProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAllocationProto.base); return *internal_default_instance(); } void BufferAllocationProto::Clear() { // @@protoc_insertion_point(message_clear_start:xla.BufferAllocationProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; assigned_.Clear(); parameter_shape_index_.Clear(); ::memset(&index_, 0, static_cast<size_t>( reinterpret_cast<char*>(&color_) - reinterpret_cast<char*>(&index_)) + sizeof(color_)); _internal_metadata_.Clear(); } bool BufferAllocationProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.BufferAllocationProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int64 index = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &index_))); } else { goto handle_unusual; } break; } // int64 size = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &size_))); } else { goto handle_unusual; } break; } // bool is_thread_local = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &is_thread_local_))); } else { goto handle_unusual; } break; } // bool is_entry_computation_parameter = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &is_entry_computation_parameter_))); } else { goto handle_unusual; } break; } // int64 parameter_number = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &parameter_number_))); } else { goto handle_unusual; } break; } // bool maybe_live_out = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &maybe_live_out_))); } else { goto handle_unusual; } break; } // int64 color = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(64u /* 64 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &color_))); } else { goto handle_unusual; } break; } // repeated .xla.BufferAllocationProto.Assigned assigned = 9; case 9: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_assigned())); } else { goto handle_unusual; } break; } // repeated int64 parameter_shape_index = 10; case 10: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_parameter_shape_index()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(80u /* 80 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 1, 82u, input, this->mutable_parameter_shape_index()))); } else { goto handle_unusual; } break; } // bool is_tuple = 11; case 11: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(88u /* 88 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &is_tuple_))); } else { goto handle_unusual; } break; } // bool is_constant = 12; case 12: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(96u /* 96 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &is_constant_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.BufferAllocationProto) return true; failure: // @@protoc_insertion_point(parse_failure:xla.BufferAllocationProto) return false; #undef DO_ } void BufferAllocationProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.BufferAllocationProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 index = 1; if (this->index() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->index(), output); } // int64 size = 2; if (this->size() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->size(), output); } // bool is_thread_local = 3; if (this->is_thread_local() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(3, this->is_thread_local(), output); } // bool is_entry_computation_parameter = 5; if (this->is_entry_computation_parameter() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(5, this->is_entry_computation_parameter(), output); } // int64 parameter_number = 6; if (this->parameter_number() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(6, this->parameter_number(), output); } // bool maybe_live_out = 7; if (this->maybe_live_out() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(7, this->maybe_live_out(), output); } // int64 color = 8; if (this->color() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(8, this->color(), output); } // repeated .xla.BufferAllocationProto.Assigned assigned = 9; for (unsigned int i = 0, n = static_cast<unsigned int>(this->assigned_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 9, this->assigned(static_cast<int>(i)), output); } // repeated int64 parameter_shape_index = 10; if (this->parameter_shape_index_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(10, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _parameter_shape_index_cached_byte_size_)); } for (int i = 0, n = this->parameter_shape_index_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->parameter_shape_index(i), output); } // bool is_tuple = 11; if (this->is_tuple() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(11, this->is_tuple(), output); } // bool is_constant = 12; if (this->is_constant() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(12, this->is_constant(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.BufferAllocationProto) } ::google::protobuf::uint8* BufferAllocationProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.BufferAllocationProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 index = 1; if (this->index() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->index(), target); } // int64 size = 2; if (this->size() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(2, this->size(), target); } // bool is_thread_local = 3; if (this->is_thread_local() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->is_thread_local(), target); } // bool is_entry_computation_parameter = 5; if (this->is_entry_computation_parameter() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(5, this->is_entry_computation_parameter(), target); } // int64 parameter_number = 6; if (this->parameter_number() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(6, this->parameter_number(), target); } // bool maybe_live_out = 7; if (this->maybe_live_out() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(7, this->maybe_live_out(), target); } // int64 color = 8; if (this->color() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(8, this->color(), target); } // repeated .xla.BufferAllocationProto.Assigned assigned = 9; for (unsigned int i = 0, n = static_cast<unsigned int>(this->assigned_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 9, this->assigned(static_cast<int>(i)), deterministic, target); } // repeated int64 parameter_shape_index = 10; if (this->parameter_shape_index_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 10, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _parameter_shape_index_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->parameter_shape_index_, target); } // bool is_tuple = 11; if (this->is_tuple() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(11, this->is_tuple(), target); } // bool is_constant = 12; if (this->is_constant() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(12, this->is_constant(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.BufferAllocationProto) return target; } size_t BufferAllocationProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.BufferAllocationProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated .xla.BufferAllocationProto.Assigned assigned = 9; { unsigned int count = static_cast<unsigned int>(this->assigned_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->assigned(static_cast<int>(i))); } } // repeated int64 parameter_shape_index = 10; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->parameter_shape_index_); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _parameter_shape_index_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // int64 index = 1; if (this->index() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->index()); } // int64 size = 2; if (this->size() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->size()); } // int64 parameter_number = 6; if (this->parameter_number() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->parameter_number()); } // bool maybe_live_out = 7; if (this->maybe_live_out() != 0) { total_size += 1 + 1; } // bool is_thread_local = 3; if (this->is_thread_local() != 0) { total_size += 1 + 1; } // bool is_tuple = 11; if (this->is_tuple() != 0) { total_size += 1 + 1; } // bool is_entry_computation_parameter = 5; if (this->is_entry_computation_parameter() != 0) { total_size += 1 + 1; } // bool is_constant = 12; if (this->is_constant() != 0) { total_size += 1 + 1; } // int64 color = 8; if (this->color() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->color()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BufferAllocationProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.BufferAllocationProto) GOOGLE_DCHECK_NE(&from, this); const BufferAllocationProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const BufferAllocationProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.BufferAllocationProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.BufferAllocationProto) MergeFrom(*source); } } void BufferAllocationProto::MergeFrom(const BufferAllocationProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.BufferAllocationProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; assigned_.MergeFrom(from.assigned_); parameter_shape_index_.MergeFrom(from.parameter_shape_index_); if (from.index() != 0) { set_index(from.index()); } if (from.size() != 0) { set_size(from.size()); } if (from.parameter_number() != 0) { set_parameter_number(from.parameter_number()); } if (from.maybe_live_out() != 0) { set_maybe_live_out(from.maybe_live_out()); } if (from.is_thread_local() != 0) { set_is_thread_local(from.is_thread_local()); } if (from.is_tuple() != 0) { set_is_tuple(from.is_tuple()); } if (from.is_entry_computation_parameter() != 0) { set_is_entry_computation_parameter(from.is_entry_computation_parameter()); } if (from.is_constant() != 0) { set_is_constant(from.is_constant()); } if (from.color() != 0) { set_color(from.color()); } } void BufferAllocationProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.BufferAllocationProto) if (&from == this) return; Clear(); MergeFrom(from); } void BufferAllocationProto::CopyFrom(const BufferAllocationProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.BufferAllocationProto) if (&from == this) return; Clear(); MergeFrom(from); } bool BufferAllocationProto::IsInitialized() const { return true; } void BufferAllocationProto::Swap(BufferAllocationProto* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { BufferAllocationProto* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void BufferAllocationProto::UnsafeArenaSwap(BufferAllocationProto* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void BufferAllocationProto::InternalSwap(BufferAllocationProto* other) { using std::swap; CastToBase(&assigned_)->InternalSwap(CastToBase(&other->assigned_)); parameter_shape_index_.InternalSwap(&other->parameter_shape_index_); swap(index_, other->index_); swap(size_, other->size_); swap(parameter_number_, other->parameter_number_); swap(maybe_live_out_, other->maybe_live_out_); swap(is_thread_local_, other->is_thread_local_); swap(is_tuple_, other->is_tuple_); swap(is_entry_computation_parameter_, other->is_entry_computation_parameter_); swap(is_constant_, other->is_constant_); swap(color_, other->color_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata BufferAllocationProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void HeapSimulatorTrace_Event::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HeapSimulatorTrace_Event::kKindFieldNumber; const int HeapSimulatorTrace_Event::kBufferIdFieldNumber; const int HeapSimulatorTrace_Event::kComputationNameFieldNumber; const int HeapSimulatorTrace_Event::kInstructionNameFieldNumber; const int HeapSimulatorTrace_Event::kShareWithCanonicalIdFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HeapSimulatorTrace_Event::HeapSimulatorTrace_Event() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HeapSimulatorTrace_Event.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.HeapSimulatorTrace.Event) } HeapSimulatorTrace_Event::HeapSimulatorTrace_Event(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HeapSimulatorTrace_Event.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.HeapSimulatorTrace.Event) } HeapSimulatorTrace_Event::HeapSimulatorTrace_Event(const HeapSimulatorTrace_Event& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); computation_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.computation_name().size() > 0) { computation_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.computation_name(), GetArenaNoVirtual()); } instruction_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.instruction_name().size() > 0) { instruction_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.instruction_name(), GetArenaNoVirtual()); } ::memcpy(&buffer_id_, &from.buffer_id_, static_cast<size_t>(reinterpret_cast<char*>(&kind_) - reinterpret_cast<char*>(&buffer_id_)) + sizeof(kind_)); // @@protoc_insertion_point(copy_constructor:xla.HeapSimulatorTrace.Event) } void HeapSimulatorTrace_Event::SharedCtor() { computation_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); instruction_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&buffer_id_, 0, static_cast<size_t>( reinterpret_cast<char*>(&kind_) - reinterpret_cast<char*>(&buffer_id_)) + sizeof(kind_)); } HeapSimulatorTrace_Event::~HeapSimulatorTrace_Event() { // @@protoc_insertion_point(destructor:xla.HeapSimulatorTrace.Event) SharedDtor(); } void HeapSimulatorTrace_Event::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); computation_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); instruction_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void HeapSimulatorTrace_Event::ArenaDtor(void* object) { HeapSimulatorTrace_Event* _this = reinterpret_cast< HeapSimulatorTrace_Event* >(object); (void)_this; } void HeapSimulatorTrace_Event::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void HeapSimulatorTrace_Event::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HeapSimulatorTrace_Event::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HeapSimulatorTrace_Event& HeapSimulatorTrace_Event::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HeapSimulatorTrace_Event.base); return *internal_default_instance(); } void HeapSimulatorTrace_Event::Clear() { // @@protoc_insertion_point(message_clear_start:xla.HeapSimulatorTrace.Event) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; computation_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); instruction_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); ::memset(&buffer_id_, 0, static_cast<size_t>( reinterpret_cast<char*>(&kind_) - reinterpret_cast<char*>(&buffer_id_)) + sizeof(kind_)); _internal_metadata_.Clear(); } bool HeapSimulatorTrace_Event::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.HeapSimulatorTrace.Event) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // .xla.HeapSimulatorTrace.Event.Kind kind = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_kind(static_cast< ::xla::HeapSimulatorTrace_Event_Kind >(value)); } else { goto handle_unusual; } break; } // int64 buffer_id = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &buffer_id_))); } else { goto handle_unusual; } break; } // string computation_name = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_computation_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->computation_name().data(), static_cast<int>(this->computation_name().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HeapSimulatorTrace.Event.computation_name")); } else { goto handle_unusual; } break; } // string instruction_name = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_instruction_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->instruction_name().data(), static_cast<int>(this->instruction_name().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HeapSimulatorTrace.Event.instruction_name")); } else { goto handle_unusual; } break; } // int64 share_with_canonical_id = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &share_with_canonical_id_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.HeapSimulatorTrace.Event) return true; failure: // @@protoc_insertion_point(parse_failure:xla.HeapSimulatorTrace.Event) return false; #undef DO_ } void HeapSimulatorTrace_Event::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.HeapSimulatorTrace.Event) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .xla.HeapSimulatorTrace.Event.Kind kind = 1; if (this->kind() != 0) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 1, this->kind(), output); } // int64 buffer_id = 2; if (this->buffer_id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->buffer_id(), output); } // string computation_name = 3; if (this->computation_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->computation_name().data(), static_cast<int>(this->computation_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HeapSimulatorTrace.Event.computation_name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->computation_name(), output); } // string instruction_name = 4; if (this->instruction_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->instruction_name().data(), static_cast<int>(this->instruction_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HeapSimulatorTrace.Event.instruction_name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 4, this->instruction_name(), output); } // int64 share_with_canonical_id = 5; if (this->share_with_canonical_id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(5, this->share_with_canonical_id(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.HeapSimulatorTrace.Event) } ::google::protobuf::uint8* HeapSimulatorTrace_Event::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.HeapSimulatorTrace.Event) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .xla.HeapSimulatorTrace.Event.Kind kind = 1; if (this->kind() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 1, this->kind(), target); } // int64 buffer_id = 2; if (this->buffer_id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(2, this->buffer_id(), target); } // string computation_name = 3; if (this->computation_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->computation_name().data(), static_cast<int>(this->computation_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HeapSimulatorTrace.Event.computation_name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 3, this->computation_name(), target); } // string instruction_name = 4; if (this->instruction_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->instruction_name().data(), static_cast<int>(this->instruction_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HeapSimulatorTrace.Event.instruction_name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 4, this->instruction_name(), target); } // int64 share_with_canonical_id = 5; if (this->share_with_canonical_id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(5, this->share_with_canonical_id(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.HeapSimulatorTrace.Event) return target; } size_t HeapSimulatorTrace_Event::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.HeapSimulatorTrace.Event) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // string computation_name = 3; if (this->computation_name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->computation_name()); } // string instruction_name = 4; if (this->instruction_name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->instruction_name()); } // int64 buffer_id = 2; if (this->buffer_id() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->buffer_id()); } // int64 share_with_canonical_id = 5; if (this->share_with_canonical_id() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->share_with_canonical_id()); } // .xla.HeapSimulatorTrace.Event.Kind kind = 1; if (this->kind() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->kind()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HeapSimulatorTrace_Event::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.HeapSimulatorTrace.Event) GOOGLE_DCHECK_NE(&from, this); const HeapSimulatorTrace_Event* source = ::google::protobuf::internal::DynamicCastToGenerated<const HeapSimulatorTrace_Event>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.HeapSimulatorTrace.Event) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.HeapSimulatorTrace.Event) MergeFrom(*source); } } void HeapSimulatorTrace_Event::MergeFrom(const HeapSimulatorTrace_Event& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.HeapSimulatorTrace.Event) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.computation_name().size() > 0) { set_computation_name(from.computation_name()); } if (from.instruction_name().size() > 0) { set_instruction_name(from.instruction_name()); } if (from.buffer_id() != 0) { set_buffer_id(from.buffer_id()); } if (from.share_with_canonical_id() != 0) { set_share_with_canonical_id(from.share_with_canonical_id()); } if (from.kind() != 0) { set_kind(from.kind()); } } void HeapSimulatorTrace_Event::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.HeapSimulatorTrace.Event) if (&from == this) return; Clear(); MergeFrom(from); } void HeapSimulatorTrace_Event::CopyFrom(const HeapSimulatorTrace_Event& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.HeapSimulatorTrace.Event) if (&from == this) return; Clear(); MergeFrom(from); } bool HeapSimulatorTrace_Event::IsInitialized() const { return true; } void HeapSimulatorTrace_Event::Swap(HeapSimulatorTrace_Event* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { HeapSimulatorTrace_Event* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void HeapSimulatorTrace_Event::UnsafeArenaSwap(HeapSimulatorTrace_Event* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void HeapSimulatorTrace_Event::InternalSwap(HeapSimulatorTrace_Event* other) { using std::swap; computation_name_.Swap(&other->computation_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); instruction_name_.Swap(&other->instruction_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(buffer_id_, other->buffer_id_); swap(share_with_canonical_id_, other->share_with_canonical_id_); swap(kind_, other->kind_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HeapSimulatorTrace_Event::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void HeapSimulatorTrace::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HeapSimulatorTrace::kEventsFieldNumber; const int HeapSimulatorTrace::kWholeModuleSimulationFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HeapSimulatorTrace::HeapSimulatorTrace() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HeapSimulatorTrace.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.HeapSimulatorTrace) } HeapSimulatorTrace::HeapSimulatorTrace(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), events_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HeapSimulatorTrace.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.HeapSimulatorTrace) } HeapSimulatorTrace::HeapSimulatorTrace(const HeapSimulatorTrace& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), events_(from.events_) { _internal_metadata_.MergeFrom(from._internal_metadata_); whole_module_simulation_ = from.whole_module_simulation_; // @@protoc_insertion_point(copy_constructor:xla.HeapSimulatorTrace) } void HeapSimulatorTrace::SharedCtor() { whole_module_simulation_ = false; } HeapSimulatorTrace::~HeapSimulatorTrace() { // @@protoc_insertion_point(destructor:xla.HeapSimulatorTrace) SharedDtor(); } void HeapSimulatorTrace::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void HeapSimulatorTrace::ArenaDtor(void* object) { HeapSimulatorTrace* _this = reinterpret_cast< HeapSimulatorTrace* >(object); (void)_this; } void HeapSimulatorTrace::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void HeapSimulatorTrace::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HeapSimulatorTrace::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HeapSimulatorTrace& HeapSimulatorTrace::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HeapSimulatorTrace.base); return *internal_default_instance(); } void HeapSimulatorTrace::Clear() { // @@protoc_insertion_point(message_clear_start:xla.HeapSimulatorTrace) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; events_.Clear(); whole_module_simulation_ = false; _internal_metadata_.Clear(); } bool HeapSimulatorTrace::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.HeapSimulatorTrace) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .xla.HeapSimulatorTrace.Event events = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_events())); } else { goto handle_unusual; } break; } // bool whole_module_simulation = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &whole_module_simulation_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.HeapSimulatorTrace) return true; failure: // @@protoc_insertion_point(parse_failure:xla.HeapSimulatorTrace) return false; #undef DO_ } void HeapSimulatorTrace::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.HeapSimulatorTrace) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .xla.HeapSimulatorTrace.Event events = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->events_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->events(static_cast<int>(i)), output); } // bool whole_module_simulation = 2; if (this->whole_module_simulation() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->whole_module_simulation(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.HeapSimulatorTrace) } ::google::protobuf::uint8* HeapSimulatorTrace::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.HeapSimulatorTrace) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .xla.HeapSimulatorTrace.Event events = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->events_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, this->events(static_cast<int>(i)), deterministic, target); } // bool whole_module_simulation = 2; if (this->whole_module_simulation() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->whole_module_simulation(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.HeapSimulatorTrace) return target; } size_t HeapSimulatorTrace::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.HeapSimulatorTrace) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated .xla.HeapSimulatorTrace.Event events = 1; { unsigned int count = static_cast<unsigned int>(this->events_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->events(static_cast<int>(i))); } } // bool whole_module_simulation = 2; if (this->whole_module_simulation() != 0) { total_size += 1 + 1; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HeapSimulatorTrace::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.HeapSimulatorTrace) GOOGLE_DCHECK_NE(&from, this); const HeapSimulatorTrace* source = ::google::protobuf::internal::DynamicCastToGenerated<const HeapSimulatorTrace>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.HeapSimulatorTrace) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.HeapSimulatorTrace) MergeFrom(*source); } } void HeapSimulatorTrace::MergeFrom(const HeapSimulatorTrace& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.HeapSimulatorTrace) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; events_.MergeFrom(from.events_); if (from.whole_module_simulation() != 0) { set_whole_module_simulation(from.whole_module_simulation()); } } void HeapSimulatorTrace::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.HeapSimulatorTrace) if (&from == this) return; Clear(); MergeFrom(from); } void HeapSimulatorTrace::CopyFrom(const HeapSimulatorTrace& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.HeapSimulatorTrace) if (&from == this) return; Clear(); MergeFrom(from); } bool HeapSimulatorTrace::IsInitialized() const { return true; } void HeapSimulatorTrace::Swap(HeapSimulatorTrace* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { HeapSimulatorTrace* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void HeapSimulatorTrace::UnsafeArenaSwap(HeapSimulatorTrace* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void HeapSimulatorTrace::InternalSwap(HeapSimulatorTrace* other) { using std::swap; CastToBase(&events_)->InternalSwap(CastToBase(&other->events_)); swap(whole_module_simulation_, other->whole_module_simulation_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HeapSimulatorTrace::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void HloModuleGroupProto::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HloModuleGroupProto::kNameFieldNumber; const int HloModuleGroupProto::kHloModulesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HloModuleGroupProto::HloModuleGroupProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloModuleGroupProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.HloModuleGroupProto) } HloModuleGroupProto::HloModuleGroupProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), hlo_modules_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloModuleGroupProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.HloModuleGroupProto) } HloModuleGroupProto::HloModuleGroupProto(const HloModuleGroupProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), hlo_modules_(from.hlo_modules_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(), GetArenaNoVirtual()); } // @@protoc_insertion_point(copy_constructor:xla.HloModuleGroupProto) } void HloModuleGroupProto::SharedCtor() { name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } HloModuleGroupProto::~HloModuleGroupProto() { // @@protoc_insertion_point(destructor:xla.HloModuleGroupProto) SharedDtor(); } void HloModuleGroupProto::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void HloModuleGroupProto::ArenaDtor(void* object) { HloModuleGroupProto* _this = reinterpret_cast< HloModuleGroupProto* >(object); (void)_this; } void HloModuleGroupProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void HloModuleGroupProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HloModuleGroupProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HloModuleGroupProto& HloModuleGroupProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloModuleGroupProto.base); return *internal_default_instance(); } void HloModuleGroupProto::Clear() { // @@protoc_insertion_point(message_clear_start:xla.HloModuleGroupProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; hlo_modules_.Clear(); name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _internal_metadata_.Clear(); } bool HloModuleGroupProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.HloModuleGroupProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string name = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HloModuleGroupProto.name")); } else { goto handle_unusual; } break; } // repeated .xla.HloModuleProto hlo_modules = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_hlo_modules())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.HloModuleGroupProto) return true; failure: // @@protoc_insertion_point(parse_failure:xla.HloModuleGroupProto) return false; #undef DO_ } void HloModuleGroupProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.HloModuleGroupProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloModuleGroupProto.name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // repeated .xla.HloModuleProto hlo_modules = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->hlo_modules_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->hlo_modules(static_cast<int>(i)), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.HloModuleGroupProto) } ::google::protobuf::uint8* HloModuleGroupProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.HloModuleGroupProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloModuleGroupProto.name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // repeated .xla.HloModuleProto hlo_modules = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->hlo_modules_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, this->hlo_modules(static_cast<int>(i)), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.HloModuleGroupProto) return target; } size_t HloModuleGroupProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.HloModuleGroupProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated .xla.HloModuleProto hlo_modules = 2; { unsigned int count = static_cast<unsigned int>(this->hlo_modules_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->hlo_modules(static_cast<int>(i))); } } // string name = 1; if (this->name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->name()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HloModuleGroupProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.HloModuleGroupProto) GOOGLE_DCHECK_NE(&from, this); const HloModuleGroupProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const HloModuleGroupProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.HloModuleGroupProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.HloModuleGroupProto) MergeFrom(*source); } } void HloModuleGroupProto::MergeFrom(const HloModuleGroupProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.HloModuleGroupProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; hlo_modules_.MergeFrom(from.hlo_modules_); if (from.name().size() > 0) { set_name(from.name()); } } void HloModuleGroupProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.HloModuleGroupProto) if (&from == this) return; Clear(); MergeFrom(from); } void HloModuleGroupProto::CopyFrom(const HloModuleGroupProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.HloModuleGroupProto) if (&from == this) return; Clear(); MergeFrom(from); } bool HloModuleGroupProto::IsInitialized() const { return true; } void HloModuleGroupProto::Swap(HloModuleGroupProto* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { HloModuleGroupProto* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void HloModuleGroupProto::UnsafeArenaSwap(HloModuleGroupProto* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void HloModuleGroupProto::InternalSwap(HloModuleGroupProto* other) { using std::swap; CastToBase(&hlo_modules_)->InternalSwap(CastToBase(&other->hlo_modules_)); name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HloModuleGroupProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void BufferAssignmentProto_BufferAlias::InitAsDefaultInstance() { ::xla::_BufferAssignmentProto_BufferAlias_default_instance_._instance.get_mutable()->location_ = const_cast< ::xla::LogicalBufferProto_Location*>( ::xla::LogicalBufferProto_Location::internal_default_instance()); } void BufferAssignmentProto_BufferAlias::unsafe_arena_set_allocated_location( ::xla::LogicalBufferProto_Location* location) { if (GetArenaNoVirtual() == NULL) { delete location_; } location_ = location; if (location) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.BufferAssignmentProto.BufferAlias.location) } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int BufferAssignmentProto_BufferAlias::kSourceBufferIdFieldNumber; const int BufferAssignmentProto_BufferAlias::kLocationFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 BufferAssignmentProto_BufferAlias::BufferAssignmentProto_BufferAlias() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAssignmentProto_BufferAlias.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.BufferAssignmentProto.BufferAlias) } BufferAssignmentProto_BufferAlias::BufferAssignmentProto_BufferAlias(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAssignmentProto_BufferAlias.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.BufferAssignmentProto.BufferAlias) } BufferAssignmentProto_BufferAlias::BufferAssignmentProto_BufferAlias(const BufferAssignmentProto_BufferAlias& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_location()) { location_ = new ::xla::LogicalBufferProto_Location(*from.location_); } else { location_ = NULL; } source_buffer_id_ = from.source_buffer_id_; // @@protoc_insertion_point(copy_constructor:xla.BufferAssignmentProto.BufferAlias) } void BufferAssignmentProto_BufferAlias::SharedCtor() { ::memset(&location_, 0, static_cast<size_t>( reinterpret_cast<char*>(&source_buffer_id_) - reinterpret_cast<char*>(&location_)) + sizeof(source_buffer_id_)); } BufferAssignmentProto_BufferAlias::~BufferAssignmentProto_BufferAlias() { // @@protoc_insertion_point(destructor:xla.BufferAssignmentProto.BufferAlias) SharedDtor(); } void BufferAssignmentProto_BufferAlias::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); if (this != internal_default_instance()) delete location_; } void BufferAssignmentProto_BufferAlias::ArenaDtor(void* object) { BufferAssignmentProto_BufferAlias* _this = reinterpret_cast< BufferAssignmentProto_BufferAlias* >(object); (void)_this; } void BufferAssignmentProto_BufferAlias::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void BufferAssignmentProto_BufferAlias::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* BufferAssignmentProto_BufferAlias::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const BufferAssignmentProto_BufferAlias& BufferAssignmentProto_BufferAlias::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAssignmentProto_BufferAlias.base); return *internal_default_instance(); } void BufferAssignmentProto_BufferAlias::Clear() { // @@protoc_insertion_point(message_clear_start:xla.BufferAssignmentProto.BufferAlias) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (GetArenaNoVirtual() == NULL && location_ != NULL) { delete location_; } location_ = NULL; source_buffer_id_ = GOOGLE_LONGLONG(0); _internal_metadata_.Clear(); } bool BufferAssignmentProto_BufferAlias::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.BufferAssignmentProto.BufferAlias) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int64 source_buffer_id = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &source_buffer_id_))); } else { goto handle_unusual; } break; } // .xla.LogicalBufferProto.Location location = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_location())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.BufferAssignmentProto.BufferAlias) return true; failure: // @@protoc_insertion_point(parse_failure:xla.BufferAssignmentProto.BufferAlias) return false; #undef DO_ } void BufferAssignmentProto_BufferAlias::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.BufferAssignmentProto.BufferAlias) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 source_buffer_id = 1; if (this->source_buffer_id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->source_buffer_id(), output); } // .xla.LogicalBufferProto.Location location = 2; if (this->has_location()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->_internal_location(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.BufferAssignmentProto.BufferAlias) } ::google::protobuf::uint8* BufferAssignmentProto_BufferAlias::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.BufferAssignmentProto.BufferAlias) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 source_buffer_id = 1; if (this->source_buffer_id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->source_buffer_id(), target); } // .xla.LogicalBufferProto.Location location = 2; if (this->has_location()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, this->_internal_location(), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.BufferAssignmentProto.BufferAlias) return target; } size_t BufferAssignmentProto_BufferAlias::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.BufferAssignmentProto.BufferAlias) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // .xla.LogicalBufferProto.Location location = 2; if (this->has_location()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *location_); } // int64 source_buffer_id = 1; if (this->source_buffer_id() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->source_buffer_id()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BufferAssignmentProto_BufferAlias::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.BufferAssignmentProto.BufferAlias) GOOGLE_DCHECK_NE(&from, this); const BufferAssignmentProto_BufferAlias* source = ::google::protobuf::internal::DynamicCastToGenerated<const BufferAssignmentProto_BufferAlias>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.BufferAssignmentProto.BufferAlias) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.BufferAssignmentProto.BufferAlias) MergeFrom(*source); } } void BufferAssignmentProto_BufferAlias::MergeFrom(const BufferAssignmentProto_BufferAlias& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.BufferAssignmentProto.BufferAlias) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.has_location()) { mutable_location()->::xla::LogicalBufferProto_Location::MergeFrom(from.location()); } if (from.source_buffer_id() != 0) { set_source_buffer_id(from.source_buffer_id()); } } void BufferAssignmentProto_BufferAlias::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.BufferAssignmentProto.BufferAlias) if (&from == this) return; Clear(); MergeFrom(from); } void BufferAssignmentProto_BufferAlias::CopyFrom(const BufferAssignmentProto_BufferAlias& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.BufferAssignmentProto.BufferAlias) if (&from == this) return; Clear(); MergeFrom(from); } bool BufferAssignmentProto_BufferAlias::IsInitialized() const { return true; } void BufferAssignmentProto_BufferAlias::Swap(BufferAssignmentProto_BufferAlias* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { BufferAssignmentProto_BufferAlias* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void BufferAssignmentProto_BufferAlias::UnsafeArenaSwap(BufferAssignmentProto_BufferAlias* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void BufferAssignmentProto_BufferAlias::InternalSwap(BufferAssignmentProto_BufferAlias* other) { using std::swap; swap(location_, other->location_); swap(source_buffer_id_, other->source_buffer_id_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata BufferAssignmentProto_BufferAlias::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void BufferAssignmentProto::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int BufferAssignmentProto::kLogicalBuffersFieldNumber; const int BufferAssignmentProto::kBufferAliasesFieldNumber; const int BufferAssignmentProto::kBufferAllocationsFieldNumber; const int BufferAssignmentProto::kHeapSimulatorTracesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 BufferAssignmentProto::BufferAssignmentProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAssignmentProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.BufferAssignmentProto) } BufferAssignmentProto::BufferAssignmentProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), logical_buffers_(arena), buffer_aliases_(arena), buffer_allocations_(arena), heap_simulator_traces_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAssignmentProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.BufferAssignmentProto) } BufferAssignmentProto::BufferAssignmentProto(const BufferAssignmentProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), logical_buffers_(from.logical_buffers_), buffer_aliases_(from.buffer_aliases_), buffer_allocations_(from.buffer_allocations_), heap_simulator_traces_(from.heap_simulator_traces_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:xla.BufferAssignmentProto) } void BufferAssignmentProto::SharedCtor() { } BufferAssignmentProto::~BufferAssignmentProto() { // @@protoc_insertion_point(destructor:xla.BufferAssignmentProto) SharedDtor(); } void BufferAssignmentProto::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void BufferAssignmentProto::ArenaDtor(void* object) { BufferAssignmentProto* _this = reinterpret_cast< BufferAssignmentProto* >(object); (void)_this; } void BufferAssignmentProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void BufferAssignmentProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* BufferAssignmentProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const BufferAssignmentProto& BufferAssignmentProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_BufferAssignmentProto.base); return *internal_default_instance(); } void BufferAssignmentProto::Clear() { // @@protoc_insertion_point(message_clear_start:xla.BufferAssignmentProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; logical_buffers_.Clear(); buffer_aliases_.Clear(); buffer_allocations_.Clear(); heap_simulator_traces_.Clear(); _internal_metadata_.Clear(); } bool BufferAssignmentProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.BufferAssignmentProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .xla.LogicalBufferProto logical_buffers = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_logical_buffers())); } else { goto handle_unusual; } break; } // repeated .xla.BufferAssignmentProto.BufferAlias buffer_aliases = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_buffer_aliases())); } else { goto handle_unusual; } break; } // repeated .xla.BufferAllocationProto buffer_allocations = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_buffer_allocations())); } else { goto handle_unusual; } break; } // repeated .xla.HeapSimulatorTrace heap_simulator_traces = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_heap_simulator_traces())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.BufferAssignmentProto) return true; failure: // @@protoc_insertion_point(parse_failure:xla.BufferAssignmentProto) return false; #undef DO_ } void BufferAssignmentProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.BufferAssignmentProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .xla.LogicalBufferProto logical_buffers = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->logical_buffers_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->logical_buffers(static_cast<int>(i)), output); } // repeated .xla.BufferAssignmentProto.BufferAlias buffer_aliases = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->buffer_aliases_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->buffer_aliases(static_cast<int>(i)), output); } // repeated .xla.BufferAllocationProto buffer_allocations = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->buffer_allocations_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->buffer_allocations(static_cast<int>(i)), output); } // repeated .xla.HeapSimulatorTrace heap_simulator_traces = 4; for (unsigned int i = 0, n = static_cast<unsigned int>(this->heap_simulator_traces_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->heap_simulator_traces(static_cast<int>(i)), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.BufferAssignmentProto) } ::google::protobuf::uint8* BufferAssignmentProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.BufferAssignmentProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .xla.LogicalBufferProto logical_buffers = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->logical_buffers_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, this->logical_buffers(static_cast<int>(i)), deterministic, target); } // repeated .xla.BufferAssignmentProto.BufferAlias buffer_aliases = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->buffer_aliases_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, this->buffer_aliases(static_cast<int>(i)), deterministic, target); } // repeated .xla.BufferAllocationProto buffer_allocations = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->buffer_allocations_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, this->buffer_allocations(static_cast<int>(i)), deterministic, target); } // repeated .xla.HeapSimulatorTrace heap_simulator_traces = 4; for (unsigned int i = 0, n = static_cast<unsigned int>(this->heap_simulator_traces_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 4, this->heap_simulator_traces(static_cast<int>(i)), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.BufferAssignmentProto) return target; } size_t BufferAssignmentProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.BufferAssignmentProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated .xla.LogicalBufferProto logical_buffers = 1; { unsigned int count = static_cast<unsigned int>(this->logical_buffers_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->logical_buffers(static_cast<int>(i))); } } // repeated .xla.BufferAssignmentProto.BufferAlias buffer_aliases = 2; { unsigned int count = static_cast<unsigned int>(this->buffer_aliases_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->buffer_aliases(static_cast<int>(i))); } } // repeated .xla.BufferAllocationProto buffer_allocations = 3; { unsigned int count = static_cast<unsigned int>(this->buffer_allocations_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->buffer_allocations(static_cast<int>(i))); } } // repeated .xla.HeapSimulatorTrace heap_simulator_traces = 4; { unsigned int count = static_cast<unsigned int>(this->heap_simulator_traces_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->heap_simulator_traces(static_cast<int>(i))); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BufferAssignmentProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.BufferAssignmentProto) GOOGLE_DCHECK_NE(&from, this); const BufferAssignmentProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const BufferAssignmentProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.BufferAssignmentProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.BufferAssignmentProto) MergeFrom(*source); } } void BufferAssignmentProto::MergeFrom(const BufferAssignmentProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.BufferAssignmentProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; logical_buffers_.MergeFrom(from.logical_buffers_); buffer_aliases_.MergeFrom(from.buffer_aliases_); buffer_allocations_.MergeFrom(from.buffer_allocations_); heap_simulator_traces_.MergeFrom(from.heap_simulator_traces_); } void BufferAssignmentProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.BufferAssignmentProto) if (&from == this) return; Clear(); MergeFrom(from); } void BufferAssignmentProto::CopyFrom(const BufferAssignmentProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.BufferAssignmentProto) if (&from == this) return; Clear(); MergeFrom(from); } bool BufferAssignmentProto::IsInitialized() const { return true; } void BufferAssignmentProto::Swap(BufferAssignmentProto* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { BufferAssignmentProto* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void BufferAssignmentProto::UnsafeArenaSwap(BufferAssignmentProto* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void BufferAssignmentProto::InternalSwap(BufferAssignmentProto* other) { using std::swap; CastToBase(&logical_buffers_)->InternalSwap(CastToBase(&other->logical_buffers_)); CastToBase(&buffer_aliases_)->InternalSwap(CastToBase(&other->buffer_aliases_)); CastToBase(&buffer_allocations_)->InternalSwap(CastToBase(&other->buffer_allocations_)); CastToBase(&heap_simulator_traces_)->InternalSwap(CastToBase(&other->heap_simulator_traces_)); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata BufferAssignmentProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void HloProto::InitAsDefaultInstance() { ::xla::_HloProto_default_instance_._instance.get_mutable()->hlo_module_ = const_cast< ::xla::HloModuleProto*>( ::xla::HloModuleProto::internal_default_instance()); ::xla::_HloProto_default_instance_._instance.get_mutable()->buffer_assignment_ = const_cast< ::xla::BufferAssignmentProto*>( ::xla::BufferAssignmentProto::internal_default_instance()); } void HloProto::unsafe_arena_set_allocated_hlo_module( ::xla::HloModuleProto* hlo_module) { if (GetArenaNoVirtual() == NULL) { delete hlo_module_; } hlo_module_ = hlo_module; if (hlo_module) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloProto.hlo_module) } void HloProto::unsafe_arena_set_allocated_buffer_assignment( ::xla::BufferAssignmentProto* buffer_assignment) { if (GetArenaNoVirtual() == NULL) { delete buffer_assignment_; } buffer_assignment_ = buffer_assignment; if (buffer_assignment) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloProto.buffer_assignment) } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HloProto::kHloModuleFieldNumber; const int HloProto::kBufferAssignmentFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HloProto::HloProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.HloProto) } HloProto::HloProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.HloProto) } HloProto::HloProto(const HloProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_hlo_module()) { hlo_module_ = new ::xla::HloModuleProto(*from.hlo_module_); } else { hlo_module_ = NULL; } if (from.has_buffer_assignment()) { buffer_assignment_ = new ::xla::BufferAssignmentProto(*from.buffer_assignment_); } else { buffer_assignment_ = NULL; } // @@protoc_insertion_point(copy_constructor:xla.HloProto) } void HloProto::SharedCtor() { ::memset(&hlo_module_, 0, static_cast<size_t>( reinterpret_cast<char*>(&buffer_assignment_) - reinterpret_cast<char*>(&hlo_module_)) + sizeof(buffer_assignment_)); } HloProto::~HloProto() { // @@protoc_insertion_point(destructor:xla.HloProto) SharedDtor(); } void HloProto::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); if (this != internal_default_instance()) delete hlo_module_; if (this != internal_default_instance()) delete buffer_assignment_; } void HloProto::ArenaDtor(void* object) { HloProto* _this = reinterpret_cast< HloProto* >(object); (void)_this; } void HloProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void HloProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HloProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HloProto& HloProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloProto.base); return *internal_default_instance(); } void HloProto::Clear() { // @@protoc_insertion_point(message_clear_start:xla.HloProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (GetArenaNoVirtual() == NULL && hlo_module_ != NULL) { delete hlo_module_; } hlo_module_ = NULL; if (GetArenaNoVirtual() == NULL && buffer_assignment_ != NULL) { delete buffer_assignment_; } buffer_assignment_ = NULL; _internal_metadata_.Clear(); } bool HloProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.HloProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // .xla.HloModuleProto hlo_module = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_hlo_module())); } else { goto handle_unusual; } break; } // .xla.BufferAssignmentProto buffer_assignment = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_buffer_assignment())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.HloProto) return true; failure: // @@protoc_insertion_point(parse_failure:xla.HloProto) return false; #undef DO_ } void HloProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.HloProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .xla.HloModuleProto hlo_module = 1; if (this->has_hlo_module()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->_internal_hlo_module(), output); } // .xla.BufferAssignmentProto buffer_assignment = 3; if (this->has_buffer_assignment()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->_internal_buffer_assignment(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.HloProto) } ::google::protobuf::uint8* HloProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.HloProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .xla.HloModuleProto hlo_module = 1; if (this->has_hlo_module()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, this->_internal_hlo_module(), deterministic, target); } // .xla.BufferAssignmentProto buffer_assignment = 3; if (this->has_buffer_assignment()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, this->_internal_buffer_assignment(), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.HloProto) return target; } size_t HloProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.HloProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // .xla.HloModuleProto hlo_module = 1; if (this->has_hlo_module()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *hlo_module_); } // .xla.BufferAssignmentProto buffer_assignment = 3; if (this->has_buffer_assignment()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *buffer_assignment_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HloProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.HloProto) GOOGLE_DCHECK_NE(&from, this); const HloProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const HloProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.HloProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.HloProto) MergeFrom(*source); } } void HloProto::MergeFrom(const HloProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.HloProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.has_hlo_module()) { mutable_hlo_module()->::xla::HloModuleProto::MergeFrom(from.hlo_module()); } if (from.has_buffer_assignment()) { mutable_buffer_assignment()->::xla::BufferAssignmentProto::MergeFrom(from.buffer_assignment()); } } void HloProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.HloProto) if (&from == this) return; Clear(); MergeFrom(from); } void HloProto::CopyFrom(const HloProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.HloProto) if (&from == this) return; Clear(); MergeFrom(from); } bool HloProto::IsInitialized() const { return true; } void HloProto::Swap(HloProto* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { HloProto* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void HloProto::UnsafeArenaSwap(HloProto* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void HloProto::InternalSwap(HloProto* other) { using std::swap; swap(hlo_module_, other->hlo_module_); swap(buffer_assignment_, other->buffer_assignment_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HloProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void HloSnapshot::InitAsDefaultInstance() { ::xla::_HloSnapshot_default_instance_._instance.get_mutable()->hlo_ = const_cast< ::xla::HloProto*>( ::xla::HloProto::internal_default_instance()); ::xla::_HloSnapshot_default_instance_._instance.get_mutable()->result_ = const_cast< ::xla::LiteralProto*>( ::xla::LiteralProto::internal_default_instance()); } void HloSnapshot::unsafe_arena_set_allocated_hlo( ::xla::HloProto* hlo) { if (GetArenaNoVirtual() == NULL) { delete hlo_; } hlo_ = hlo; if (hlo) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloSnapshot.hlo) } void HloSnapshot::clear_arguments() { arguments_.Clear(); } void HloSnapshot::unsafe_arena_set_allocated_result( ::xla::LiteralProto* result) { if (GetArenaNoVirtual() == NULL) { delete result_; } result_ = result; if (result) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloSnapshot.result) } void HloSnapshot::clear_result() { if (GetArenaNoVirtual() == NULL && result_ != NULL) { delete result_; } result_ = NULL; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HloSnapshot::kHloFieldNumber; const int HloSnapshot::kArgumentsFieldNumber; const int HloSnapshot::kResultFieldNumber; const int HloSnapshot::kExecutionPlatformFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HloSnapshot::HloSnapshot() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloSnapshot.base); SharedCtor(); // @@protoc_insertion_point(constructor:xla.HloSnapshot) } HloSnapshot::HloSnapshot(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), arguments_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloSnapshot.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:xla.HloSnapshot) } HloSnapshot::HloSnapshot(const HloSnapshot& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), arguments_(from.arguments_) { _internal_metadata_.MergeFrom(from._internal_metadata_); execution_platform_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.execution_platform().size() > 0) { execution_platform_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.execution_platform(), GetArenaNoVirtual()); } if (from.has_hlo()) { hlo_ = new ::xla::HloProto(*from.hlo_); } else { hlo_ = NULL; } if (from.has_result()) { result_ = new ::xla::LiteralProto(*from.result_); } else { result_ = NULL; } // @@protoc_insertion_point(copy_constructor:xla.HloSnapshot) } void HloSnapshot::SharedCtor() { execution_platform_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&hlo_, 0, static_cast<size_t>( reinterpret_cast<char*>(&result_) - reinterpret_cast<char*>(&hlo_)) + sizeof(result_)); } HloSnapshot::~HloSnapshot() { // @@protoc_insertion_point(destructor:xla.HloSnapshot) SharedDtor(); } void HloSnapshot::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); execution_platform_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete hlo_; if (this != internal_default_instance()) delete result_; } void HloSnapshot::ArenaDtor(void* object) { HloSnapshot* _this = reinterpret_cast< HloSnapshot* >(object); (void)_this; } void HloSnapshot::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void HloSnapshot::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HloSnapshot::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HloSnapshot& HloSnapshot::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::scc_info_HloSnapshot.base); return *internal_default_instance(); } void HloSnapshot::Clear() { // @@protoc_insertion_point(message_clear_start:xla.HloSnapshot) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; arguments_.Clear(); execution_platform_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); if (GetArenaNoVirtual() == NULL && hlo_ != NULL) { delete hlo_; } hlo_ = NULL; if (GetArenaNoVirtual() == NULL && result_ != NULL) { delete result_; } result_ = NULL; _internal_metadata_.Clear(); } bool HloSnapshot::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:xla.HloSnapshot) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // .xla.HloProto hlo = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_hlo())); } else { goto handle_unusual; } break; } // repeated .xla.LiteralProto arguments = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_arguments())); } else { goto handle_unusual; } break; } // .xla.LiteralProto result = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_result())); } else { goto handle_unusual; } break; } // string execution_platform = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_execution_platform())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->execution_platform().data(), static_cast<int>(this->execution_platform().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "xla.HloSnapshot.execution_platform")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:xla.HloSnapshot) return true; failure: // @@protoc_insertion_point(parse_failure:xla.HloSnapshot) return false; #undef DO_ } void HloSnapshot::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:xla.HloSnapshot) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .xla.HloProto hlo = 1; if (this->has_hlo()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->_internal_hlo(), output); } // repeated .xla.LiteralProto arguments = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->arguments_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->arguments(static_cast<int>(i)), output); } // .xla.LiteralProto result = 3; if (this->has_result()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->_internal_result(), output); } // string execution_platform = 4; if (this->execution_platform().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->execution_platform().data(), static_cast<int>(this->execution_platform().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloSnapshot.execution_platform"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 4, this->execution_platform(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:xla.HloSnapshot) } ::google::protobuf::uint8* HloSnapshot::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:xla.HloSnapshot) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .xla.HloProto hlo = 1; if (this->has_hlo()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, this->_internal_hlo(), deterministic, target); } // repeated .xla.LiteralProto arguments = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->arguments_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, this->arguments(static_cast<int>(i)), deterministic, target); } // .xla.LiteralProto result = 3; if (this->has_result()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, this->_internal_result(), deterministic, target); } // string execution_platform = 4; if (this->execution_platform().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->execution_platform().data(), static_cast<int>(this->execution_platform().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "xla.HloSnapshot.execution_platform"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 4, this->execution_platform(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:xla.HloSnapshot) return target; } size_t HloSnapshot::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:xla.HloSnapshot) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated .xla.LiteralProto arguments = 2; { unsigned int count = static_cast<unsigned int>(this->arguments_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->arguments(static_cast<int>(i))); } } // string execution_platform = 4; if (this->execution_platform().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->execution_platform()); } // .xla.HloProto hlo = 1; if (this->has_hlo()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *hlo_); } // .xla.LiteralProto result = 3; if (this->has_result()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *result_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HloSnapshot::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:xla.HloSnapshot) GOOGLE_DCHECK_NE(&from, this); const HloSnapshot* source = ::google::protobuf::internal::DynamicCastToGenerated<const HloSnapshot>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:xla.HloSnapshot) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:xla.HloSnapshot) MergeFrom(*source); } } void HloSnapshot::MergeFrom(const HloSnapshot& from) { // @@protoc_insertion_point(class_specific_merge_from_start:xla.HloSnapshot) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; arguments_.MergeFrom(from.arguments_); if (from.execution_platform().size() > 0) { set_execution_platform(from.execution_platform()); } if (from.has_hlo()) { mutable_hlo()->::xla::HloProto::MergeFrom(from.hlo()); } if (from.has_result()) { mutable_result()->::xla::LiteralProto::MergeFrom(from.result()); } } void HloSnapshot::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:xla.HloSnapshot) if (&from == this) return; Clear(); MergeFrom(from); } void HloSnapshot::CopyFrom(const HloSnapshot& from) { // @@protoc_insertion_point(class_specific_copy_from_start:xla.HloSnapshot) if (&from == this) return; Clear(); MergeFrom(from); } bool HloSnapshot::IsInitialized() const { return true; } void HloSnapshot::Swap(HloSnapshot* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { HloSnapshot* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void HloSnapshot::UnsafeArenaSwap(HloSnapshot* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void HloSnapshot::InternalSwap(HloSnapshot* other) { using std::swap; CastToBase(&arguments_)->InternalSwap(CastToBase(&other->arguments_)); execution_platform_.Swap(&other->execution_platform_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(hlo_, other->hlo_); swap(result_, other->result_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HloSnapshot::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcompiler_2fxla_2fservice_2fhlo_2eproto::file_level_metadata[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) } // namespace xla namespace google { namespace protobuf { template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HloInstructionProto_SliceDimensions* Arena::CreateMaybeMessage< ::xla::HloInstructionProto_SliceDimensions >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HloInstructionProto_SliceDimensions >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HloInstructionProto* Arena::CreateMaybeMessage< ::xla::HloInstructionProto >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HloInstructionProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HloComputationProto* Arena::CreateMaybeMessage< ::xla::HloComputationProto >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HloComputationProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HloScheduleProto_InstructionSequence* Arena::CreateMaybeMessage< ::xla::HloScheduleProto_InstructionSequence >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HloScheduleProto_InstructionSequence >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HloScheduleProto_SequencesEntry_DoNotUse* Arena::CreateMaybeMessage< ::xla::HloScheduleProto_SequencesEntry_DoNotUse >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HloScheduleProto_SequencesEntry_DoNotUse >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HloScheduleProto* Arena::CreateMaybeMessage< ::xla::HloScheduleProto >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HloScheduleProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HloInputOutputAliasProto_AliasEntryProto* Arena::CreateMaybeMessage< ::xla::HloInputOutputAliasProto_AliasEntryProto >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HloInputOutputAliasProto_AliasEntryProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HloInputOutputAliasProto* Arena::CreateMaybeMessage< ::xla::HloInputOutputAliasProto >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HloInputOutputAliasProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::DynamicParameterBindingProto_Binding* Arena::CreateMaybeMessage< ::xla::DynamicParameterBindingProto_Binding >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::DynamicParameterBindingProto_Binding >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::DynamicParameterBindingProto* Arena::CreateMaybeMessage< ::xla::DynamicParameterBindingProto >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::DynamicParameterBindingProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HloModuleProto* Arena::CreateMaybeMessage< ::xla::HloModuleProto >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HloModuleProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::LogicalBufferProto_Location* Arena::CreateMaybeMessage< ::xla::LogicalBufferProto_Location >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::LogicalBufferProto_Location >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::LogicalBufferProto* Arena::CreateMaybeMessage< ::xla::LogicalBufferProto >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::LogicalBufferProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::BufferAllocationProto_Assigned* Arena::CreateMaybeMessage< ::xla::BufferAllocationProto_Assigned >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::BufferAllocationProto_Assigned >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::BufferAllocationProto* Arena::CreateMaybeMessage< ::xla::BufferAllocationProto >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::BufferAllocationProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HeapSimulatorTrace_Event* Arena::CreateMaybeMessage< ::xla::HeapSimulatorTrace_Event >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HeapSimulatorTrace_Event >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HeapSimulatorTrace* Arena::CreateMaybeMessage< ::xla::HeapSimulatorTrace >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HeapSimulatorTrace >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HloModuleGroupProto* Arena::CreateMaybeMessage< ::xla::HloModuleGroupProto >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HloModuleGroupProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::BufferAssignmentProto_BufferAlias* Arena::CreateMaybeMessage< ::xla::BufferAssignmentProto_BufferAlias >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::BufferAssignmentProto_BufferAlias >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::BufferAssignmentProto* Arena::CreateMaybeMessage< ::xla::BufferAssignmentProto >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::BufferAssignmentProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HloProto* Arena::CreateMaybeMessage< ::xla::HloProto >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HloProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::xla::HloSnapshot* Arena::CreateMaybeMessage< ::xla::HloSnapshot >(Arena* arena) { return Arena::CreateMessageInternal< ::xla::HloSnapshot >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope)
41.81649
196
0.720469
[ "object", "shape" ]
d742e685da8e4ab009b60f6756209c9228d8baa6
15,696
cpp
C++
src/gui_texture.cpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
50
2015-01-15T10:00:31.000Z
2022-02-04T20:45:25.000Z
src/gui_texture.cpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
88
2020-03-15T17:40:04.000Z
2022-03-15T08:21:44.000Z
src/gui_texture.cpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
19
2017-03-11T04:32:01.000Z
2022-01-12T22:47:12.000Z
#include "lxgui/gui_texture.hpp" #include "lxgui/gui_layeredregion.hpp" #include "lxgui/gui_renderer.hpp" #include "lxgui/gui_rendertarget.hpp" #include "lxgui/gui_material.hpp" #include "lxgui/gui_manager.hpp" #include "lxgui/gui_out.hpp" #include "lxgui/gui_uiobject_tpl.hpp" #include <lxgui/utils_filesystem.hpp> #include <sstream> namespace lxgui { namespace gui { texture::texture(manager& mManager) : layered_region(mManager) { lType_.push_back(CLASS_NAME); } std::string texture::serialize(const std::string& sTab) const { std::ostringstream sStr; sStr << layered_region::serialize(sTab); std::visit([&](const auto& mData) { using content_type = std::decay_t<decltype(mData)>; if constexpr (std::is_same_v<content_type, std::string>) { sStr << sTab << " # File : " << mData << "\n"; } else if constexpr (std::is_same_v<content_type, gradient>) { sStr << sTab << " # Gradient :\n"; sStr << sTab << " #-###\n"; sStr << sTab << " | # min color : " << mData.get_min_color() << "\n"; sStr << sTab << " | # max color : " << mData.get_max_color() << "\n"; sStr << sTab << " | # orientation : "; switch (mData.get_orientation()) { case gradient::orientation::HORIZONTAL : sStr << "HORIZONTAL\n"; break; case gradient::orientation::VERTICAL : sStr << "VERTICAL\n"; break; default : sStr << "<error>\n"; break; } sStr << sTab << " #-###\n"; } else if constexpr (std::is_same_v<content_type, color>) { sStr << sTab << " # Color : " << mData << "\n"; } }, mContent_); sStr << sTab << " # Tex. coord. :\n"; sStr << sTab << " #-###\n"; sStr << sTab << " | # top-left : (" << mQuad_.v[0].uvs << ")\n"; sStr << sTab << " | # top-right : (" << mQuad_.v[1].uvs << ")\n"; sStr << sTab << " | # bottom-right : (" << mQuad_.v[2].uvs << ")\n"; sStr << sTab << " | # bottom-left : (" << mQuad_.v[3].uvs << ")\n"; sStr << sTab << " #-###\n"; sStr << sTab << " # TexCModRect : " << bTexCoordModifiesRect_ << "\n"; sStr << sTab << " # Blend mode : "; switch (mBlendMode_) { case blend_mode::NONE : sStr << "NONE\n"; break; case blend_mode::BLEND : sStr << "BLEND\n"; break; case blend_mode::KEY : sStr << "KEY\n"; break; case blend_mode::ADD : sStr << "ADD\n"; break; case blend_mode::MOD : sStr << "MOD\n"; break; default : sStr << "<error>\n"; break; } sStr << sTab << " # Filter : "; switch (mFilter_) { case material::filter::NONE : sStr << "NONE\n"; break; case material::filter::LINEAR : sStr << "LINEAR\n"; break; default : sStr << "<error>\n"; break; } sStr << sTab << " # Desaturated : " << bIsDesaturated_ << "\n"; return sStr.str(); } void texture::render() const { if (is_visible()) { const auto& mRenderer = get_manager().get_renderer(); float fAlpha = get_effective_alpha(); if (fAlpha != 1.0f) { quad mBlendedQuad = mQuad_; for (std::size_t i = 0; i < 4; ++i) mBlendedQuad.v[i].col.a *= fAlpha; mRenderer.render_quad(mBlendedQuad); } else { mRenderer.render_quad(mQuad_); } } } void texture::create_glue() { create_glue_(this); } void texture::copy_from(const uiobject& mObj) { uiobject::copy_from(mObj); const texture* pTexture = down_cast<texture>(&mObj); if (!pTexture) return; if (pTexture->has_texture_file()) this->set_texture(pTexture->get_texture_file()); else if (pTexture->has_gradient()) this->set_gradient(pTexture->get_gradient()); else if (pTexture->has_solid_color()) this->set_solid_color(pTexture->get_solid_color()); this->set_blend_mode(pTexture->get_blend_mode()); this->set_tex_coord(pTexture->get_tex_coord()); this->set_tex_coord_modifies_rect(pTexture->get_tex_coord_modifies_rect()); this->set_desaturated(pTexture->is_desaturated()); } texture::blend_mode texture::get_blend_mode() const { return mBlendMode_; } material::filter texture::get_filter_mode() const { return mFilter_; } bool texture::has_solid_color() const { return std::holds_alternative<color>(mContent_); } const color& texture::get_solid_color() const { return std::get<color>(mContent_); } bool texture::has_gradient() const { return std::holds_alternative<gradient>(mContent_); } const gradient& texture::get_gradient() const { return std::get<gradient>(mContent_); } std::array<float,8> texture::get_tex_coord() const { std::array<float,8> mCoords{}; if (mQuad_.mat) { for (std::size_t i = 0; i < 4; ++i) { const vector2f lUV = mQuad_.mat->get_local_uv(mQuad_.v[i].uvs, true); mCoords[2*i+0] = lUV.x; mCoords[2*i+1] = lUV.y; } } else { for (std::size_t i = 0; i < 4; ++i) { mCoords[2*i+0] = mQuad_.v[i].uvs.x; mCoords[2*i+1] = mQuad_.v[i].uvs.y; } } return mCoords; } bool texture::get_tex_coord_modifies_rect() const { return bTexCoordModifiesRect_; } bool texture::has_texture_file() const { return std::holds_alternative<std::string>(mContent_); } const std::string& texture::get_texture_file() const { return std::get<std::string>(mContent_); } color texture::get_vertex_color(std::size_t uiIndex) const { if (uiIndex >= 4) { gui::out << gui::error << "gui::" << lType_.back() << " : " << "Vertex index out of bound (" << uiIndex << ")." << std::endl; return color::WHITE; } return mQuad_.v[uiIndex].col; } bool texture::is_desaturated() const { return bIsDesaturated_; } void texture::set_blend_mode(blend_mode mBlendMode) { if (mBlendMode != blend_mode::BLEND) { gui::out << gui::warning << "gui::" << lType_.back() << " : " << "texture::set_blend_mode other than \"BLEND\" is not yet implemented." << std::endl; return; } if (mBlendMode_ == mBlendMode) return; mBlendMode_ = mBlendMode; notify_renderer_need_redraw(); } void texture::set_blend_mode(const std::string& sBlendMode) { blend_mode mNewBlendMode = blend_mode::BLEND; if (sBlendMode == "BLEND") mBlendMode_ = blend_mode::BLEND; else if (sBlendMode == "ADD") mBlendMode_ = blend_mode::ADD; else if (sBlendMode == "MOD") mBlendMode_ = blend_mode::MOD; else if (sBlendMode == "KEY") mBlendMode_ = blend_mode::KEY; else if (sBlendMode == "NONE") mBlendMode_ = blend_mode::NONE; else { gui::out << gui::warning << "gui::" << lType_.back() << " : " << "Unknown blending : \"" << sBlendMode << "\". Using \"BLEND\"." << std::endl; } set_blend_mode(mNewBlendMode); } void texture::set_filter_mode(material::filter mFilter) { if (mFilter_ == mFilter) return; mFilter_ = mFilter; if (std::holds_alternative<std::string>(mContent_)) { // Force re-load of the material std::string sFileName = std::get<std::string>(mContent_); mContent_ = std::string{}; set_texture(sFileName); } } void texture::set_filter_mode(const std::string& sFilter) { material::filter mNewFilter = material::filter::NONE; if (sFilter == "NONE") mNewFilter = material::filter::NONE; else if (sFilter == "LINEAR") mNewFilter = material::filter::LINEAR; else { gui::out << gui::warning << "gui::" << lType_.back() << " : " << "Unknown filtering : \"" << sFilter << "\". Using \"NONE\"." << std::endl; } set_filter_mode(mNewFilter); } void texture::set_desaturated(bool bIsDesaturated) { if (bIsDesaturated_ == bIsDesaturated) return; bIsDesaturated_ = bIsDesaturated; if (bIsDesaturated) { gui::out << gui::warning << "gui::" << lType_.back() << " : " << "Texture de-saturation is not yet implemented." << std::endl; } notify_renderer_need_redraw(); } void texture::set_gradient(const gradient& mGradient) { mContent_ = mGradient; mQuad_.mat = nullptr; if (mGradient.get_orientation() == gradient::orientation::HORIZONTAL) { mQuad_.v[0].col = mGradient.get_min_color(); mQuad_.v[1].col = mGradient.get_max_color(); mQuad_.v[2].col = mGradient.get_max_color(); mQuad_.v[3].col = mGradient.get_min_color(); } else { mQuad_.v[0].col = mGradient.get_min_color(); mQuad_.v[1].col = mGradient.get_min_color(); mQuad_.v[2].col = mGradient.get_max_color(); mQuad_.v[3].col = mGradient.get_max_color(); } notify_renderer_need_redraw(); } void texture::set_tex_rect(const std::array<float,4>& lTextureRect) { if (mQuad_.mat) { mQuad_.v[0].uvs = mQuad_.mat->get_canvas_uv(vector2f(lTextureRect[0], lTextureRect[1]), true); mQuad_.v[1].uvs = mQuad_.mat->get_canvas_uv(vector2f(lTextureRect[2], lTextureRect[1]), true); mQuad_.v[2].uvs = mQuad_.mat->get_canvas_uv(vector2f(lTextureRect[2], lTextureRect[3]), true); mQuad_.v[3].uvs = mQuad_.mat->get_canvas_uv(vector2f(lTextureRect[0], lTextureRect[3]), true); if (bTexCoordModifiesRect_) update_dimensions_from_tex_coord_(); } else { mQuad_.v[0].uvs = vector2f(lTextureRect[0], lTextureRect[1]); mQuad_.v[1].uvs = vector2f(lTextureRect[2], lTextureRect[1]); mQuad_.v[2].uvs = vector2f(lTextureRect[2], lTextureRect[3]); mQuad_.v[3].uvs = vector2f(lTextureRect[0], lTextureRect[3]); } notify_renderer_need_redraw(); } void texture::set_tex_coord(const std::array<float,8>& lTextureCoords) { if (mQuad_.mat) { mQuad_.v[0].uvs = mQuad_.mat->get_canvas_uv(vector2f(lTextureCoords[0], lTextureCoords[1]), true); mQuad_.v[1].uvs = mQuad_.mat->get_canvas_uv(vector2f(lTextureCoords[2], lTextureCoords[3]), true); mQuad_.v[2].uvs = mQuad_.mat->get_canvas_uv(vector2f(lTextureCoords[4], lTextureCoords[5]), true); mQuad_.v[3].uvs = mQuad_.mat->get_canvas_uv(vector2f(lTextureCoords[6], lTextureCoords[7]), true); if (bTexCoordModifiesRect_) update_dimensions_from_tex_coord_(); } else { mQuad_.v[0].uvs = vector2f(lTextureCoords[0], lTextureCoords[1]); mQuad_.v[1].uvs = vector2f(lTextureCoords[2], lTextureCoords[3]); mQuad_.v[2].uvs = vector2f(lTextureCoords[4], lTextureCoords[5]); mQuad_.v[3].uvs = vector2f(lTextureCoords[6], lTextureCoords[7]); } notify_renderer_need_redraw(); } void texture::set_tex_coord_modifies_rect(bool bTexCoordModifiesRect) { if (bTexCoordModifiesRect_ != bTexCoordModifiesRect) { bTexCoordModifiesRect_ = bTexCoordModifiesRect; if (bTexCoordModifiesRect_ && mQuad_.mat) update_dimensions_from_tex_coord_(); } } void texture::update_dimensions_from_tex_coord_() { vector2f mExtent = mQuad_.v[2].uvs - mQuad_.v[0].uvs; set_dimensions(mExtent*vector2f(mQuad_.mat->get_canvas_dimensions())); } void texture::set_texture(const std::string& sFile) { mContent_ = sFile; if (sFile.empty()) return; auto& mRenderer = get_manager().get_renderer(); std::shared_ptr<gui::material> pMat; if (utils::file_exists(sFile)) pMat = mRenderer.create_atlas_material("GUI", sFile, mFilter_); mQuad_.mat = pMat; if (pMat) { mQuad_.v[0].uvs = mQuad_.mat->get_canvas_uv(vector2f(0, 0), true); mQuad_.v[1].uvs = mQuad_.mat->get_canvas_uv(vector2f(1, 0), true); mQuad_.v[2].uvs = mQuad_.mat->get_canvas_uv(vector2f(1, 1), true); mQuad_.v[3].uvs = mQuad_.mat->get_canvas_uv(vector2f(0, 1), true); if (!is_apparent_width_defined()) set_width(mQuad_.mat->get_rect().width()); if (!is_apparent_height_defined()) set_height(mQuad_.mat->get_rect().height()); } else { gui::out << gui::error << "gui::" << lType_.back() << " : " << "Cannot load file \"" << sFile << "\" for \"" << sName_ << "\".\nUsing white texture instead." << std::endl; } notify_renderer_need_redraw(); } void texture::set_texture(std::shared_ptr<render_target> pRenderTarget) { mContent_ = std::string{}; auto& mRenderer = get_manager().get_renderer(); std::shared_ptr<gui::material> pMat; if (pRenderTarget) pMat = mRenderer.create_material(pRenderTarget); mQuad_.mat = pMat; if (pMat) { mQuad_.v[0].uvs = mQuad_.mat->get_canvas_uv(vector2f(0, 0), true); mQuad_.v[1].uvs = mQuad_.mat->get_canvas_uv(vector2f(1, 0), true); mQuad_.v[2].uvs = mQuad_.mat->get_canvas_uv(vector2f(1, 1), true); mQuad_.v[3].uvs = mQuad_.mat->get_canvas_uv(vector2f(0, 1), true); if (!is_apparent_width_defined()) set_width(mQuad_.mat->get_rect().width()); if (!is_apparent_height_defined()) set_height(mQuad_.mat->get_rect().height()); } else { gui::out << gui::error << "gui::" << lType_.back() << " : " << "Cannot create a texture from render target.\n" "Using white texture instead." << std::endl; } notify_renderer_need_redraw(); } void texture::set_solid_color(const color& mColor) { mContent_ = mColor; mQuad_.mat = nullptr; mQuad_.v[0].col = mColor; mQuad_.v[1].col = mColor; mQuad_.v[2].col = mColor; mQuad_.v[3].col = mColor; notify_renderer_need_redraw(); } void texture::set_quad(const quad& mQuad) { mContent_ = std::string{}; mQuad_ = mQuad; vector2f mExtent = mQuad_.v[2].pos - mQuad_.v[0].pos; set_dimensions(mExtent); notify_renderer_need_redraw(); } void texture::set_vertex_color(const color& mColor, std::size_t uiIndex) { if (uiIndex == std::numeric_limits<std::size_t>::max()) { for (std::size_t i = 0; i < 4; ++i) mQuad_.v[i].col = mColor; notify_renderer_need_redraw(); return; } if (uiIndex >= 4) { gui::out << gui::error << "gui::" << lType_.back() << " : " << "Vertex index out of bound (" << uiIndex << ")." << std::endl; return; } mQuad_.v[uiIndex].col = mColor; notify_renderer_need_redraw(); } void texture::update_borders_() const { bool bBordersUpdated = bUpdateBorders_; layered_region::update_borders_(); if (bBordersUpdated) { mQuad_.v[0].pos = lBorderList_.top_left(); mQuad_.v[1].pos = lBorderList_.top_right(); mQuad_.v[2].pos = lBorderList_.bottom_right(); mQuad_.v[3].pos = lBorderList_.bottom_left(); } } } }
29.338318
107
0.573076
[ "render" ]
d748faf0f1b66b2571053624c7aa3e70dd7118a5
34,437
hpp
C++
blast/include/util/compress/tar.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/include/util/compress/tar.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/include/util/compress/tar.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
#ifndef UTIL_COMPRESS__TAR__HPP #define UTIL_COMPRESS__TAR__HPP /* $Id: tar.hpp 587245 2019-05-31 23:39:51Z lavr $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors: Vladimir Ivanov * Anton Lavrentiev * * File Description: * Tar archive API */ /// @file /// Tar archive API. /// /// Supports subsets of POSIX.1-1988 (ustar), POSIX 1003.1-2001 (posix), old /// GNU (POSIX 1003.1), and V7 formats (all partially but reasonably). New /// archives are created using POSIX (genuine ustar) format, using GNU /// extensions for long names/links only when unavoidable. It cannot, /// however, handle all the exotics like sparse files (except for GNU/1.0 /// sparse PAX extension) and contiguous files (yet still can work around both /// of them gracefully, if needed), multivolume / incremental archives, etc. /// but just regular files, devices (character or block), FIFOs, directories, /// and limited links: can extract both hard- and symlinks, but can store /// symlinks only. Also, this implementation is only minimally PAX(Portable /// Archive eXchange)-aware for file extractions (and does not yet use any PAX /// extensions to store the files). /// #include <corelib/ncbifile.hpp> #include <utility> /** @addtogroup Compression * * @{ */ BEGIN_NCBI_SCOPE ///////////////////////////////////////////////////////////////////////////// /// /// TTarMode -- /// /// Permission bits as defined in tar /// enum ETarModeBits { // Special mode bits fTarSetUID = 04000, ///< set UID on execution fTarSetGID = 02000, ///< set GID on execution fTarSticky = 01000, ///< reserved (sticky bit) // File permissions fTarURead = 00400, ///< read by owner fTarUWrite = 00200, ///< write by owner fTarUExecute = 00100, ///< execute/search by owner fTarGRead = 00040, ///< read by group fTarGWrite = 00020, ///< write by group fTarGExecute = 00010, ///< execute/search by group fTarORead = 00004, ///< read by other fTarOWrite = 00002, ///< write by other fTarOExecute = 00001 ///< execute/search by other }; typedef unsigned int TTarMode; ///< Bitwise OR of ETarModeBits ///////////////////////////////////////////////////////////////////////////// /// /// CTarException -- /// /// Define exceptions generated by the API. /// Exception text may include detailed dump of a tar header (when appropriate) /// if fDumpEntryHeaders is set in the archive flags. /// /// CTarException inherits its basic functionality from CCoreException /// and defines additional error codes for tar archive operations. /// /// @sa /// CTar::SetFlags class NCBI_XUTIL_EXPORT CTarException : public CCoreException { public: /// Error types that file operations can generate. enum EErrCode { eUnsupportedTarFormat, eUnsupportedEntryType, eUnsupportedSource, eNameTooLong, eChecksum, eBadName, eCreate, eOpen, eRead, eWrite, eBackup, eMemory, eRestoreAttrs }; /// Translate from an error code value to its string representation. virtual const char* GetErrCodeString(void) const override { switch (GetErrCode()) { case eUnsupportedTarFormat: return "eUnsupportedTarFormat"; case eUnsupportedEntryType: return "eUnsupportedEntryType"; case eUnsupportedSource: return "eUnsupportedSource"; case eNameTooLong: return "eNameTooLong"; case eChecksum: return "eChecksum"; case eBadName: return "eBadName"; case eCreate: return "eCreate"; case eOpen: return "eOpen"; case eRead: return "eRead"; case eWrite: return "eWrite"; case eBackup: return "eBackup"; case eMemory: return "eMemory"; case eRestoreAttrs: return "eRestoreAttrs"; default: return CException::GetErrCodeString(); } } // Standard exception boilerplate code. NCBI_EXCEPTION_DEFAULT(CTarException, CCoreException); }; ////////////////////////////////////////////////////////////////////////////// /// /// CTarEntryInfo class /// /// Information about a tar archive entry. class NCBI_XUTIL_EXPORT CTarEntryInfo { public: /// Archive entry type. enum EType { eFile = CDirEntry::eFile, ///< Regular file eDir = CDirEntry::eDir, ///< Directory eSymLink = CDirEntry::eSymLink, ///< Symbolic link ePipe = CDirEntry::ePipe, ///< Pipe (FIFO) eCharDev = CDirEntry::eCharSpecial, ///< Character device eBlockDev = CDirEntry::eBlockSpecial, ///< Block device eUnknown = CDirEntry::eUnknown, ///< Unknown type eHardLink, ///< Hard link eVolHeader, ///< Volume header ePAXHeader, ///< PAX extended header eSparseFile, ///< GNU/STAR sparse file eGNULongName, ///< GNU long name eGNULongLink ///< GNU long link }; /// Position type. enum EPos { ePos_Header, ePos_Data }; // No setters -- they are not needed for access by the user, and thus are // done directly from CTar for the sake of performance and code clarity. // Getters only! EType GetType(void) const { return m_Type; } const string& GetName(void) const { return m_Name; } const string& GetLinkName(void) const { return m_LinkName; } const string& GetUserName(void) const { return m_UserName; } const string& GetGroupName(void) const { return m_GroupName; } time_t GetModificationTime(void) const { return m_Stat.orig.st_mtime; } CTime GetModificationCTime(void) const { CTime mtime(m_Stat.orig.st_mtime); mtime.SetNanoSecond(m_Stat.mtime_nsec); return mtime; } time_t GetLastAccessTime(void) const { return m_Stat.orig.st_atime; } CTime GetLastAccessCTime(void) const { CTime atime(m_Stat.orig.st_atime); atime.SetNanoSecond(m_Stat.atime_nsec); return atime; } time_t GetCreationTime(void) const { return m_Stat.orig.st_ctime; } CTime GetCreationCTime(void) const { CTime ctime(m_Stat.orig.st_ctime); ctime.SetNanoSecond(m_Stat.ctime_nsec); return ctime; } Uint8 GetSize(void) const { return m_Stat.orig.st_size; } TTarMode GetMode(void) const;// Raw mode as stored in tar void GetMode(CDirEntry::TMode* user_mode, CDirEntry::TMode* group_mode = 0, CDirEntry::TMode* other_mode = 0, CDirEntry::TSpecialModeBits* special_bits = 0) const; unsigned int GetMajor(void) const; unsigned int GetMinor(void) const; unsigned int GetUserId(void) const { return m_Stat.orig.st_uid; } unsigned int GetGroupId(void) const { return m_Stat.orig.st_gid; } Uint8 GetPosition(EPos which) const { return which == ePos_Header ? m_Pos : m_Pos + m_HeaderSize; } // Comparison operator. bool operator == (const CTarEntryInfo& info) const { return (m_Type == info.m_Type && m_Name == info.m_Name && m_LinkName == info.m_LinkName && m_UserName == info.m_UserName && m_GroupName == info.m_GroupName && m_HeaderSize == info.m_HeaderSize && memcmp(&m_Stat,&info.m_Stat, sizeof(m_Stat)) == 0 && m_Pos == info.m_Pos ? true : false); } protected: // Constructor. CTarEntryInfo(Uint8 pos = 0) : m_Type(eUnknown), m_HeaderSize(0), m_Pos(pos) { memset(&m_Stat, 0, sizeof(m_Stat)); } EType m_Type; ///< Type string m_Name; ///< Entry name string m_LinkName; ///< Link name if type is e{Sym|Hard}Link string m_UserName; ///< User name string m_GroupName; ///< Group name streamsize m_HeaderSize; ///< Total size of all headers for the entry CDirEntry::SStat m_Stat; ///< Direntry-compatible info Uint8 m_Pos; ///< Entry (not data!) position in archive friend class CTar; // Setter }; /// User-creatable info for streaming into a tar. /// Since the entry info is built largerly incomplete, all getters have been /// disabled; should some be needed they could be brought back by subclassing /// and redeclaring the necessary one(s) in the public part of the new class. class CTarUserEntryInfo : protected CTarEntryInfo { public: CTarUserEntryInfo(const string& name, Uint8 size) { m_Name = name; m_Stat.orig.st_size = size; } friend class CTar; // Accessor }; /// Nice TOC(table of contents) printout. NCBI_XUTIL_EXPORT ostream& operator << (ostream&, const CTarEntryInfo&); /// Forward declaration of a tar header used internally. struct STarHeader; ////////////////////////////////////////////////////////////////////////////// /// /// CTar class /// /// (Throws exceptions on most errors.) /// Note that if stream constructor is used, then CTar can only perform one /// pass over the archive. This means that only one full action will succeed /// (and if the action was to update -- e.g. append -- the archive, it has to /// be explicitly followed by Close() when no more appends are expected). /// Before the next read/update action, the stream position has to be reset /// explicitly to the beginning of the archive, or it may also remain at the /// end of the archive for a series of successive append operations. class NCBI_XUTIL_EXPORT CTar { public: /// General flags enum EFlags { // --- Extract/List/Test --- /// Ignore blocks of zeros in archive. // Generally, 2 or more consecutive zero blocks indicate EOT. fIgnoreZeroBlocks = (1<<1), // --- Extract/Append/Update --- /// Follow symbolic links (instead of storing/extracting them) fFollowLinks = (1<<2), // --- Extract --- (NB: fUpdate also applies to Update) /// Allow to overwrite destinations with entries from the archive fOverwrite = (1<<3), /// Only update entries that are older than those already existing fUpdate = (1<<4) | fOverwrite, /// Backup destinations if they exist (all entries including dirs) fBackup = (1<<5) | fOverwrite, /// If destination entry exists, it must have the same type as source fEqualTypes = (1<<6), /// Create extracted files with the original ownership fPreserveOwner = (1<<7), /// Create extracted files with the original permissions fPreserveMode = (1<<8), /// Preserve date/times for extracted files fPreserveTime = (1<<9), /// Preserve all file attributes fPreserveAll = fPreserveOwner | fPreserveMode | fPreserveTime, /// Preserve absolute path instead of stripping the leadind slash('/') fKeepAbsolutePath = (1<<12), /// Do not extract PAX GNU/1.0 sparse files (treat 'em as unsupported) fSparseUnsupported = (1<<13), // --- Extract/List --- /// Skip unsupported entries rather than make files out of them when /// extracting (the latter is the default behavior required by POSIX) fSkipUnsupported = (1<<15), // --- Append --- /// Ignore unreadable files/dirs (still warn them, but don't stop) fIgnoreUnreadable = (1<<17), /// Always use OldGNU headers for long names (default:only when needed) fLongNameSupplement = (1<<18), // --- Debugging --- fDumpEntryHeaders = (1<<20), fSlowSkipWithRead = (1<<21), // --- Miscellaneous --- /// Stream tar data through fStreamPipeThrough = (1<<24), /// Do not trim tar file size after append/update fTarfileNoTruncate = (1<<26), /// Suppress NCBI signatures in entry headers fStandardHeaderOnly = (1<<28), /// Default flags fDefault = fOverwrite | fPreserveAll }; typedef unsigned int TFlags; ///< Bitwise OR of EFlags /// Mask type enumerator. /// @enum eExtractMask /// CMask can select both inclusions and exclusions (in this order) of /// fully-qualified archive entries for listing or extraction, so that /// e.g. ".svn" does not match an entry like "a/.svn" for processing. /// @enum eExcludeMask /// CMask can select both exclusions and inclusions (in this order) of /// patterns of the archive entries for all operations (excepting eTest), /// and so that ".svn" matches "a/b/c/.svn". enum EMaskType { eExtractMask = 0, ///< exact for list or extract eExcludeMask ///< pattern for all but test }; /// Constructors CTar(const string& filename, size_t blocking_factor = 20); /// Stream version does not at all use stream positioning and so is safe on /// non-positionable streams, like pipes/sockets (or magnetic tapes :-I). CTar(CNcbiIos& stream, size_t blocking_factor = 20); /// Destructor (finalize the archive if currently open). /// @sa /// Close virtual ~CTar(); /// Define a list of entries. typedef list<CTarEntryInfo> TEntries; /// Define a list of files with sizes (directories and specials, such as /// devices, must be given with sizes of 0; symlinks -- with the sizes /// of the names they are linking to). typedef pair<string, Uint8> TFile; typedef list<TFile> TFiles; //------------------------------------------------------------------------ // Main functions //------------------------------------------------------------------------ /// Create a new empty archive. /// /// If a file with such a name already exists it will be overwritten. /// @sa /// Append void Create(void); /// Close the archive making sure all pending output is flushed. /// /// Normally, direct call of this method need _not_ intersperse successive /// archive manipulations by other methods, as they open and close the /// archive automagically as needed. Rather, this call is to make sure the /// archive is complete earlier than it otherwise usually be done /// automatically in the destructor of the CTar object. /// @sa /// ~CTar void Close(void); /// Append an entry at the end of the archive that already exists. /// /// Appended entry can be either a file, a directory, a symbolic link, /// a device special file (block or character), or a FIFO special file, /// subject to any exclusions as set by SetMask() with eExcludeMask. /// The name is taken with respect to the base directory, if any set. /// /// Adding a directory results in all its files and subdirectories (subject // for the exclusion mask) to get added: examine the return value to find /// out what has been added. /// /// Note that the final name of an entry may not contain embedded '..'. /// Leading slash in the absolute paths will be retained. The names of /// all appended entries will be converted to Unix format (that is, to /// have only forward slashes in the paths, and drive letter, if any on /// MS-Windows, stripped). All entries will be added at the logical end /// (not always EOF) of the archive, when appending to a non-empty one. /// /// @note Adding to a stream archive does not seek to the logical end of /// the archive but begins at the current position right away. /// /// @return /// A list of entries appended. /// @sa /// Create, Update, SetBaseDir, SetMask unique_ptr<TEntries> Append(const string& name); /// Append an entry from a stream (exactly entry.GetSize() bytes). /// @note /// Name masks (if any set with SetMask()) are all ignored. /// @return /// A list (containing this one entry) with full archive info filled in /// @sa /// Append unique_ptr<TEntries> Append(const CTarUserEntryInfo& entry, CNcbiIstream& is); /// Look whether more recent copies of the archive members are available in /// the file system, and if so, append them to the archive: /// /// - if fUpdate is set in processing flags, only the existing archive /// entries (including directories) will be updated; that is, Update(".") /// won't recursively add "." if "." is not an archive member; it will, /// however, do the recursive update should "." be found in the archive; /// /// - if fUpdate is unset, the existing entries will be updated (if their /// file system counterparts are newer), and nonexistent entries will be /// added to the archive; that is, Update(".") will recursively scan "." /// to update both existing entries (if newer files found), and also add /// new entries for any files/directories, which are currently not in. /// /// @note Updating stream archive may (and most certainly will) cause /// zero-filled gaps in the archive (can be read with "ignore zeroes"). /// /// @return /// A list of entries that have been updated. /// @sa /// Append, SetBaseDir, SetMask, SetFlags unique_ptr<TEntries> Update(const string& name); /// Extract the entire archive (into either current directory or a /// directory otherwise specified by SetBaseDir()). /// /// If the same-named files exist, they will be replaced (subject to /// fOverwrite) or backed up (fBackup), unless fUpdate is set, which would /// cause the replacement / backup only if the files are older than the /// archive entries. Note that if fOverwrite is stripped, no matching /// files will be updated / backed up / overwritten, but skipped. /// /// Extract all archive entries, whose names match the pre-set mask. /// @note /// Unlike Append(), extracting a matching directory does *not* /// automatically extract all files within: for them to be extracted, /// they still must match the mask. So if there is a directory "dir/" /// stored in the archive, the extract mask can be "dir/*" for the /// entire subtree to be extracted. Note that "dir/" will only extract /// the directory itself, and "dir" won't cause that directory to be /// extracted at all (mismatch due to the trailing slash '/' missing). /// @return /// A list of entries that have been actually extracted. /// @sa /// SetMask, SetBaseDir, SetFlags unique_ptr<TEntries> Extract(void); /// Get information about all matching archive entries. /// /// @return /// An array containing information on those archive entries, whose /// names match the pre-set mask. /// @sa /// SetMask unique_ptr<TEntries> List(void); /// Verify archive integrity. /// /// Read through the archive without actually extracting anything from it. /// Flag fDumpEntryHeaders causes most of archive headers to be dumped to /// the log (with eDiag_Info) as the Test() advances through the archive. /// @sa /// SetFlags void Test(void); //------------------------------------------------------------------------ // Utility functions //------------------------------------------------------------------------ /// Get processing flags. TFlags GetFlags(void) const; /// Set processing flags. void SetFlags(TFlags flags); /// Get current stream position. Uint8 GetCurrentPosition(void) const; /// Set name mask. /// /// The set of masks is used to process existing entries in the archive: /// both the extract and exclude masks apply to the list and extract /// operations, and only the exclude mask apply to the named append. /// If masks are not defined then all archive entries will be processed. /// /// @note Unset mask means wildcard processing (all entries match). /// /// @param mask /// Set of masks (0 to unset the current set without setting a new one). /// @param own /// Whether to take ownership on the mask (delete upon CTar destruction). /// @sa // SetFlags void SetMask(CMask* mask, EOwnership own = eNoOwnership, EMaskType type = eExtractMask, NStr::ECase acase = NStr::eCase); /// Get base directory to use for files while extracting from/adding to /// the archive, and in the latter case used only for relative paths. /// @sa /// SetBaseDir const string& GetBaseDir(void) const; /// Set base directory to use for files while extracting from/adding to /// the archive, and in the latter case used only for relative paths. /// @sa /// GetBaseDir void SetBaseDir(const string& dirname); /// Return archive size as if all specified input entries were put in it. /// Note that the return value is not the exact but the upper bound of /// what the archive size can be expected. This call does not recurse /// into any subdirectories but relies solely upon the information as /// passed via the parameter. /// /// The returned size includes all necessary alignments and padding. /// @return /// An upper estimate of archive size given that all specified files /// were stored in it (the actual size may turn out to be smaller). static Uint8 EstimateArchiveSize(const TFiles& files, size_t blocking_factor = 20, const string& base_dir = kEmptyStr); //------------------------------------------------------------------------ // Streaming //------------------------------------------------------------------------ /// Iterate over the archive forward and return first (or next) entry. /// /// When using this method (possibly along with GetNextEntryData()), the /// archive stream (if any) must not be accessed outside the CTar API, /// because otherwise inconsistency in data may result. /// An application may call GetNextEntryData() to stream some or all of the /// data out of this entry, or it may call GetNextEntryInfo() again to skip /// to the next archive entry, etc. /// Note that the archive can contain multiple versions of the same entry /// (in case if an update was done on it), all of which but the last one /// are to be ignored. This call traverses through all those entry /// versions, and sequentially exposes them to the application level. /// See test suite (in test/test_tar.cpp) for a usage example. /// @return /// Pointer to next entry info in the archive or 0 if EOF encountered. /// @sa /// CTarEntryInfo, GetNextEntryData const CTarEntryInfo* GetNextEntryInfo(void); /// Create and return an IReader, which can extract the current archive /// entry that has been previously returned via GetNextEntryInfo. /// /// The returned pointer is non-zero only if the current entry is a file /// (even of size 0). The ownership of the pointer is passed to the caller /// (so it has to be explicitly deleted when no longer needed). /// The IReader may be used to read all or part of data out of the entry /// without affecting GetNextEntryInfo()'s ability to find any following /// entry in the archive. /// See test suite (in test/test_tar.cpp) for a usage example. /// @return /// Pointer to IReader, or 0 if the current entry is not a file. /// @sa /// GetNextEntryData, IReader, CRStream IReader* GetNextEntryData(void); /// Create and return an IReader, which can extract contents of one named /// file (which can be requested by a name mask in the "name" parameter). /// /// The tar archive is deemed to be in the specified stream "is", properly /// positioned (either at the beginning of the archive, or at any /// CTarEntryInfo::GetPosition(ePos_Header)'s result possibly off-set /// with some fixed archive base position, e.g. if there is any preamble). /// The extraction is done at the first matching entry only, then stops. /// @note fStreamPipeThrough will be ignored if passed in flags. /// See test suite (in test/test_tar.cpp) for a usage example. /// @return /// IReader interface to read the file contents with; 0 on error. /// @sa /// CTarEntryInfo::GetPosition, Extract, SetMask, SetFlags, /// GetNextEntryInfo, GetNextEntryData, IReader, CRStream static IReader* Extract(CNcbiIstream& is, const string& name, TFlags flags = fSkipUnsupported); protected: //------------------------------------------------------------------------ // User-redefinable callback //------------------------------------------------------------------------ /// Return false to skip the current entry when reading; /// the return code gets ignored when writing. /// /// Note that the callback can encounter multiple entries of the same file /// in case the archive has been updated (so only the last occurrence is /// the actual copy of the file when extracted). virtual bool Checkpoint(const CTarEntryInfo& /*current*/, bool /*ifwrite: write==true, read==false*/) { return true; } private: /// Archive open mode and action enum EOpenMode { eNone = 0, eWO = 1, eRO = 2, eRW = eRO | eWO }; enum EAction { eUndefined = eNone, eList = (1 << 2) | eRO, eAppend = (1 << 3) | eRW, eUpdate = eList | eAppend, eExtract = (1 << 4) | eRO, eTest = eList | eExtract, eCreate = (1 << 5) | eWO, eInternal = (1 << 6) | eRO }; /// I/O completion code enum EStatus { eFailure = -1, eSuccess = 0, eContinue, eZeroBlock, eEOF }; /// Mask storage struct SMask { CMask* mask; NStr::ECase acase; EOwnership owned; SMask(void) : mask(0), acase(NStr::eNocase), owned(eNoOwnership) { } }; // Common part of initialization. void x_Init(void); // Open/close the archive. void x_Open(EAction action); void x_Close(bool truncate); // NB: "truncate" effects file archives only // Flush the archive (w/EOT); return "true" if it is okay to truncate bool x_Flush(bool nothrow = false); // Backspace and fast-forward the archive. void x_Backspace(EAction action); // NB: m_ZeroBlockCount blocks back void x_Skip(Uint8 blocks); // NB: Can do by either skip or read // Parse in extended entry information (PAX) for the current entry. EStatus x_ParsePAXData(const string& data); // Read information about current entry in the archive. EStatus x_ReadEntryInfo(bool dump, bool pax); // Pack current name or linkname into archive entry header. bool x_PackCurrentName(STarHeader* header, bool link); // Write information for current entry into the archive. void x_WriteEntryInfo(const string& name); // Read the archive and do the requested "action" on current entry. unique_ptr<TEntries> x_ReadAndProcess(EAction action); // Process current entry from the archive (the actual size passed in). // If action != eExtract, then just skip the entry without any processing. // Return true iff the entry was successfully extracted (ie with eExtract). bool x_ProcessEntry(EAction action, Uint8 size, const TEntries* done); // Extract current entry (archived size passed in) from the archive into // the file system, and update the size still remaining in the archive, if // any. Return true if the extraction succeeded, false otherwise. bool x_ExtractEntry(Uint8& size, const CDirEntry* dst, const CDirEntry* src); // Extract file data from the archive. void x_ExtractPlainFile (Uint8& size, const CDirEntry* dst); bool x_ExtractSparseFile(Uint8& size, const CDirEntry* dst, bool dump = false); // Restore attributes of an entry in the file system. // If "path" is not specified, then the destination path will be // constructed from "info", and the base directory (if any). Otherwise, // "path" will be used "as is", assuming it corresponds to "info". void x_RestoreAttrs(const CTarEntryInfo& info, TFlags what, const CDirEntry* path = 0, TTarMode perm = 0/*override*/) const; // Read a text string terminated with '\n'. string x_ReadLine(Uint8& size, const char*& data, size_t& nread); // Read/write specified number of bytes from/to the archive. const char* x_ReadArchive (size_t& n); void x_WriteArchive(size_t n, const char* buffer = 0); // Append an entry from the file system to the archive. unique_ptr<TEntries> x_Append(const string& name, const TEntries* toc = 0); // Append an entry from an istream to the archive. unique_ptr<TEntries> x_Append(const CTarUserEntryInfo& entry, CNcbiIstream& is); // Append data from an istream to the archive. void x_AppendStream(const string& name, CNcbiIstream& is); // Append a regular file to the archive. bool x_AppendFile(const string& file); private: string m_FileName; ///< Tar archive file name (only if file) CNcbiFstream* m_FileStream; ///< File stream of the archive (if file) CNcbiIos& m_Stream; ///< Archive stream (used for all I/O) size_t m_ZeroBlockCount; ///< Zero blocks seen in between entries const size_t m_BufferSize; ///< Buffer(record) size for I/O operations size_t m_BufferPos; ///< Position within the record Uint8 m_StreamPos; ///< Position in stream (0-based) char* m_BufPtr; ///< Page-unaligned buffer pointer char* m_Buffer; ///< I/O buffer (page-aligned) SMask m_Mask[2]; ///< Entry masks for operations EOpenMode m_OpenMode; ///< What was it opened for bool m_Modified; ///< True after at least one write bool m_Bad; ///< True if a fatal output error occurred TFlags m_Flags; ///< Bitwise OR of flags string m_BaseDir; ///< Base directory for relative paths CTarEntryInfo m_Current; ///< Current entry being processed private: // Prohibit assignment and copy CTar& operator=(const CTar&); CTar(const CTar&); friend class CTarReader; }; ////////////////////////////////////////////////////////////////////////////// // // Inline methods // inline void CTar::Create(void) { x_Open(eCreate); } inline void CTar::Close(void) { x_Close(x_Flush()); } inline unique_ptr<CTar::TEntries> CTar::Append(const string& name) { x_Open(eAppend); return x_Append(name); } inline unique_ptr<CTar::TEntries> CTar::Append(const CTarUserEntryInfo& entry, CNcbiIstream& is) { x_Open(eAppend); return x_Append(entry, is); } inline unique_ptr<CTar::TEntries> CTar::Update(const string& name) { x_Open(eUpdate); return x_Append(name, x_ReadAndProcess(eUpdate).get()); } inline unique_ptr<CTar::TEntries> CTar::List(void) { x_Open(eList); return x_ReadAndProcess(eList); } inline void CTar::Test(void) { x_Open(eTest); x_ReadAndProcess(eTest); } inline CTar::TFlags CTar::GetFlags(void) const { return m_Flags; } inline void CTar::SetFlags(TFlags flags) { m_Flags = flags; } inline Uint8 CTar::GetCurrentPosition(void) const { return m_StreamPos; } inline const string& CTar::GetBaseDir(void) const { return m_BaseDir; } END_NCBI_SCOPE /* @} */ #endif /* UTIL_COMPRESS__TAR__HPP */
39.401602
79
0.60133
[ "object" ]
d750c33650a70b96a8d028e1bb79366bf57fdde5
4,169
cpp
C++
sources/model/Lists.cpp
rizwanniazigroupdocs/aspose-words-cloud-cpp
c27be122cf538f5a487529d2d1cb8fe3fb30598c
[ "MIT" ]
null
null
null
sources/model/Lists.cpp
rizwanniazigroupdocs/aspose-words-cloud-cpp
c27be122cf538f5a487529d2d1cb8fe3fb30598c
[ "MIT" ]
null
null
null
sources/model/Lists.cpp
rizwanniazigroupdocs/aspose-words-cloud-cpp
c27be122cf538f5a487529d2d1cb8fe3fb30598c
[ "MIT" ]
null
null
null
/** -------------------------------------------------------------------------------------------------------------------- * <copyright company="Aspose" file="Lists.cpp"> * Copyright (c) 2020 Aspose.Words for Cloud * </copyright> * <summary> * 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. * </summary> -------------------------------------------------------------------------------------------------------------------- **/ #include "Lists.h" namespace aspose { namespace words { namespace cloud { namespace api { namespace models { Lists::Lists() { m_ListInfoIsSet = false; } Lists::~Lists() { } void Lists::validate() { // TODO: implement validation } web::json::value Lists::toJson() const { web::json::value val = this->LinkElement::toJson(); if(m_ListInfoIsSet) { std::vector<web::json::value> jsonArray; std::transform(m_ListInfo.begin(), m_ListInfo.end(), std::back_inserter(jsonArray), [&](std::shared_ptr<ListInfo> item) { return ModelBase::toJson(item); }); if(jsonArray.size() > 0) { val[_XPLATSTR("ListInfo")] = web::json::value::array(jsonArray); } } return val; } void Lists::fromJson(web::json::value& val) { this->LinkElement::fromJson(val); { m_ListInfo.clear(); if(val.has_field(_XPLATSTR("ListInfo")) && !val[_XPLATSTR("ListInfo")].is_null()) { auto arr = val[_XPLATSTR("ListInfo")].as_array(); std::transform(arr.begin(), arr.end(), std::back_inserter(m_ListInfo), [&](web::json::value& item){ if(!item.is_null()) { std::shared_ptr<ListInfo> newItem(new ListInfo()); newItem->fromJson(item); return newItem; } return (std::shared_ptr<ListInfo>)nullptr; }); } } } void Lists::toMultipart(const std::shared_ptr<MultipartFormData>& multipart, const utility::string_t& prefix) const { LinkElement::toMultipart(multipart, prefix); auto namePrefix = ModelBase::fixNamePrefix(prefix); { std::vector<web::json::value> jsonArray; std::transform(m_ListInfo.begin(), m_ListInfo.end(), std::back_inserter(jsonArray), [&](std::shared_ptr<ListInfo> item){ return ModelBase::toJson(item); }); if(jsonArray.size() > 0) { multipart->add(ModelBase::toHttpContent(namePrefix + _XPLATSTR("ListInfo"), web::json::value::array(jsonArray), _XPLATSTR("application/json"))); } } } void Lists::fromMultiPart(const std::shared_ptr<MultipartFormData>& multipart, const utility::string_t& prefix) { // TODO: implement fromMultiPart } std::vector<std::shared_ptr<ListInfo>>& Lists::getListInfo() { return m_ListInfo; } void Lists::setListInfo(std::vector<std::shared_ptr<ListInfo>> const& value) { m_ListInfo = value; m_ListInfoIsSet = true; } bool Lists::listInfoIsSet() const { return m_ListInfoIsSet; } void Lists::unsetListInfo() { m_ListInfoIsSet = false; } } } } } }
28.951389
156
0.608779
[ "vector", "transform" ]
d750c7d327fb53e5219ad497855b6a7ff3a9b02f
1,838
cpp
C++
ProjectEuler/pe106.cpp
wang12d/ProgrammingPractices
c7a150eb1aeb0e30a30bc77a25aba940b99ce773
[ "MIT" ]
null
null
null
ProjectEuler/pe106.cpp
wang12d/ProgrammingPractices
c7a150eb1aeb0e30a30bc77a25aba940b99ce773
[ "MIT" ]
null
null
null
ProjectEuler/pe106.cpp
wang12d/ProgrammingPractices
c7a150eb1aeb0e30a30bc77a25aba940b99ce773
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; vector<vector<int> > all_combinations; // 所有的k个组和 vector<int> mids; // 在生成k-combinations时的中间函数 void pretty_print(vector<int> sour) { printf("[ "); vector<int>::iterator end = sour.end(); for (vector<int>::iterator it = sour.begin(); it != end; ++it) { printf("%d%c", *it, (it+1 == end ? ' ' : ',')); } printf("]\n"); } // k-combinations // 从一个数组中生成全部的k个组合 void k_combinations(int k, vector<int> sour, int offset) { if (k == 0) { all_combinations.push_back(mids); return; } for (int i = offset; i <= sour.size() - k; ++i) { mids.push_back(sour[i]); k_combinations(k-1, sour, i+1); mids.pop_back(); } } // 给出两个数组,判断其是否符合条件 // size(vec1) == size(vec2) int need_check(vector<int> vec1, vector<int> vec2) { int size = vec1.size(); for (int i = 0; i < size; ++i) { int a = vec1[i]; for (int j = 0; j < size; ++j) { if (a == vec2[j]) { return 0; } } } bool flag = false; for (int i = 0; i < size; ++i) { int a = vec1[i], b = vec2[i]; if (a > b) { flag = true; break; } } return flag; } int main(int argc, char **argv) { vector<int> sour {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; int cnt = 0; int size = sour.size(); for (int i = 2; 2*i <= size; ++i) { k_combinations(i, sour, 0); int comb_size = all_combinations.size(); for (int j = 0; j < comb_size; ++j) { vector<int> vec = all_combinations[j]; for (int v = j+1; v < comb_size; ++v) { cnt += need_check(vec, all_combinations[v]); } } all_combinations.clear(); } printf("%d\n", cnt); }
22.975
68
0.486398
[ "vector" ]
d75160e4b77cbb2be83f04ff4c86348eac4c6b51
10,913
cpp
C++
jni/WiEngine_binding/opengl/com_wiyun_engine_opengl_Primitives.cpp
zchajax/WiEngine
ea2fa297f00aa5367bb5b819d6714ac84a8a8e25
[ "MIT" ]
39
2015-01-23T10:01:31.000Z
2021-06-10T03:01:18.000Z
jni/WiEngine_binding/opengl/com_wiyun_engine_opengl_Primitives.cpp
luckypen/WiEngine
7e80641fe15a77a2fc43db90f15dad6aa2c2860a
[ "MIT" ]
1
2015-04-15T08:07:47.000Z
2015-04-15T08:07:47.000Z
jni/WiEngine_binding/opengl/com_wiyun_engine_opengl_Primitives.cpp
luckypen/WiEngine
7e80641fe15a77a2fc43db90f15dad6aa2c2860a
[ "MIT" ]
20
2015-01-20T07:36:10.000Z
2019-09-15T01:02:19.000Z
#include "com_wiyun_engine_opengl_Primitives.h" #include "wyPrimitives.h" #include <stdlib.h> #include "wyUtils_android.h" extern jfieldID g_fid_WYPoint_x; extern jfieldID g_fid_WYPoint_y; extern jfieldID g_fid_WYSize_width; extern jfieldID g_fid_WYSize_height; extern jfieldID g_fid_WYRect_origin; extern jfieldID g_fid_WYRect_size; extern jfieldID g_fid_WYBezierConfig_cubic; extern jfieldID g_fid_WYBezierConfig_startX; extern jfieldID g_fid_WYBezierConfig_startY; extern jfieldID g_fid_WYBezierConfig_endX; extern jfieldID g_fid_WYBezierConfig_endY; extern jfieldID g_fid_WYBezierConfig_cp1X; extern jfieldID g_fid_WYBezierConfig_cp1Y; extern jfieldID g_fid_WYBezierConfig_cp2X; extern jfieldID g_fid_WYBezierConfig_cp2Y; extern jfieldID g_fid_WYLagrangeConfig_cubic; extern jfieldID g_fid_WYLagrangeConfig_startX; extern jfieldID g_fid_WYLagrangeConfig_startY; extern jfieldID g_fid_WYLagrangeConfig_endX; extern jfieldID g_fid_WYLagrangeConfig_endY; extern jfieldID g_fid_WYLagrangeConfig_cp1X; extern jfieldID g_fid_WYLagrangeConfig_cp1Y; extern jfieldID g_fid_WYLagrangeConfig_cp2X; extern jfieldID g_fid_WYLagrangeConfig_cp2Y; extern jfieldID g_fid_WYLagrangeConfig_t0; extern jfieldID g_fid_WYLagrangeConfig_t1; extern jfieldID g_fid_WYLagrangeConfig_t2; extern jfieldID g_fid_WYLagrangeConfig_t3; // WYHypotrochoidConfig class extern jfieldID g_fid_WYHypotrochoidConfig_R; extern jfieldID g_fid_WYHypotrochoidConfig_r; extern jfieldID g_fid_WYHypotrochoidConfig_d; extern jfieldID g_fid_WYHypotrochoidConfig_startAngle; extern jfieldID g_fid_WYHypotrochoidConfig_endAngle; extern jfieldID g_fid_WYHypotrochoidConfig_centreX; extern jfieldID g_fid_WYHypotrochoidConfig_centreY; JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawPoint (JNIEnv * env, jclass clazz, jfloat x, jfloat y) { wyDrawPoint(x, y); } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawPoints___3Lcom_wiyun_engine_types_WYPoint_2 (JNIEnv * env, jclass clazz, jobjectArray points) { // build buffer jsize len = env->GetArrayLength(points); float* p = (float*)wyMalloc(sizeof(float) * len * 2); for(int i = 0; i < len; i++) { jobject point = env->GetObjectArrayElement(points, i); p[i * 2] = env->GetFloatField(point, g_fid_WYPoint_x); p[i * 2 + 1] = env->GetFloatField(point, g_fid_WYPoint_y); env->DeleteLocalRef(point); } // draw wyDrawPoints(p, len * 2); // free wyFree(p); } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawPoints___3F (JNIEnv * env, jclass clazz, jfloatArray points) { jsize len = env->GetArrayLength(points); float* array = env->GetFloatArrayElements(points, NULL); wyDrawPoints(array, len); env->ReleaseFloatArrayElements(points, array, 0); } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawLine (JNIEnv * env, jclass clazz, jfloat x1, jfloat y1, jfloat x2, jfloat y2) { wyDrawLine(x1, y1, x2, y2); } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawDashLine (JNIEnv * env, jclass clazz, jfloat x1, jfloat y1, jfloat x2, jfloat y2, jfloat dashLength) { wyDrawDashLine(x1, y1, x2, y2, dashLength); } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawPath (JNIEnv * env, jclass clazz, jfloatArray points) { jsize len = env->GetArrayLength(points); float* array = env->GetFloatArrayElements(points, NULL); wyDrawPath(array, len); env->ReleaseFloatArrayElements(points, array, 0); } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawDashPath (JNIEnv * env, jclass clazz, jfloatArray points, jfloat dashLength) { jsize len = env->GetArrayLength(points); float* array = env->GetFloatArrayElements(points, NULL); wyDrawDashPath(array, len, dashLength); env->ReleaseFloatArrayElements(points, array, 0); } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawRect (JNIEnv * env, jclass clazz, jobject rect) { // get object fields jobject origin = env->GetObjectField(rect, g_fid_WYRect_origin); jobject size = env->GetObjectField(rect, g_fid_WYRect_size); float x = env->GetFloatField(origin, g_fid_WYPoint_x); float y = env->GetFloatField(origin, g_fid_WYPoint_y); float w = env->GetFloatField(size, g_fid_WYSize_width); float h = env->GetFloatField(size, g_fid_WYSize_height); env->DeleteLocalRef(origin); env->DeleteLocalRef(size); // build buffer float* p = (float*)wyMalloc(sizeof(float) * 4 * 2); p[0] = x; p[1] = y; p[2] = x + w; p[3] = y; p[4] = x + w; p[5] = y + h; p[6] = x; p[7] = y + h; // draw wyDrawRect(p); // free wyFree(p); } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawPoly (JNIEnv * env, jclass clazz, jobjectArray poli, jboolean closePolygon) { // build buffer jsize len = env->GetArrayLength(poli); float* p = (float*)wyMalloc(sizeof(float) * len * 2); for(int i = 0; i < len; i++) { jobject point = env->GetObjectArrayElement(poli, i); p[i * 2] = env->GetFloatField(point, g_fid_WYPoint_x); p[i * 2 + 1] = env->GetFloatField(point, g_fid_WYPoint_y); env->DeleteLocalRef(point); } // draw wyDrawPoly(p, len * 2, closePolygon); // free wyFree(p); } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawCircle (JNIEnv * env, jclass clazz, jfloat centerX, jfloat centerY, jfloat r, jfloat radiusLineAngle, jint segments, jboolean drawLineToCenter) { wyDrawCircle(centerX, centerY, r, radiusLineAngle, segments, drawLineToCenter); } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawSolidCircle (JNIEnv * env, jclass clazz, jfloat centerX, jfloat centerY, jfloat r, jint segments, jobject color) { wyDrawSolidCircle(centerX, centerY, r, segments, wyUtils_android::to_wyColor4B( color)); } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawBezier (JNIEnv * env, jclass clazz, jobject c, jint segments) { bool cubic = env->GetBooleanField(c, g_fid_WYBezierConfig_cubic); if(cubic) { wyBezierConfig config = wybcCubic(env->GetFloatField(c, g_fid_WYBezierConfig_startX), env->GetFloatField(c, g_fid_WYBezierConfig_startY), env->GetFloatField(c, g_fid_WYBezierConfig_endX), env->GetFloatField(c, g_fid_WYBezierConfig_endY), env->GetFloatField(c, g_fid_WYBezierConfig_cp1X), env->GetFloatField(c, g_fid_WYBezierConfig_cp1Y), env->GetFloatField(c, g_fid_WYBezierConfig_cp2X), env->GetFloatField(c, g_fid_WYBezierConfig_cp2Y)); wyDrawBezier(config, segments); } else { wyBezierConfig config = wybcQuad(env->GetFloatField(c, g_fid_WYBezierConfig_startX), env->GetFloatField(c, g_fid_WYBezierConfig_startY), env->GetFloatField(c, g_fid_WYBezierConfig_endX), env->GetFloatField(c, g_fid_WYBezierConfig_endY), env->GetFloatField(c, g_fid_WYBezierConfig_cp1X), env->GetFloatField(c, g_fid_WYBezierConfig_cp1Y)); wyDrawBezier(config, segments); } } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawHypotrochoid (JNIEnv * env, jclass clazz, jobject c, jint segments) { wyHypotrochoidConfig config = wyhcQuad(env->GetFloatField(c, g_fid_WYHypotrochoidConfig_R), env->GetFloatField(c, g_fid_WYHypotrochoidConfig_r), env->GetFloatField(c, g_fid_WYHypotrochoidConfig_d), env->GetFloatField(c, g_fid_WYHypotrochoidConfig_startAngle), env->GetFloatField(c, g_fid_WYHypotrochoidConfig_endAngle), env->GetFloatField(c, g_fid_WYHypotrochoidConfig_centreX), env->GetFloatField(c, g_fid_WYHypotrochoidConfig_centreY)); wyDrawHypotrochoid(config, segments); } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawLagrange (JNIEnv * env, jclass clazz, jobject c, jint segments) { bool cubic = env->GetBooleanField(c, g_fid_WYLagrangeConfig_cubic); if(cubic) { wyLagrangeConfig config = wylcCubic(env->GetFloatField(c, g_fid_WYLagrangeConfig_startX), env->GetFloatField(c, g_fid_WYLagrangeConfig_startY), env->GetFloatField(c, g_fid_WYLagrangeConfig_endX), env->GetFloatField(c, g_fid_WYLagrangeConfig_endY), env->GetFloatField(c, g_fid_WYLagrangeConfig_cp1X), env->GetFloatField(c, g_fid_WYLagrangeConfig_cp1Y), env->GetFloatField(c, g_fid_WYLagrangeConfig_cp2X), env->GetFloatField(c, g_fid_WYLagrangeConfig_cp2Y)); config.t0 = env->GetFloatField(c, g_fid_WYLagrangeConfig_t0); config.t1 = env->GetFloatField(c, g_fid_WYLagrangeConfig_t1); config.t2 = env->GetFloatField(c, g_fid_WYLagrangeConfig_t2); config.t3 = env->GetFloatField(c, g_fid_WYLagrangeConfig_t3); wyDrawLagrange(config, segments); } else { wyLagrangeConfig config = wylcQuad(env->GetFloatField(c, g_fid_WYLagrangeConfig_startX), env->GetFloatField(c, g_fid_WYLagrangeConfig_startY), env->GetFloatField(c, g_fid_WYLagrangeConfig_endX), env->GetFloatField(c, g_fid_WYLagrangeConfig_endY), env->GetFloatField(c, g_fid_WYLagrangeConfig_cp1X), env->GetFloatField(c, g_fid_WYLagrangeConfig_cp1Y)); config.t0 = env->GetFloatField(c, g_fid_WYLagrangeConfig_t0); config.t1 = env->GetFloatField(c, g_fid_WYLagrangeConfig_t1); config.t2 = env->GetFloatField(c, g_fid_WYLagrangeConfig_t2); config.t3 = env->GetFloatField(c, g_fid_WYLagrangeConfig_t3); wyDrawLagrange(config, segments); } } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawSolidRect (JNIEnv * env, jclass clazz, jobject rect, jobject color) { // get object fields jobject origin = env->GetObjectField(rect, g_fid_WYRect_origin); jobject size = env->GetObjectField(rect, g_fid_WYRect_size); float x = env->GetFloatField(origin, g_fid_WYPoint_x); float y = env->GetFloatField(origin, g_fid_WYPoint_y); float w = env->GetFloatField(size, g_fid_WYSize_width); float h = env->GetFloatField(size, g_fid_WYSize_height); env->DeleteLocalRef(origin); env->DeleteLocalRef(size); // build buffer float* p = (float*)wyMalloc(sizeof(float) * 4 * 2); p[0] = x; p[1] = y; p[2] = x + w; p[3] = y; p[4] = x + w; p[5] = y + h; p[6] = x; p[7] = y + h; wyColor4B c = wyUtils_android::to_wyColor4B( color); // draw wyDrawSolidRect(p, c); // free wyFree(p); } JNIEXPORT void JNICALL Java_com_wiyun_engine_opengl_Primitives_drawSolidPoly (JNIEnv * env, jclass clazz, jobjectArray poli, jobject color) { // build buffer jsize len = env->GetArrayLength(poli); float* p = (float*)wyMalloc(sizeof(float) * len * 2); for(int i = 0; i < len; i++) { jobject point = env->GetObjectArrayElement(poli, i); p[i * 2] = env->GetFloatField(point, g_fid_WYPoint_x); p[i * 2 + 1] = env->GetFloatField(point, g_fid_WYPoint_y); env->DeleteLocalRef(point); } wyColor4B c = wyUtils_android::to_wyColor4B( color); // draw wyDrawSolidPoly(p, len * 2, c); // free wyFree(p); }
38.698582
141
0.756804
[ "object" ]
d755062492c77f38905e0814657eb90ca9d07e33
2,910
cpp
C++
src/test/example_complexity.cpp
Lectem/nanobench
de9b49373eaa4efa9f1d1cf23af725069ac1f90c
[ "MIT" ]
null
null
null
src/test/example_complexity.cpp
Lectem/nanobench
de9b49373eaa4efa9f1d1cf23af725069ac1f90c
[ "MIT" ]
null
null
null
src/test/example_complexity.cpp
Lectem/nanobench
de9b49373eaa4efa9f1d1cf23af725069ac1f90c
[ "MIT" ]
null
null
null
#include <nanobench.h> #include <thirdparty/doctest/doctest.h> #include <algorithm> #include <cmath> #include <functional> #include <iostream> #include <set> TEST_CASE("example_complexity_set") { ankerl::nanobench::Bench bench; ankerl::nanobench::Rng rng; for (size_t range = 10; range <= 1000; range = range * 3 / 2) { // create vector with random data std::set<uint64_t> set; for (size_t i = 0; i < range; ++i) { set.insert(rng()); } bench.complexityN(range).run("std::set find " + std::to_string(range), [&] { ankerl::nanobench::doNotOptimizeAway(set.find(rng())); }); } std::cout << bench.complexityBigO() << std::endl; } TEST_CASE("example_complexity_sort") { ankerl::nanobench::Rng rng{123}; ankerl::nanobench::Bench bench; for (size_t n = 10; n < 10000; n *= 2) { // prepare a set with range number of elements std::vector<uint64_t> data(n); for (size_t i = 0; i < n; ++i) { data[i] = rng(); } // sort should be O(n log n), shuffle is O(n), so we expect O(n log n). bench.complexityN(n).run("std::sort " + std::to_string(n), [&] { std::shuffle(data.begin(), data.end(), rng); std::sort(data.begin(), data.end()); }); } // calculates bigO of all preconfigured complexity functions std::cout << bench.complexityBigO() << std::endl; // calculates bigO for a custom function auto logLogN = bench.complexityBigO("O(log log n)", [](double n) { return std::log2(std::log2(n)); }); std::cout << logLogN << std::endl; } TEST_CASE("example_complexity_quadratic") { // create an ankerl::nanobench::Config object that is used in all the benchmarks ankerl::nanobench::Bench bench; ankerl::nanobench::Rng rng{123}; // run the same benchmark multiple times with different ranges for (size_t range = 10; range <= 1000; range *= 2) { // create vector with random data std::vector<double> vec(range, 0.0); for (auto& x : vec) { x = rng.uniform01(); } // each run is configured with complexityN(range) to specify the run's input N bench.complexityN(range).run("minimum pair " + std::to_string(range), [&] { // Actual algorithm we want to evaluate double minVal = std::numeric_limits<double>::max(); for (size_t i = 0; i < vec.size() - 1; ++i) { for (size_t j = i + 1; j < vec.size(); ++j) { auto diff = vec[i] - vec[j]; minVal = std::min(minVal, diff * diff); } } ankerl::nanobench::doNotOptimizeAway(minVal); }); } // after all the runs are done, calculate the BigO, and show the results std::cout << bench.complexityBigO() << std::endl; }
35.487805
106
0.567354
[ "object", "vector" ]
d757714d48cc1fa1183091526a37a00aceac7241
15,874
cpp
C++
routing/directions_engine.cpp
dbf256/organicmaps
1b20d277200dd5444443cf10c6b43cbabf59f3d8
[ "Apache-2.0" ]
1
2022-02-18T17:26:50.000Z
2022-02-18T17:26:50.000Z
routing/directions_engine.cpp
dbf256/organicmaps
1b20d277200dd5444443cf10c6b43cbabf59f3d8
[ "Apache-2.0" ]
null
null
null
routing/directions_engine.cpp
dbf256/organicmaps
1b20d277200dd5444443cf10c6b43cbabf59f3d8
[ "Apache-2.0" ]
null
null
null
#include "routing/directions_engine.hpp" #include "routing/data_source.hpp" #include "routing/fake_feature_ids.hpp" #include "routing/routing_helpers.hpp" #include "routing/routing_callbacks.hpp" #include "traffic/traffic_info.hpp" #include "routing_common/car_model.hpp" #include "indexer/ftypes_matcher.hpp" #include "coding/string_utf8_multilang.hpp" #include "geometry/mercator.hpp" #include "geometry/point2d.hpp" #include <cstdlib> #include <utility> namespace routing { namespace { bool IsFakeFeature(uint32_t featureId) { return routing::FakeFeatureIds::IsGuidesFeature(featureId) || routing::FakeFeatureIds::IsTransitFeature(featureId); } } // namespace using namespace routing::turns; using namespace std; using namespace traffic; void DirectionsEngine::Clear() { m_adjacentEdges.clear(); m_pathSegments.clear(); } std::unique_ptr<FeatureType> DirectionsEngine::GetFeature(FeatureID const & featureId) { if (IsFakeFeature(featureId.m_index)) return nullptr; return m_dataSource.GetFeature(featureId); } void DirectionsEngine::LoadPathAttributes(FeatureID const & featureId, LoadedPathSegment & pathSegment) { if (!featureId.IsValid()) return; auto ft = GetFeature(featureId); if (!ft) return; auto const highwayClass = ftypes::GetHighwayClass(feature::TypesHolder(*ft)); ASSERT_NOT_EQUAL(highwayClass, ftypes::HighwayClass::Error, ()); ASSERT_NOT_EQUAL(highwayClass, ftypes::HighwayClass::Undefined, ()); pathSegment.m_highwayClass = highwayClass; pathSegment.m_isLink = ftypes::IsLinkChecker::Instance()(*ft); pathSegment.m_onRoundabout = ftypes::IsRoundAboutChecker::Instance()(*ft); pathSegment.m_isOneWay = ftypes::IsOneWayChecker::Instance()(*ft); pathSegment.m_roadNameInfo.m_isLink = pathSegment.m_isLink; pathSegment.m_roadNameInfo.m_junction_ref = ft->GetMetadata(feature::Metadata::FMD_JUNCTION_REF); pathSegment.m_roadNameInfo.m_destination_ref = ft->GetMetadata(feature::Metadata::FMD_DESTINATION_REF); pathSegment.m_roadNameInfo.m_destination = ft->GetMetadata(feature::Metadata::FMD_DESTINATION); pathSegment.m_roadNameInfo.m_ref = ft->GetRoadNumber(); pathSegment.m_roadNameInfo.m_name = ft->GetName(StringUtf8Multilang::kDefaultCode); } void DirectionsEngine::GetSegmentRangeAndAdjacentEdges(IRoadGraph::EdgeListT const & outgoingEdges, Edge const & inEdge, uint32_t startSegId, uint32_t endSegId, SegmentRange & segmentRange, TurnCandidates & outgoingTurns) { outgoingTurns.isCandidatesAngleValid = true; outgoingTurns.candidates.reserve(outgoingEdges.size()); segmentRange = SegmentRange(inEdge.GetFeatureId(), startSegId, endSegId, inEdge.IsForward(), inEdge.GetStartPoint(), inEdge.GetEndPoint()); CHECK(segmentRange.IsCorrect(), ()); m2::PointD const & ingoingPoint = inEdge.GetStartJunction().GetPoint(); m2::PointD const & junctionPoint = inEdge.GetEndJunction().GetPoint(); for (auto const & edge : outgoingEdges) { if (edge.IsFake()) continue; auto ft = GetFeature(edge.GetFeatureId()); if (!ft) continue; auto const highwayClass = ftypes::GetHighwayClass(feature::TypesHolder(*ft)); ASSERT_NOT_EQUAL( highwayClass, ftypes::HighwayClass::Error, (mercator::ToLatLon(edge.GetStartPoint()), mercator::ToLatLon(edge.GetEndPoint()))); ASSERT_NOT_EQUAL( highwayClass, ftypes::HighwayClass::Undefined, (mercator::ToLatLon(edge.GetStartPoint()), mercator::ToLatLon(edge.GetEndPoint()))); bool const isLink = ftypes::IsLinkChecker::Instance()(*ft); double angle = 0; if (inEdge.GetFeatureId().m_mwmId == edge.GetFeatureId().m_mwmId) { ASSERT_LESS(mercator::DistanceOnEarth(junctionPoint, edge.GetStartJunction().GetPoint()), turns::kFeaturesNearTurnMeters, ()); m2::PointD const & outgoingPoint = edge.GetEndJunction().GetPoint(); angle = base::RadToDeg(turns::PiMinusTwoVectorsAngle(junctionPoint, ingoingPoint, outgoingPoint)); } else { // Note. In case of crossing mwm border // (inEdge.GetFeatureId().m_mwmId != edge.GetFeatureId().m_mwmId) // twins of inEdge.GetFeatureId() are considered as outgoing features. // In this case that turn candidate angle is invalid and // should not be used for turn generation. outgoingTurns.isCandidatesAngleValid = false; } outgoingTurns.candidates.emplace_back(angle, ConvertEdgeToSegment(*m_numMwmIds, edge), highwayClass, isLink); } if (outgoingTurns.isCandidatesAngleValid) { sort(outgoingTurns.candidates.begin(), outgoingTurns.candidates.end(), base::LessBy(&TurnCandidate::m_angle)); } } void DirectionsEngine::GetEdges(IndexRoadGraph const & graph, geometry::PointWithAltitude const & currJunction, bool isCurrJunctionFinish, IRoadGraph::EdgeListT & outgoing, IRoadGraph::EdgeListT & ingoing) { // Note. If |currJunction| is a finish the outgoing edges // from finish are not important for turn generation. if (!isCurrJunctionFinish) graph.GetOutgoingEdges(currJunction, outgoing); graph.GetIngoingEdges(currJunction, ingoing); } void DirectionsEngine::FillPathSegmentsAndAdjacentEdgesMap( IndexRoadGraph const & graph, vector<geometry::PointWithAltitude> const & path, IRoadGraph::EdgeVector const & routeEdges, base::Cancellable const & cancellable) { size_t const pathSize = path.size(); CHECK_GREATER(pathSize, 1, ()); CHECK_EQUAL(routeEdges.size() + 1, pathSize, ()); // Filling |m_adjacentEdges|. auto constexpr kInvalidSegId = numeric_limits<uint32_t>::max(); // |startSegId| is a value to keep start segment id of a new instance of LoadedPathSegment. uint32_t startSegId = kInvalidSegId; vector<geometry::PointWithAltitude> prevJunctions; vector<Segment> prevSegments; for (size_t i = 1; i < pathSize; ++i) { if (cancellable.IsCancelled()) return; geometry::PointWithAltitude const & prevJunction = path[i - 1]; geometry::PointWithAltitude const & currJunction = path[i]; IRoadGraph::EdgeListT outgoingEdges; IRoadGraph::EdgeListT ingoingEdges; bool const isCurrJunctionFinish = (i + 1 == pathSize); GetEdges(graph, currJunction, isCurrJunctionFinish, outgoingEdges, ingoingEdges); Edge const & inEdge = routeEdges[i - 1]; // Note. |inFeatureId| may be invalid in case of adding fake features. // It happens for example near starts and a finishes. FeatureID const & inFeatureId = inEdge.GetFeatureId(); uint32_t const inSegId = inEdge.GetSegId(); if (startSegId == kInvalidSegId) startSegId = inSegId; prevJunctions.push_back(prevJunction); prevSegments.push_back(ConvertEdgeToSegment(*m_numMwmIds, inEdge)); if (!isCurrJunctionFinish && inFeatureId.IsValid() && !IsJoint(ingoingEdges, outgoingEdges, inEdge, routeEdges[i])) continue; CHECK_EQUAL(prevJunctions.size(), static_cast<size_t>(abs(int(inSegId) - int(startSegId)) + 1), ()); prevJunctions.push_back(currJunction); AdjacentEdges adjacentEdges(ingoingEdges.size()); SegmentRange segmentRange; GetSegmentRangeAndAdjacentEdges(outgoingEdges, inEdge, startSegId, inSegId, segmentRange, adjacentEdges.m_outgoingTurns); size_t const prevJunctionSize = prevJunctions.size(); LoadedPathSegment pathSegment; LoadPathAttributes(segmentRange.GetFeature(), pathSegment); pathSegment.m_segmentRange = segmentRange; pathSegment.m_path = move(prevJunctions); // @TODO(bykoianko) |pathSegment.m_weight| should be filled here. // |prevSegments| contains segments which corresponds to road edges between joints. In case of a // fake edge a fake segment is created. CHECK_EQUAL(prevSegments.size() + 1, prevJunctionSize, ()); pathSegment.m_segments = move(prevSegments); if (!segmentRange.IsEmpty()) { auto const it = m_adjacentEdges.find(segmentRange); m_adjacentEdges.insert(it, make_pair(segmentRange, move(adjacentEdges))); } m_pathSegments.push_back(move(pathSegment)); prevJunctions.clear(); prevSegments.clear(); startSegId = kInvalidSegId; } } bool DirectionsEngine::Generate(IndexRoadGraph const & graph, vector<geometry::PointWithAltitude> const & path, base::Cancellable const & cancellable, Route::TTurns & turns, Route::TStreets & streetNames, vector<geometry::PointWithAltitude> & routeGeometry, vector<Segment> & segments) { CHECK(m_numMwmIds, ()); m_adjacentEdges.clear(); m_pathSegments.clear(); turns.clear(); streetNames.clear(); segments.clear(); IndexRoadGraph::EdgeVector routeEdges; CHECK_NOT_EQUAL(m_vehicleType, VehicleType::Count, (m_vehicleType)); if (m_vehicleType == VehicleType::Transit) { routeGeometry = path; graph.GetRouteSegments(segments); graph.GetRouteEdges(routeEdges); turns.emplace_back(routeEdges.size(), turns::PedestrianDirection::ReachedYourDestination); return true; } routeGeometry.clear(); if (path.size() <= 1) return false; graph.GetRouteEdges(routeEdges); if (routeEdges.empty()) return false; if (cancellable.IsCancelled()) return false; FillPathSegmentsAndAdjacentEdgesMap(graph, path, routeEdges, cancellable); if (cancellable.IsCancelled()) return false; auto const res = MakeTurnAnnotation(routeEdges, cancellable, routeGeometry, turns, streetNames, segments); if (res != RouterResultCode::NoError) return false; // In case of bicycle routing |m_pathSegments| may have an empty // |LoadedPathSegment::m_segments| fields. In that case |segments| is empty // so size of |segments| is not equal to size of |routeEdges|. if (!segments.empty()) CHECK_EQUAL(segments.size(), routeEdges.size(), ()); CHECK_EQUAL( routeGeometry.size(), path.size(), ("routeGeometry and path have different sizes. routeGeometry size:", routeGeometry.size(), "path size:", path.size(), "segments size:", segments.size(), "routeEdges size:", routeEdges.size())); return true; } /*! * \brief Compute turn and time estimation structs for the abstract route result. * \param result abstract routing result to annotate. * \param delegate Routing callbacks delegate. * \param points Storage for unpacked points of the path. * \param turnsDir output turns annotation storage. * \param streets output street names along the path. * \param segments route segments. * \return routing operation result code. */ // Normally loadedSegments structure is: // - Start point. Fake loop LoadedPathSegment with 1 segment of zero length. // - Straight jump from start point to the beginning of real route. LoadedPathSegment with 1 segment. // - Real route. N LoadedPathSegments, each with arbitrary amount of segments. N >= 1. // - Straight jump from the end of real route to finish point. LoadedPathSegment with 1 segment. // - Finish point. Fake loop LoadedPathSegment with 1 segment of zero length. // So minimal amount of segments is 5. // Resulting structure of turnsDir: // No Turn for 0th segment (no ingoing). m_index == 0. // No Turn for 1st segment (ingoing fake loop) - at start point. m_index == 1. // No Turn for 2nd (ingoing == jump) - at beginning of real route. m_index == 2. // Possible turn for next N-1 segments. m_index >= 3. // No Turn for (2 + N + 1)th segment (outgoing jump) - at finish point. m_index = 3 + M. // No Turn for (2 + N + 2)th segment (outgoing fake loop) - at finish point. m_index == 4 + M. // Added ReachedYourDestination - at finish point. m_index == 4 + M. // Where M - total amount of all segments from all LoadedPathSegments (size of |segments|). // So minimum m_index of ReachedYourDestination is 5 (real route with single segment), // and minimal |turnsDir| is - single ReachedYourDestination with m_index == 5. RouterResultCode DirectionsEngine::MakeTurnAnnotation(IndexRoadGraph::EdgeVector const & routeEdges, base::Cancellable const & cancellable, std::vector<geometry::PointWithAltitude> & junctions, Route::TTurns & turnsDir, Route::TStreets & streets, std::vector<Segment> & segments) { RoutingEngineResult result(routeEdges, m_adjacentEdges, m_pathSegments); LOG(LDEBUG, ("Shortest path length:", result.GetPathLength())); if (cancellable.IsCancelled()) return RouterResultCode::Cancelled; size_t skipTurnSegments = 0; auto const & loadedSegments = result.GetSegments(); segments.reserve(loadedSegments.size()); RoutingSettings const vehicleSettings = GetRoutingSettings(m_vehicleType); for (auto loadedSegmentIt = loadedSegments.cbegin(); loadedSegmentIt != loadedSegments.cend(); ++loadedSegmentIt) { CHECK(loadedSegmentIt->IsValid(), ()); // Street names contain empty names too for avoiding of freezing of old street name while // moving along unnamed street. streets.emplace_back(max(junctions.size(), static_cast<size_t>(1)) - 1, loadedSegmentIt->m_roadNameInfo); // Turns information. if (!junctions.empty() && skipTurnSegments == 0) { size_t const outgoingSegmentIndex = base::asserted_cast<size_t>(distance(loadedSegments.begin(), loadedSegmentIt)); TurnItem turnItem; turnItem.m_index = static_cast<uint32_t>(junctions.size() - 1); skipTurnSegments = GetTurnDirection(result, outgoingSegmentIndex, *m_numMwmIds, vehicleSettings, turnItem); if (!turnItem.IsTurnNone()) turnsDir.push_back(move(turnItem)); } if (skipTurnSegments > 0) --skipTurnSegments; // Path geometry. CHECK_GREATER_OR_EQUAL(loadedSegmentIt->m_path.size(), 2, ()); // Note. Every LoadedPathSegment in TUnpackedPathSegments contains LoadedPathSegment::m_path // of several Junctions. Last PointWithAltitude in a LoadedPathSegment::m_path is equal to first // junction in next LoadedPathSegment::m_path in vector TUnpackedPathSegments: // *---*---*---*---* *---* *---*---*---* // *---*---* *---*---*---* // To prevent having repetitions in |junctions| list it's necessary to take the first point only // from the first item of |loadedSegments|. The beginning should be ignored for the rest // |m_path|. junctions.insert(junctions.end(), loadedSegmentIt == loadedSegments.cbegin() ? loadedSegmentIt->m_path.cbegin() : loadedSegmentIt->m_path.cbegin() + 1, loadedSegmentIt->m_path.cend()); segments.insert(segments.end(), loadedSegmentIt->m_segments.cbegin(), loadedSegmentIt->m_segments.cend()); } // Path found. Points will be replaced by start and end edges junctions. if (junctions.size() == 1) junctions.push_back(junctions.front()); if (junctions.size() < 2) return RouterResultCode::RouteNotFound; junctions.front() = result.GetStartPoint(); junctions.back() = result.GetEndPoint(); FixupTurns(junctions, turnsDir); return RouterResultCode::NoError; } } // namespace routing
39.195062
121
0.684012
[ "geometry", "vector" ]
d75aa726c76645e63f457d1da408cd949a8f6167
285
cc
C++
openmit/tools/dstruct/dstring_test.cc
openmit/openmit
01e3262d69d47fbe38bad1ba95c7d1ade110d01e
[ "Apache-2.0" ]
15
2017-06-28T08:39:51.000Z
2019-03-27T14:08:45.000Z
openmit/tools/dstruct/dstring_test.cc
openmit/openmit
01e3262d69d47fbe38bad1ba95c7d1ade110d01e
[ "Apache-2.0" ]
null
null
null
openmit/tools/dstruct/dstring_test.cc
openmit/openmit
01e3262d69d47fbe38bad1ba95c7d1ade110d01e
[ "Apache-2.0" ]
3
2017-07-30T08:50:45.000Z
2017-10-24T14:41:30.000Z
#include "dstring.h" #include <iostream> int main(int argc, char ** argv) { std::string str("auc"); std::vector<std::string> result; mit::string::Split(str, &result, ','); for (size_t i = 0; i < result.size(); ++i) { std::cout << result[i] << std::endl; } return 0; }
21.923077
46
0.578947
[ "vector" ]
d7625299068fa41970a068826368f51ed587b46d
25,553
cpp
C++
arduino/0.4/drumkid/MozziDK/MozziGuts.cpp
mattybrad/drumkid
279f3e1caf94d5a3491ffedfa133147086a3ebdd
[ "MIT" ]
56
2019-09-10T19:52:11.000Z
2022-03-31T06:28:24.000Z
arduino/1.0/drumkid/MozziDK/MozziGuts.cpp
mattybrad/drumkidmozzi
3e164223c49dfb34f62391396056348b42a158c0
[ "MIT" ]
4
2020-04-19T13:05:45.000Z
2022-03-09T04:47:02.000Z
arduino/1.0/drumkid/MozziDK/MozziGuts.cpp
mattybrad/drumkidmozzi
3e164223c49dfb34f62391396056348b42a158c0
[ "MIT" ]
14
2019-08-23T07:24:39.000Z
2022-03-21T17:34:00.000Z
/* * MozziGuts.cpp * * Copyright 2012 Tim Barrass. * * This file is part of Mozzi. * * Mozzi by Tim Barrass is licensed under a Creative Commons * Attribution-NonCommercial-ShareAlike 4.0 International License. * */ #if ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "CircularBuffer.h" #include "MozziGuts.h" #include "mozzi_analog.h" #include "mozzi_config.h" // at the top of all MozziGuts and analog files //#include "mozzi_utils.h" #if IS_AVR() #include "FrequencyTimer2.h" #include "TimerOne.h" #elif IS_TEENSY3() // required from http://github.com/pedvide/ADC for Teensy 3.* #include "IntervalTimer.h" #include <ADC.h> #elif IS_STM32() #include "HardwareTimer.h" #include <STM32ADC.h> #elif IS_ESP8266() #include <Ticker.h> #include <uart.h> #endif #ifdef EXTERNAL_DAC DAC_MCP49xx dac(DAC_MCP49xx::MCP4922, 10); #endif #if (IS_TEENSY3() && F_CPU != 48000000) || (IS_AVR() && F_CPU != 16000000) #warning \ "Mozzi has been tested with a cpu clock speed of 16MHz on Arduino and 48MHz on Teensy 3! Results may vary with other speeds." #endif #if IS_TEENSY3() ADC *adc; // adc object uint8_t teensy_pin; #elif IS_STM32() STM32ADC adc(ADC1); uint8_t stm32_current_adc_pin; #endif /* ATmega328 technical manual, Section 12.7.4: The dual-slope operation [of phase correct pwm] has lower maximum operation frequency than single slope operation. However, due to the symmetric feature of the dual-slope PWM modes, these modes are preferred for motor control applications. Due to the single-slope operation, the operating frequency of the fast PWM mode can be twice as high as the phase correct PWM mode that use dual-slope operation. This high frequency makes the fast PWM mode well suited for power regulation, rectification, and DAC applications. High frequency allows physically small sized external components (coils, capacitors).. DAC, that's us! Fast PWM. PWM frequency tests 62500Hz, single 8 or dual 16 bits, bad aliasing 125000Hz dual 14 bits, sweet 250000Hz dual 12 bits, gritty, if you're gonna have 2 pins, have 14 bits 500000Hz dual 10 bits, grittier 16384Hz single nearly 9 bits (original mode) not bad for a single pin, but carrier freq noise can be an issue */ #if IS_ESP8266() && (ESP_AUDIO_OUT_MODE != PDM_VIA_SERIAL) #include <i2s.h> uint16_t output_buffer_size = 0; uint64_t samples_written_to_buffer = 0; #else #if IS_ESP8266() && (ESP_AUDIO_OUT_MODE == PDM_VIA_SERIAL) bool output_stopped = true; #endif //----------------------------------------------------------------------------------------------------------------- // ring buffer for audio output CircularBuffer<unsigned int> output_buffer; // fixed size 256 #if (STEREO_HACK == true) CircularBuffer<unsigned int> output_buffer2; // fixed size 256 #endif //----------------------------------------------------------------------------------------------------------------- #endif #if IS_AVR() // not storing backups, just turning timer on and off for pause for // teensy 3.*, other ARMs #ifdef EXTERNAL_DAC // in case an external MCP4922 dac is used. static void dacMCPAudioOutput() { dac.output((unsigned int)output_buffer.read()); } #if (STEREO_HACK == true) static void dacMCPAudioOutput2() { dac.outputB((unsigned int)output_buffer2.read()); } #endif #endif // to store backups of timer registers so Mozzi can be stopped and pre_mozzi // timer values can be restored static uint8_t pre_mozzi_TCCR1A, pre_mozzi_TCCR1B, pre_mozzi_OCR1A, pre_mozzi_TIMSK1; #if (AUDIO_MODE == HIFI) #if defined(TCCR2A) static uint8_t pre_mozzi_TCCR2A, pre_mozzi_TCCR2B, pre_mozzi_OCR2A, pre_mozzi_TIMSK2; #elif defined(TCCR2) static uint8_t pre_mozzi_TCCR2, pre_mozzi_OCR2, pre_mozzi_TIMSK; #elif defined(TCCR4A) static uint8_t pre_mozzi_TCCR4A, pre_mozzi_TCCR4B, pre_mozzi_TCCR4C, pre_mozzi_TCCR4D, pre_mozzi_TCCR4E, pre_mozzi_OCR4C, pre_mozzi_TIMSK4; #endif #endif static void backupPreMozziTimer1() { // backup pre-mozzi register values for pausing later pre_mozzi_TCCR1A = TCCR1A; pre_mozzi_TCCR1B = TCCR1B; pre_mozzi_OCR1A = OCR1A; pre_mozzi_TIMSK1 = TIMSK1; } //----------------------------------------------------------------------------------------------------------------- #if (AUDIO_MODE == HIFI) #if defined(TCCR2A) static uint8_t mozzi_TCCR2A, mozzi_TCCR2B, mozzi_OCR2A, mozzi_TIMSK2; #elif defined(TCCR2) static uint8_t mozzi_TCCR2, mozzi_OCR2, mozzi_TIMSK; #elif defined(TCCR4A) static uint8_t mozzi_TCCR4A, mozzi_TCCR4B, mozzi_TCCR4C, mozzi_TCCR4D, mozzi_TCCR4E, mozzi_OCR4C, mozzi_TIMSK4; #endif #endif #endif // end of timer backups for non-Teensy 3 boards //----------------------------------------------------------------------------------------------------------------- #if (USE_AUDIO_INPUT == true) // ring buffer for audio input CircularBuffer<unsigned int> input_buffer; // fixed size 256 static boolean audio_input_is_available; static int audio_input; // holds the latest audio from input_buffer uint8_t adc_count = 0; int getAudioInput() { return audio_input; } static void startFirstAudioADC() { #if IS_TEENSY3() adc->startSingleRead( AUDIO_INPUT_PIN); // ADC lib converts pin/channel in startSingleRead #elif IS_STM32() uint8_t dummy = AUDIO_INPUT_PIN; adc.setPins(&dummy, 1); adc.startConversion(); #else adcStartConversion(adcPinToChannelNum(AUDIO_INPUT_PIN)); #endif } /* static void receiveFirstAudioADC() { // nothing } */ static void startSecondAudioADC() { #if IS_TEENSY3() adc->startSingleRead(AUDIO_INPUT_PIN); #elif IS_STM32() uint8_t dummy = AUDIO_INPUT_PIN; adc.setPins(&dummy, 1); adc.startConversion(); #else ADCSRA |= (1 << ADSC); // start a second conversion on the current channel #endif } static void receiveSecondAudioADC() { if (!input_buffer.isFull()) #if IS_TEENSY3() input_buffer.write(adc->readSingle()); #elif IS_STM32() input_buffer.write(adc.getData()); #else input_buffer.write(ADC); #endif } #if !IS_SAMD21() #if IS_TEENSY3() void adc0_isr(void) #elif IS_STM32() void stm32_adc_eoc_handler() #else ISR(ADC_vect, ISR_BLOCK) #endif { switch (adc_count) { case 0: // 6us receiveSecondAudioADC(); adcReadSelectedChannels(); break; case 1: // <2us, <1us w/o receive // receiveFirstControlADC(); startSecondControlADC(); break; case 2: // 3us receiveSecondControlADC(); startFirstAudioADC(); break; // case 3: // invisible // receiveFirstAudioADC(); // break; } adc_count++; } #endif // end main audio input section #endif #if IS_SAMD21() // These are ARM SAMD21 Timer 5 routines to establish a sample rate interrupt static bool tcIsSyncing() { return TC5->COUNT16.STATUS.reg & TC_STATUS_SYNCBUSY; } static void tcStartCounter() { // Enable TC TC5->COUNT16.CTRLA.reg |= TC_CTRLA_ENABLE; while (tcIsSyncing()) ; } static void tcReset() { // Reset TCx TC5->COUNT16.CTRLA.reg = TC_CTRLA_SWRST; while (tcIsSyncing()) ; while (TC5->COUNT16.CTRLA.bit.SWRST) ; } static void tcDisable() { // Disable TC5 TC5->COUNT16.CTRLA.reg &= ~TC_CTRLA_ENABLE; while (tcIsSyncing()) ; } static void tcEnd() { tcDisable(); tcReset(); analogWrite(AUDIO_CHANNEL_1_PIN, 0); } static void tcConfigure(uint32_t sampleRate) { // Enable GCLK for TCC2 and TC5 (timer counter input clock) GCLK->CLKCTRL.reg = (uint16_t)(GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID(GCM_TC4_TC5)); while (GCLK->STATUS.bit.SYNCBUSY) ; tcReset(); // Set Timer counter Mode to 16 bits TC5->COUNT16.CTRLA.reg |= TC_CTRLA_MODE_COUNT16; // Set TC5 mode as match frequency TC5->COUNT16.CTRLA.reg |= TC_CTRLA_WAVEGEN_MFRQ; TC5->COUNT16.CTRLA.reg |= TC_CTRLA_PRESCALER_DIV1 | TC_CTRLA_ENABLE; TC5->COUNT16.CC[0].reg = (uint16_t)(SystemCoreClock / sampleRate - 1); while (tcIsSyncing()) ; // Configure interrupt request NVIC_DisableIRQ(TC5_IRQn); NVIC_ClearPendingIRQ(TC5_IRQn); NVIC_SetPriority(TC5_IRQn, 0); NVIC_EnableIRQ(TC5_IRQn); // Enable the TC5 interrupt request TC5->COUNT16.INTENSET.bit.MC0 = 1; while (tcIsSyncing()) ; } #endif #if IS_ESP8266() // lookup table for fast pdm coding on 8 output bits at a time static byte fast_pdm_table[]{0, 0b00010000, 0b01000100, 0b10010010, 0b10101010, 0b10110101, 0b11011101, 0b11110111, 0b11111111}; inline void writePDMCoded(uint16_t sample) { static uint32_t lastwritten = 0; static uint32_t nexttarget = 0; // We can write 32 bits at a time to the output buffer, typically, we'll do // this either once of twice per sample for (uint8_t words = 0; words < PDM_RESOLUTION; ++words) { uint32_t outbits = 0; for (uint8_t i = 0; i < 4; ++i) { nexttarget += sample - lastwritten; lastwritten = nexttarget & 0b11110000000000000; // code the highest 3-and-a-little bits next. // Note that sample only has 16 bits, while the // highest bit we consider for writing is bit 17. // Thus, if the highest bit is set, the next // three bits cannot be. #if (ESP_AUDIO_OUT_MODE == PDM_VIA_SERIAL) U1F = fast_pdm_table[lastwritten >> 13]; // optimized version of: Serial1.write(...); #else outbits = outbits << 8; outbits |= fast_pdm_table[lastwritten >> 13]; #endif } #if (ESP_AUDIO_OUT_MODE == PDM_VIA_I2S) i2s_write_sample(outbits); #endif } } #if (ESP_AUDIO_OUT_MODE == PDM_VIA_SERIAL) void ICACHE_RAM_ATTR write_audio_to_serial_tx() { #define OPTIMIZED_SERIAL1_AVAIALABLEFORWRITE \ (UART_TX_FIFO_SIZE - ((U1S >> USTXC) & 0xff)) if (output_stopped) return; while (OPTIMIZED_SERIAL1_AVAIALABLEFORWRITE > (PDM_RESOLUTION * 4)) { writePDMCoded(output_buffer.read()); } } #else inline void espWriteAudioToBuffer() { #if (ESP_AUDIO_OUT_MODE == EXTERNAL_DAC_VIA_I2S) #if (STEREO_HACK == true) updateAudio(); i2s_write_lr(audio_out_1, audio_out_2); #else i2s_write_lr(updateAudio(), 0); #endif #else uint16_t sample = updateAudio() + AUDIO_BIAS; writePDMCoded(sample); #endif ++samples_written_to_buffer; } #endif #endif static uint16_t update_control_timeout; static uint16_t update_control_counter; static void updateControlWithAutoADC(); void audioHook() // 2us excluding updateAudio() { // setPin13High(); #if (USE_AUDIO_INPUT == true) if (!input_buffer.isEmpty()) audio_input = input_buffer.read(); #endif #if IS_ESP8266() && (ESP_AUDIO_OUT_MODE != PDM_VIA_SERIAL) #if (PDM_RESOLUTION != 1) if (i2s_available() >= PDM_RESOLUTION) { #else if (!i2s_is_full()) { #endif #else if (!output_buffer.isFull()) { #endif if (!update_control_counter) { update_control_counter = update_control_timeout; updateControlWithAutoADC(); } else { --update_control_counter; } #if IS_ESP8266() && (ESP_AUDIO_OUT_MODE != PDM_VIA_SERIAL) // NOTE: On ESP / output via I2S, we simply use the I2S buffer as the output // buffer, which saves RAM, but also simplifies things a lot // esp. since i2s output already has output rate control -> no need for a // separate output timer espWriteAudioToBuffer(); #else #if (STEREO_HACK == true) updateAudio(); // in hacked version, this returns void output_buffer.write((unsigned int)(audio_out_1 + AUDIO_BIAS)); output_buffer2.write((unsigned int)(audio_out_2 + AUDIO_BIAS)); #else output_buffer.write((unsigned int)(updateAudio() + AUDIO_BIAS)); #endif #endif #if IS_ESP8266() yield(); #endif } // setPin13Low(); } #if IS_SAMD21() void TC5_Handler(void) __attribute__((weak, alias("samd21AudioOutput"))); #endif //----------------------------------------------------------------------------------------------------------------- #if (AUDIO_MODE == STANDARD) || (AUDIO_MODE == STANDARD_PLUS) || IS_STM32() #if IS_SAMD21() #ifdef __cplusplus extern "C" { #endif void samd21AudioOutput(void); #ifdef __cplusplus } #endif #elif IS_TEENSY3() IntervalTimer timer1; #elif IS_STM32() HardwareTimer audio_update_timer(AUDIO_UPDATE_TIMER); HardwareTimer audio_pwm_timer(AUDIO_PWM_TIMER); #endif #if IS_SAMD21() #ifdef __cplusplus extern "C" { #endif void samd21AudioOutput() { #if (USE_AUDIO_INPUT == true) adc_count = 0; startSecondAudioADC(); #endif analogWrite(AUDIO_CHANNEL_1_PIN, (int)output_buffer.read()); TC5->COUNT16.INTFLAG.bit.MC0 = 1; } #ifdef __cplusplus } #endif #elif IS_TEENSY3() static void teensyAudioOutput() { #if (USE_AUDIO_INPUT == true) adc_count = 0; startSecondAudioADC(); #endif analogWrite(AUDIO_CHANNEL_1_PIN, (int)output_buffer.read()); } #elif IS_STM32() static void pwmAudioOutput() { #if (USE_AUDIO_INPUT == true) adc_count = 0; startSecondAudioADC(); #endif #if (AUDIO_MODE == HIFI) int out = output_buffer.read(); pwmWrite(AUDIO_CHANNEL_1_PIN, out & ((1 << AUDIO_BITS_PER_CHANNEL) - 1)); pwmWrite(AUDIO_CHANNEL_1_PIN_HIGH, out >> AUDIO_BITS_PER_CHANNEL); #else pwmWrite(AUDIO_CHANNEL_1_PIN, (int)output_buffer.read()); #if (STEREO_HACK == true) pwmWrite(AUDIO_CHANNEL_2_PIN, (int)output_buffer2.read()); #endif #endif } #endif #if !IS_AVR() static void startAudioStandard() { #if IS_TEENSY3() adc->setAveraging(0); adc->setConversionSpeed( ADC_CONVERSION_SPEED::MED_SPEED); // could be HIGH_SPEED, noisier analogWriteResolution(12); timer1.begin(teensyAudioOutput, 1000000UL / AUDIO_RATE); #elif IS_SAMD21() #ifdef ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS { static const int CPLAY_SPEAKER_SHUTDOWN = 11; pinMode(CPLAY_SPEAKER_SHUTDOWN, OUTPUT); digitalWrite(CPLAY_SPEAKER_SHUTDOWN, HIGH); } #endif analogWriteResolution(12); analogWrite(AUDIO_CHANNEL_1_PIN, 0); tcConfigure(AUDIO_RATE); #elif IS_STM32() audio_update_timer.pause(); //audio_update_timer.setPeriod(1000000UL / AUDIO_RATE); // Manually calculate prescaler and overflow instead of using setPeriod, to avoid rounding errors uint32_t period_cyc = F_CPU / AUDIO_RATE; uint16_t prescaler = (uint16_t)(period_cyc / 65535 + 1); uint16_t overflow = (uint16_t)((period_cyc + (prescaler / 2)) / prescaler); audio_update_timer.setPrescaleFactor(prescaler); audio_update_timer.setOverflow(overflow); audio_update_timer.setChannel1Mode(TIMER_OUTPUT_COMPARE); audio_update_timer.setCompare(TIMER_CH1, 1); // Interrupt 1 count after each update audio_update_timer.attachCompare1Interrupt(pwmAudioOutput); audio_update_timer.refresh(); audio_update_timer.resume(); pinMode(AUDIO_CHANNEL_1_PIN, PWM); #if (AUDIO_MODE == HIFI) pinMode(AUDIO_CHANNEL_1_PIN_HIGH, PWM); #elif (STEREO_HACK == true) pinMode(AUDIO_CHANNEL_2_PIN, PWM); #endif #define MAX_CARRIER_FREQ (F_CPU / (1 << AUDIO_BITS_PER_CHANNEL)) #if MAX_CARRIER_FREQ < AUDIO_RATE #error Configured audio resolution is definitely too high at the configured audio rate (and the given CPU speed) #elif MAX_CARRIER_FREQ < (AUDIO_RATE * 3) #warning Configured audio resolution may be higher than optimal at the configured audio rate (and the given CPU speed) #endif #if MAX_CARRIER_FREQ < (AUDIO_RATE * 5) // Generate as fast a carrier as possible audio_pwm_timer.setPrescaleFactor(1); #else // No point in generating arbitrarily high carrier frequencies. In fact, if // there _is_ any headroom, give the PWM pin more time to swing from HIGH to // LOW and BACK, cleanly audio_pwm_timer.setPrescaleFactor((int)MAX_CARRIER_FREQ / (AUDIO_RATE * 5)); #endif audio_pwm_timer.setOverflow( 1 << AUDIO_BITS_PER_CHANNEL); // Allocate enough room to write all // intended bits #elif IS_ESP8266() #if (ESP_AUDIO_OUT_MODE == PDM_VIA_SERIAL) output_stopped = false; Serial1.begin( AUDIO_RATE * (PDM_RESOLUTION * 40), SERIAL_8N1, SERIAL_TX_ONLY); // Note: PDM_RESOLUTION corresponds to packets of 32 // encoded bits However, the UART (unfortunately) adds a // start and stop bit each around each byte, thus sending // a total to 40 bits per audio sample per // PDM_RESOLUTION. // set up a timer to copy from Mozzi output_buffer into Serial TX buffer timer1_isr_init(); timer1_attachInterrupt(write_audio_to_serial_tx); // UART FIFO buffer size is 128 bytes. To be on the safe side, we keep the // interval to the time needed to write half of that. PDM_RESOLUTION * 4 bytes // per sample written. timer1_enable(TIM_DIV16, TIM_EDGE, TIM_LOOP); timer1_write(F_CPU / (AUDIO_RATE * PDM_RESOLUTION)); #else i2s_begin(); #if (ESP_AUDIO_OUT_MODE == PDM_VIA_I2S) pinMode(2, INPUT); // Set the two unneeded I2S pins to input mode, to reduce // side effects pinMode(15, INPUT); #endif i2s_set_rate(AUDIO_RATE * PDM_RESOLUTION); if (output_buffer_size == 0) output_buffer_size = i2s_available(); // Do not reset count when stopping / restarting #endif #endif } #else // avr architecture static void startAudioStandard() { backupPreMozziTimer1(); pinMode(AUDIO_CHANNEL_1_PIN, OUTPUT); // set pin to output for audio // pinMode(AUDIO_CHANNEL_2_PIN, OUTPUT); // set pin to output for audio #if (AUDIO_MODE == STANDARD) Timer1.initializeCPUCycles( F_CPU / AUDIO_RATE, PHASE_FREQ_CORRECT); // set period, phase and frequency correct #else // (AUDIO_MODE == STANDARD_PLUS) Timer1.initializeCPUCycles(F_CPU / PWM_RATE, FAST); // fast mode enables higher PWM rate #endif Timer1.pwm(AUDIO_CHANNEL_1_PIN, AUDIO_BIAS); // pwm pin, 50% of Mozzi's duty cycle, ie. 0 signal #if (STEREO_HACK == true) Timer1.pwm(AUDIO_CHANNEL_2_PIN, AUDIO_BIAS); // sets pin to output #endif TIMSK1 = _BV(TOIE1); // Overflow Interrupt Enable (when not using // Timer1.attachInterrupt()) } /* Interrupt service routine moves sound data from the output buffer to the Arduino output register, running at AUDIO_RATE. */ ISR(TIMER1_OVF_vect, ISR_BLOCK) { #if (AUDIO_MODE == STANDARD_PLUS) && \ (AUDIO_RATE == 16384) // only update every second ISR, if lower audio rate static boolean alternate; alternate = !alternate; if (alternate) { #endif #if (USE_AUDIO_INPUT == true) adc_count = 0; startSecondAudioADC(); #endif #ifdef EXTERNAL_DAC dacMCPAudioOutput(); #if (STEREO_HACK == true) dacMCPAudioOutput2(); #endif #else AUDIO_CHANNEL_1_OUTPUT_REGISTER = output_buffer.read(); #endif #if (STEREO_HACK == true) AUDIO_CHANNEL_2_OUTPUT_REGISTER = output_buffer2.read(); #endif #if (AUDIO_MODE == STANDARD_PLUS) && \ (AUDIO_RATE == 16384) // all this conditional compilation is so clutsy! } #endif } // end avr #endif // end STANDARD //----------------------------------------------------------------------------------------------------------------- #elif IS_AVR() && (AUDIO_MODE == HIFI) static void startAudioHiFi() { backupPreMozziTimer1(); // pwm on timer 1 pinMode(AUDIO_CHANNEL_1_highByte_PIN, OUTPUT); // set pin to output for audio, use 3.9k resistor pinMode(AUDIO_CHANNEL_1_lowByte_PIN, OUTPUT); // set pin to output for audio, use 499k resistor Timer1.initializeCPUCycles( F_CPU / 125000, FAST); // set period for 125000 Hz fast pwm carrier frequency = 14 bits Timer1.pwm(AUDIO_CHANNEL_1_highByte_PIN, 0); // pwm pin, 0% duty cycle, ie. 0 signal Timer1.pwm(AUDIO_CHANNEL_1_lowByte_PIN, 0); // pwm pin, 0% duty cycle, ie. 0 signal // audio output interrupt on timer 2, sets the pwm levels of timer 1 setupTimer2(); } /* set up Timer 2 using modified FrequencyTimer2 library */ void dummy() {} static void backupPreMozziTimer2() { // backup Timer2 register values #if defined(TCCR2A) pre_mozzi_TCCR2A = TCCR2A; pre_mozzi_TCCR2B = TCCR2B; pre_mozzi_OCR2A = OCR2A; pre_mozzi_TIMSK2 = TIMSK2; #elif defined(TCCR2) pre_mozzi_TCCR2 = TCCR2; pre_mozzi_OCR2 = OCR2; pre_mozzi_TIMSK = TIMSK; #elif defined(TCCR4A) pre_mozzi_TCCR4B = TCCR4A; pre_mozzi_TCCR4B = TCCR4B; pre_mozzi_TCCR4B = TCCR4C; pre_mozzi_TCCR4B = TCCR4D; pre_mozzi_TCCR4B = TCCR4E; pre_mozzi_OCR4C = OCR4C; pre_mozzi_TIMSK4 = TIMSK4; #endif } // audio output interrupt on timer 2 (or 4 on ATMEGA32U4 cpu), sets the pwm // levels of timer 2 static void setupTimer2() { backupPreMozziTimer2(); // to reset while pausing unsigned long period = F_CPU / AUDIO_RATE; FrequencyTimer2::setPeriodCPUCycles(period); FrequencyTimer2::setOnOverflow(dummy); FrequencyTimer2::enable(); } #if defined(TIMER2_COMPA_vect) ISR(TIMER2_COMPA_vect) #elif defined(TIMER2_COMP_vect) ISR(TIMER2_COMP_vect) #elif defined(TIMER4_COMPA_vect) ISR(TIMER4_COMPA_vect) #else #error \ "This board does not have a hardware timer which is compatible with FrequencyTimer2" void dummy_function(void) #endif { #if (USE_AUDIO_INPUT == true) adc_count = 0; startSecondAudioADC(); #endif // read about dual pwm at // http://www.openmusiclabs.com/learning/digital/pwm-dac/dual-pwm-circuits/ // sketches at http://wiki.openmusiclabs.com/wiki/PWMDAC, // http://wiki.openmusiclabs.com/wiki/MiniArDSP // if (!output_buffer.isEmpty()){ unsigned int out = output_buffer.read(); // 14 bit, 7 bits on each pin // AUDIO_CHANNEL_1_highByte_REGISTER = out >> 7; // B00111111 10000000 becomes // B1111111 // try to avoid looping over 7 shifts - need to check timing or disassemble to // see what really happens unsigned int out_high = out<<1; // B00111111 // 10000000 becomes B01111111 00000000 // AUDIO_CHANNEL_1_highByte_REGISTER = out_high >> 8; // B01111111 00000000 // produces B01111111 AUDIO_CHANNEL_1_lowByte_REGISTER = out & 127; /* Atmega manual, p123 The high byte (OCR1xH) has to be written first. When the high byte I/O location is written by the CPU, the TEMP Register will be updated by the value written. Then when the low byte (OCR1xL) is written to the lower eight bits, the high byte will be copied into the upper 8-bits of either the OCR1x buffer or OCR1x Compare Register in the same system clock cycle. */ AUDIO_CHANNEL_1_highByte_REGISTER = out >> AUDIO_BITS_PER_REGISTER; AUDIO_CHANNEL_1_lowByte_REGISTER = out & ((1 << AUDIO_BITS_PER_REGISTER) - 1); } // end of HIFI #endif //----------------------------------------------------------------------------------------------------------------- static void updateControlWithAutoADC() { updateControl(); /* #if (USE_AUDIO_INPUT==true) adc_count = 0; startSecondAudioADC(); #endif */ adcStartReadCycle(); } static void startControl(unsigned int control_rate_hz) { update_control_counter = 0; update_control_timeout = AUDIO_RATE / control_rate_hz; } void startMozzi(int control_rate_hz) { setupMozziADC(); // you can use setupFastAnalogRead() with FASTER or FASTEST // in setup() if desired (not for Teensy 3.* ) // delay(200); // so AutoRange doesn't read 0 to start with startControl(control_rate_hz); #if (AUDIO_MODE == STANDARD) || (AUDIO_MODE == STANDARD_PLUS) || \ IS_STM32() // Sorry, this is really hacky. But on STM32 regular and HIFI // audio modes are so similar to set up, that we do it all in one // function. startAudioStandard(); #elif (AUDIO_MODE == HIFI) startAudioHiFi(); #endif } void stopMozzi() { #if IS_TEENSY3() timer1.end(); #elif IS_STM32() audio_update_timer.pause(); #elif IS_ESP8266() #if (ESP_AUDIO_OUT_MODE != PDM_VIA_SERIAL) i2s_end(); #else output_stopped = true; // NOTE: No good way to stop the serial output itself, // but probably not needed, anyway #endif #elif IS_SAMD21() #else noInterrupts(); // restore backed up register values TCCR1A = pre_mozzi_TCCR1A; TCCR1B = pre_mozzi_TCCR1B; OCR1A = pre_mozzi_OCR1A; TIMSK1 = pre_mozzi_TIMSK1; #if (AUDIO_MODE == HIFI) #if defined(TCCR2A) TCCR2A = pre_mozzi_TCCR2A; TCCR2B = pre_mozzi_TCCR2B; OCR2A = pre_mozzi_OCR2A; TIMSK2 = pre_mozzi_TIMSK2; #elif defined(TCCR2) TCCR2 = pre_mozzi_TCCR2; OCR2 = pre_mozzi_OCR2; TIMSK = pre_mozzi_TIMSK; #elif defined(TCCR4A) TCCR4B = pre_mozzi_TCCR4A; TCCR4B = pre_mozzi_TCCR4B; TCCR4B = pre_mozzi_TCCR4C; TCCR4B = pre_mozzi_TCCR4D; TCCR4B = pre_mozzi_TCCR4E; OCR4C = pre_mozzi_OCR4C; TIMSK4 = pre_mozzi_TIMSK4; #endif #endif #endif interrupts(); } unsigned long audioTicks() { #if (IS_ESP8266() && (ESP_AUDIO_OUT_MODE != PDM_VIA_SERIAL)) #if ((ESP_AUDIO_OUT_MODE == PDM_VIA_I2S) && (PDM_RESOLUTION != 1)) return (samples_written_to_buffer - ((output_buffer_size - i2s_available()) / PDM_RESOLUTION)); #else return (samples_written_to_buffer - (output_buffer_size - i2s_available())); #endif #else return output_buffer.count(); #endif } unsigned long mozziMicros() { return audioTicks() * MICROS_PER_AUDIO_TICK; } // Unmodified TimerOne.cpp has TIMER3_OVF_vect. // Watch out if you update the library file. // The symptom will be no sound. // ISR(TIMER1_OVF_vect) // { // Timer1.isrCallback(); // }
29.472895
130
0.68356
[ "object" ]
d765460cf2c792b4eee6cabf2583fb1d35eb395f
3,187
cpp
C++
firmware/motor_controller/src/Sonar.cpp
focusrobotics/explorer
2b3c75217783830026646fe967b6d06641877642
[ "MIT" ]
null
null
null
firmware/motor_controller/src/Sonar.cpp
focusrobotics/explorer
2b3c75217783830026646fe967b6d06641877642
[ "MIT" ]
null
null
null
firmware/motor_controller/src/Sonar.cpp
focusrobotics/explorer
2b3c75217783830026646fe967b6d06641877642
[ "MIT" ]
null
null
null
/**************************************************************************** * Copyright (c) 2019 by Focus Robotics. All rights reserved. * * 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. * * Created By : Andrew Worcester * Creation_Date: Mon Dec 2 2019 * * Brief Description: * * Functionality: * * Issues: * * Limitations: * * Testing: * ******************************************************************************/ #include "Sonar.h" //#define TRIGGER_PIN 32 // Arduino pin tied to trigger pin on the ultrasonic sensor. //#define ECHO_PIN 33 // Arduino pin tied to echo pin on the ultrasonic sensor. //#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. // Sonar // Create the Sonar control object //NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. Sonar::Sonar(int tp, int ep, int md) {} Sonar::~Sonar() {} void Sonar::setup() {} void Sonar::loop() {} /* void SonarAvoidStuff() { // Sonar data is noisy! Should require a few pings in a row to something close before stopping unsigned int cm = sonar.ping_cm(); // Send ping, get distance in cm if(cm>0 && cm<30) { loc.turnAround(); loops--; Serial.print("Found obstacle. Turning around with left and right counts: "); loc.enc.printCounts(); } // Encoder stuff // Using encoder data to keep the robot going straight // This is and incredibly basic first attempt if(loc.enc.getLeftCount() > loc.enc.getRightCount()) { loc.rMotorPower++; loc.rMotor->setSpeed(loc.rMotorPower); } if(loc.enc.getLeftCount() < loc.enc.getRightCount()) { loc.rMotorPower--; loc.rMotor->setSpeed(loc.rMotorPower); } // Sonar delay shouldn't really be in the main loop like this, it should be something that is handled // by checking milis in a sonar object which is called to check and optionally update each time // through the loop delay(50); // 50ms delay between sonar pings, I think at least 30ms was suggested if(loops==0) { loc.stopMotors(); for(;;) { delay(1000); } } } */
36.632184
131
0.675871
[ "object" ]
d7655807293b461407211db1f179b13dd9a2b16c
19,647
cxx
C++
Servers/ServerManager/vtkSMDataLabelRepresentationProxy.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
1
2016-05-09T00:36:44.000Z
2016-05-09T00:36:44.000Z
Servers/ServerManager/vtkSMDataLabelRepresentationProxy.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
null
null
null
Servers/ServerManager/vtkSMDataLabelRepresentationProxy.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
3
2015-05-14T21:18:53.000Z
2022-03-07T02:53:45.000Z
/*========================================================================= Program: ParaView Module: $RCSfile: vtkSMDataLabelRepresentationProxy.cxx,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkSMDataLabelRepresentationProxy.h" #include "vtkClientServerStream.h" #include "vtkSMDoubleVectorProperty.h" #include "vtkInformation.h" #include "vtkMPIMoveData.h" #include "vtkObjectFactory.h" #include "vtkProcessModule.h" #include "vtkProp3D.h" #include "vtkPVDataInformation.h" #include "vtkPVOptions.h" #include "vtkSMInputProperty.h" #include "vtkSMIntVectorProperty.h" #include "vtkSMProxyProperty.h" #include "vtkSMRenderViewProxy.h" #include "vtkSMSourceProxy.h" #include "vtkSMStringVectorProperty.h" #include "vtkUnstructuredGrid.h" #include "vtkSMIntVectorProperty.h" vtkStandardNewMacro(vtkSMDataLabelRepresentationProxy); vtkCxxRevisionMacro(vtkSMDataLabelRepresentationProxy, "Revision: 1.1$"); //----------------------------------------------------------------------------- vtkSMDataLabelRepresentationProxy::vtkSMDataLabelRepresentationProxy() { this->CollectProxy = 0; this->UpdateSuppressorProxy = 0; this->MapperProxy = 0; this->ActorProxy = 0; this->TextPropertyProxy = 0; this->GeometryIsValid = 0; this->CellCenterFilter = 0; this->CellActorProxy = 0; this->CellMapperProxy = 0; this->CellTextPropertyProxy = 0; } //----------------------------------------------------------------------------- vtkSMDataLabelRepresentationProxy::~vtkSMDataLabelRepresentationProxy() { this->CollectProxy = 0; this->UpdateSuppressorProxy = 0; this->MapperProxy = 0; this->ActorProxy = 0; this->TextPropertyProxy = 0; this->CellCenterFilter = 0; this->CellActorProxy = 0; this->CellMapperProxy = 0; this->CellTextPropertyProxy = 0; } //---------------------------------------------------------------------------- bool vtkSMDataLabelRepresentationProxy::AddToView(vtkSMViewProxy* view) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(view); if (!renderView) { vtkErrorMacro("View must be a vtkSMRenderViewProxy."); return false; } if (!this->Superclass::AddToView(view)) { return false; } // TODO: Eventually we may want to put the label actors in Render3D //renderView->AddPropToRenderer(this->ActorProxy); //renderView->AddPropToRenderer(this->CellActorProxy); renderView->AddPropToRenderer2D(this->ActorProxy); renderView->AddPropToRenderer2D(this->CellActorProxy); return true; } //---------------------------------------------------------------------------- bool vtkSMDataLabelRepresentationProxy::RemoveFromView(vtkSMViewProxy* view) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(view); if (!renderView) { vtkErrorMacro("View must be a vtkSMRenderViewProxy."); return false; } //renderView->RemovePropFromRenderer(this->ActorProxy); //renderView->RemovePropFromRenderer(this->CellActorProxy); renderView->RemovePropFromRenderer2D(this->ActorProxy); renderView->RemovePropFromRenderer2D(this->CellActorProxy); return this->Superclass::RemoveFromView(view); } //---------------------------------------------------------------------------- bool vtkSMDataLabelRepresentationProxy::BeginCreateVTKObjects() { if (!this->Superclass::BeginCreateVTKObjects()) { return false; } this->CollectProxy = vtkSMSourceProxy::SafeDownCast( this->GetSubProxy("Collect")); this->UpdateSuppressorProxy = this->GetSubProxy("UpdateSuppressor"); this->MapperProxy = this->GetSubProxy("PointLabelMapper"); this->ActorProxy = this->GetSubProxy("PointLabelProp2D"); this->TextPropertyProxy = this->GetSubProxy("PointLabelProperty"); if (!this->CollectProxy || !this->UpdateSuppressorProxy || !this->MapperProxy || !this->ActorProxy || !this->TextPropertyProxy) { vtkErrorMacro("Not all required subproxies were defined."); return false; } this->CellCenterFilter = vtkSMSourceProxy::SafeDownCast( this->GetSubProxy("CellCentersFilter")); this->CellMapperProxy = this->GetSubProxy("CellLabelMapper"); this->CellActorProxy = this->GetSubProxy("CellLabelProp2D"); this->CellTextPropertyProxy = this->GetSubProxy("CellLabelProperty"); if (!this->CellCenterFilter || !this->CellMapperProxy || !this->CellActorProxy || !this->CellTextPropertyProxy) { vtkErrorMacro("Not all required subproxies were defined."); return false; } this->CollectProxy->SetServers(vtkProcessModule::CLIENT_AND_SERVERS); this->UpdateSuppressorProxy->SetServers(vtkProcessModule::CLIENT_AND_SERVERS); this->MapperProxy->SetServers( vtkProcessModule::CLIENT | vtkProcessModule::RENDER_SERVER); this->ActorProxy->SetServers( vtkProcessModule::CLIENT | vtkProcessModule::RENDER_SERVER); this->TextPropertyProxy->SetServers( vtkProcessModule::CLIENT | vtkProcessModule::RENDER_SERVER); this->CellCenterFilter->SetServers(vtkProcessModule::CLIENT_AND_SERVERS); this->CellMapperProxy->SetServers( vtkProcessModule::CLIENT | vtkProcessModule::RENDER_SERVER); this->CellActorProxy->SetServers( vtkProcessModule::CLIENT | vtkProcessModule::RENDER_SERVER); this->CellTextPropertyProxy->SetServers( vtkProcessModule::CLIENT | vtkProcessModule::RENDER_SERVER); return true; } //---------------------------------------------------------------------------- bool vtkSMDataLabelRepresentationProxy::EndCreateVTKObjects() { // Init UpdateSuppressor so that my pipeline knows what portion to do. vtkClientServerStream stream; vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); stream << vtkClientServerStream::Invoke << pm->GetProcessModuleID() << "GetNumberOfLocalPartitions" << vtkClientServerStream::End << vtkClientServerStream::Invoke << this->UpdateSuppressorProxy->GetID() << "SetUpdateNumberOfPieces" << vtkClientServerStream::LastResult << vtkClientServerStream::End; stream << vtkClientServerStream::Invoke << pm->GetProcessModuleID() << "GetPartitionId" << vtkClientServerStream::End << vtkClientServerStream::Invoke << this->UpdateSuppressorProxy->GetID() << "SetUpdatePiece" << vtkClientServerStream::LastResult << vtkClientServerStream::End; pm->SendStream(this->ConnectionID, this->UpdateSuppressorProxy->GetServers(), stream); // There used to be a check to ensure that the data type of input is vtkDataSet. // I've taken that out since it would cause excution of the extract selection // filter. We can put that back if needed. this->Connect(this->GetInputProxy(), this->CollectProxy, "Input", this->OutputPort); this->SetupPipeline(); this->SetupDefaults(); return this->Superclass::EndCreateVTKObjects(); } //----------------------------------------------------------------------------- void vtkSMDataLabelRepresentationProxy::SetupPipeline() { vtkSMProxyProperty* pp; vtkClientServerStream stream; vtkSMIntVectorProperty *otype = vtkSMIntVectorProperty::SafeDownCast( this->CollectProxy->GetProperty("OutputDataType")); if (otype != NULL) { otype->SetElement(0,4); //vtkUnstructuredGrid } stream << vtkClientServerStream::Invoke << this->CollectProxy->GetID() << "GetOutputPort" << vtkClientServerStream::End; stream << vtkClientServerStream::Invoke << this->UpdateSuppressorProxy->GetID() << "SetInputConnection" << vtkClientServerStream::LastResult << vtkClientServerStream::End; vtkProcessModule::GetProcessModule()->SendStream( this->ConnectionID, vtkProcessModule::CLIENT|vtkProcessModule::DATA_SERVER, stream); // Now send to the render server. // This order of sending first to CLIENT|DATA_SERVER and then to render server // ensures that the connections are set up correctly even when data server and // render server are the same. stream << vtkClientServerStream::Invoke << this->CollectProxy->GetID() << "GetOutputPort" << vtkClientServerStream::End; stream << vtkClientServerStream::Invoke << this->UpdateSuppressorProxy->GetID() << "SetInputConnection" << vtkClientServerStream::LastResult << vtkClientServerStream::End; vtkProcessModule::GetProcessModule()->SendStream( this->ConnectionID, vtkProcessModule::RENDER_SERVER, stream); this->Connect(this->UpdateSuppressorProxy, this->MapperProxy); pp = vtkSMProxyProperty::SafeDownCast( this->MapperProxy->GetProperty("LabelTextProperty")); if (!pp) { vtkErrorMacro("Failed to find property LabelTextProperty."); return; } pp->RemoveAllProxies(); pp->AddProxy(this->TextPropertyProxy); this->MapperProxy->UpdateVTKObjects(); pp = vtkSMProxyProperty::SafeDownCast( this->ActorProxy->GetProperty("Mapper")); if (!pp) { vtkErrorMacro("Failed to find property Mapper on ActorProxy."); return; } pp->RemoveAllProxies(); pp->AddProxy(this->MapperProxy); this->ActorProxy->UpdateVTKObjects(); // Set up Cell Centers pipeline this->Connect(this->UpdateSuppressorProxy, this->CellCenterFilter); this->Connect(this->CellCenterFilter, this->CellMapperProxy); pp = vtkSMProxyProperty::SafeDownCast( this->CellMapperProxy->GetProperty("LabelTextProperty")); if (!pp) { vtkErrorMacro("Failed to find property LabelTextProperty on CellMapperProxy."); return; } pp->RemoveAllProxies(); pp->AddProxy(this->CellTextPropertyProxy); this->CellMapperProxy->UpdateVTKObjects(); pp = vtkSMProxyProperty::SafeDownCast( this->CellActorProxy->GetProperty("Mapper")); if (!pp) { vtkErrorMacro("Failed to find property Mapper on CellActorProxy."); return; } pp->RemoveAllProxies(); pp->AddProxy(this->CellMapperProxy); this->CellActorProxy->UpdateVTKObjects(); } //----------------------------------------------------------------------------- void vtkSMDataLabelRepresentationProxy::SetupDefaults() { vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); vtkClientServerStream stream; vtkSMIntVectorProperty* ivp; // Collect filter needs the socket controller use to communicate between // data-server root and the client. stream << vtkClientServerStream::Invoke << pm->GetProcessModuleID() << "GetSocketController" << pm->GetConnectionClientServerID(this->ConnectionID) << vtkClientServerStream::End; stream << vtkClientServerStream::Invoke << this->CollectProxy->GetID() << "SetSocketController" << vtkClientServerStream::LastResult << vtkClientServerStream::End; pm->SendStream(this->ConnectionID, vtkProcessModule::CLIENT_AND_SERVERS, stream); // Collect filter needs the MPIMToNSocketConnection to communicate between // render server and data server nodes. stream << vtkClientServerStream::Invoke << this->CollectProxy->GetID() << "SetMPIMToNSocketConnection" << pm->GetMPIMToNSocketConnectionID(this->ConnectionID) << vtkClientServerStream::End; pm->SendStream(this->ConnectionID, vtkProcessModule::RENDER_SERVER|vtkProcessModule::DATA_SERVER, stream); // Set the server flag on the collect filter to correctly identify each // processes. stream << vtkClientServerStream::Invoke << this->CollectProxy->GetID() << "SetServerToRenderServer" << vtkClientServerStream::End; pm->SendStream(this->ConnectionID, vtkProcessModule::RENDER_SERVER, stream); stream << vtkClientServerStream::Invoke << this->CollectProxy->GetID() << "SetServerToDataServer" << vtkClientServerStream::End; pm->SendStream(this->ConnectionID, vtkProcessModule::DATA_SERVER, stream); stream << vtkClientServerStream::Invoke << this->CollectProxy->GetID() << "SetServerToClient" << vtkClientServerStream::End; pm->SendStream(this->ConnectionID, vtkProcessModule::CLIENT, stream); ivp = vtkSMIntVectorProperty::SafeDownCast( this->CollectProxy->GetProperty("MoveMode")); if (!ivp) { vtkErrorMacro("Failed to find property MoveMode on CollectProxy."); return; } ivp->SetElement(0, 2); // Clone mode. this->CollectProxy->UpdateVTKObjects(); ivp = vtkSMIntVectorProperty::SafeDownCast( this->TextPropertyProxy->GetProperty("FontSize")); if (!ivp) { vtkErrorMacro("Failed to find property FontSize on TextPropertyProxy."); return; } ivp->SetElement(0, 18); ivp = vtkSMIntVectorProperty::SafeDownCast( this->TextPropertyProxy->GetProperty("Justification")); if (!ivp) { vtkErrorMacro("Failed to find property Justification on CellTextPropertyProxy."); return; } ivp->SetElement(0, 1); //Center justified this->TextPropertyProxy->UpdateVTKObjects(); ivp = vtkSMIntVectorProperty::SafeDownCast( this->GetProperty("CellLabelVisibility")); ivp->SetElement(0, 0); this->UpdateProperty("CellLabelVisibility"); // Set default Cell Text property ivp = vtkSMIntVectorProperty::SafeDownCast( this->CellTextPropertyProxy->GetProperty("FontSize")); if (!ivp) { vtkErrorMacro("Failed to find property FontSize on CellTextPropertyProxy."); return; } ivp->SetElement(0, 24); ivp = vtkSMIntVectorProperty::SafeDownCast( this->CellTextPropertyProxy->GetProperty("Justification")); if (!ivp) { vtkErrorMacro("Failed to find property Justification on CellTextPropertyProxy."); return; } ivp->SetElement(0, 1); //Center justified vtkSMDoubleVectorProperty* dvp = vtkSMDoubleVectorProperty::SafeDownCast( this->CellTextPropertyProxy->GetProperty("Color")); if (!dvp) { vtkErrorMacro("Failed to find property Color on CellTextPropertyProxy."); return; } dvp->SetElements3(0.0, 1.0, 0.0); this->CellTextPropertyProxy->UpdateVTKObjects(); } //----------------------------------------------------------------------------- void vtkSMDataLabelRepresentationProxy::Update( vtkSMViewProxy* view) { if (!this->ObjectsCreated) { vtkErrorMacro("Objects not created yet!"); return; } if (!this->GetInputProxy()) { vtkErrorMacro("Input is not set yet!"); return; } // check if we should UseCache if (this->ViewInformation) { if (this->ViewInformation->Has(vtkSMViewProxy::USE_CACHE())) { if(this->ViewInformation->Get(vtkSMViewProxy::USE_CACHE())>0) { if (this->ViewInformation->Has(vtkSMViewProxy::CACHE_TIME())) { vtkSMDoubleVectorProperty* dvp = vtkSMDoubleVectorProperty::SafeDownCast( this->UpdateSuppressorProxy->GetProperty("CacheUpdate")); dvp->SetElement(0, this->ViewInformation->Get(vtkSMViewProxy::CACHE_TIME())); this->UpdateSuppressorProxy->UpdateProperty("CacheUpdate", 1); return; } } } } if (this->GeometryIsValid || !this->UpdateSuppressorProxy) { return; } this->GeometryIsValid = 1; this->UpdateSuppressorProxy->InvokeCommand("ForceUpdate"); this->Superclass::Update(view); // this->InvokeEvent(vtkSMViewProxy::ForceUpdateEvent); } //----------------------------------------------------------------------------- void vtkSMDataLabelRepresentationProxy::SetUpdateTime(double time) { if (!this->ObjectsCreated) { vtkErrorMacro("Objects not created!"); return; } vtkSMDoubleVectorProperty* dvp = vtkSMDoubleVectorProperty::SafeDownCast( this->UpdateSuppressorProxy->GetProperty("UpdateTime")); dvp->SetElement(0, time); // UpdateTime is immediate update, so no need to update. // Go upstream to the reader and mark it modified. this->MarkUpstreamModified(); } //---------------------------------------------------------------------------- void vtkSMDataLabelRepresentationProxy::MarkModified(vtkSMProxy* modifiedProxy) { if (modifiedProxy != this) { this->GeometryIsValid = 0; } this->Superclass::MarkModified(modifiedProxy); } //----------------------------------------------------------------------------- void vtkSMDataLabelRepresentationProxy::InvalidateGeometryInternal(int useCache) { if (!useCache) { this->GeometryIsValid = 0; if (this->UpdateSuppressorProxy) { vtkSMProperty *p = this->UpdateSuppressorProxy->GetProperty("RemoveAllCaches"); p->Modified(); this->UpdateSuppressorProxy->UpdateVTKObjects(); } } } //---------------------------------------------------------------------------- void vtkSMDataLabelRepresentationProxy::SetPointFontSizeCM(int size) { if (this->TextPropertyProxy) { vtkSMIntVectorProperty* ivp; ivp = vtkSMIntVectorProperty::SafeDownCast( this->TextPropertyProxy->GetProperty("FontSize")); if (!ivp) { vtkErrorMacro("Failed to find property FontSize on TextPropertyProxy."); return; } ivp->SetElement(0, size); this->TextPropertyProxy->UpdateVTKObjects(); } } //---------------------------------------------------------------------------- int vtkSMDataLabelRepresentationProxy::GetPointFontSizeCM() { if (this->TextPropertyProxy) { vtkSMIntVectorProperty* ivp; ivp = vtkSMIntVectorProperty::SafeDownCast( this->TextPropertyProxy->GetProperty("FontSize")); if (!ivp) { vtkErrorMacro("Failed to find property FontSize on TextPropertyProxy."); return 0; } return ivp->GetElement(0); } return 0; } //---------------------------------------------------------------------------- void vtkSMDataLabelRepresentationProxy::SetCellFontSizeCM(int size) { if (this->CellTextPropertyProxy) { vtkSMIntVectorProperty* ivp; ivp = vtkSMIntVectorProperty::SafeDownCast( this->CellTextPropertyProxy->GetProperty("FontSize")); if (!ivp) { vtkErrorMacro("Failed to find property FontSize on TextPropertyProxy."); return; } ivp->SetElement(0, size); this->CellTextPropertyProxy->UpdateVTKObjects(); } } //---------------------------------------------------------------------------- int vtkSMDataLabelRepresentationProxy::GetCellFontSizeCM() { if (this->CellTextPropertyProxy) { vtkSMIntVectorProperty* ivp; ivp = vtkSMIntVectorProperty::SafeDownCast( this->CellTextPropertyProxy->GetProperty("FontSize")); if (!ivp) { vtkErrorMacro("Failed to find property FontSize on TextPropertyProxy."); return 0; } return ivp->GetElement(0); } return 0; } //----------------------------------------------------------------------------- bool vtkSMDataLabelRepresentationProxy::GetVisibility() { vtkSMIntVectorProperty* ivp = vtkSMIntVectorProperty::SafeDownCast( this->GetProperty("PointLabelVisibility")); if(ivp->GetElement(0)) { return true; } ivp = vtkSMIntVectorProperty::SafeDownCast( this->GetProperty("CellLabelVisibility")); if(ivp->GetElement(0)) { return true; } return false; } //----------------------------------------------------------------------------- void vtkSMDataLabelRepresentationProxy::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "GeometryIsValid: " << this->GeometryIsValid << endl; }
32.58209
85
0.662137
[ "render" ]
d7694ac46fc8d643f4b0cecb50d82f111a783799
24,230
cpp
C++
client/src/main.cpp
kkevlar/TARgETS
d729e94e246470dbee4a20de1b46b615818bcd97
[ "MIT" ]
4
2019-12-10T22:00:47.000Z
2020-02-04T23:41:46.000Z
client/src/main.cpp
kkevlar/TARgETS
d729e94e246470dbee4a20de1b46b615818bcd97
[ "MIT" ]
1
2019-12-13T18:53:54.000Z
2019-12-13T18:55:19.000Z
client/src/main.cpp
kkevlar/TARgETS
d729e94e246470dbee4a20de1b46b615818bcd97
[ "MIT" ]
null
null
null
#include <glad/glad.h> #include <algorithm> #include <iostream> #include <thread> #include <vector> #include "Billboard.h" #include "Cube.h" #include "GLSL.h" #include "MatrixStack.h" #include "Program.h" #include "message.h" #include "webclient.h" #include "Collision.h" #include "Shape.h" #include "ShotManager.h" #include "Skybox.h" #include "WindowManager.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> using namespace glm; using namespace std; #define PI_CONST ((float)(103993.0f / 33102.0f)) #define PLAYER_CURSOR_COUNT 64 static uint8_t tmpWriteBuf[256]; double get_last_elapsed_time() { static double lasttime = glfwGetTime(); double actualtime = glfwGetTime(); double difference = actualtime - lasttime; lasttime = actualtime; return difference; } class camera { public: glm::vec3 pos, rot; int w, a, s, d; camera() { w = a = s = d = 0; pos = glm::vec3(0, 0, 0); rot = glm::vec3(0, 0, 0); } glm::mat4 process(double ftime) { float speed = 0; float yangle = 0; if (a == 1) yangle = -1 * ftime; else if (d == 1) yangle = 1 * ftime; rot.y += yangle * 2; glm::mat4 R = glm::rotate(glm::mat4(1), rot.y, glm::vec3(0, 1, 0)); glm::vec4 dir = glm::vec4(0, 0, speed, 1); dir = dir * R; pos += glm::vec3(dir.x, dir.y, dir.z); glm::mat4 T = glm::translate(glm::mat4(1), pos); return R * T; } }; camera mycam; class Application : public EventCallbacks { public: int kn = 0; int md = 0; int rmd = 0; WindowManager *windowManager = nullptr; // Our shader program std::shared_ptr<Program> prog, shapeprog; std::shared_ptr<Program> glowprog; std::shared_ptr<Program> bbprog; std::shared_ptr<Program> skyboxprog; // Contains vertex information for OpenGL GLuint VertexArrayID; GLuint CylinderArrayID; // Data necessary to give our box to OpenGL GLuint VertexBufferID, VertexColorIDBox, IndexBufferIDBox; GLuint CylinderVertexBufferId, CylinderVertexColorId, CylinderBufferIndeciesID; Shape shape; MessageContext *msg_context; CollisionHandler collision; Billboard billboard; Skybox skybox; bool playGame = 0; std::vector<CylCoords> cursors; ShotManager shots = ShotManager(PLAYER_CURSOR_COUNT); TargetManager cubes; void keyCallback( GLFWwindow *window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GL_TRUE); } if (key == GLFW_KEY_W && action == GLFW_PRESS) { mycam.w = 1; } if (key == GLFW_KEY_W && action == GLFW_RELEASE) { mycam.w = 0; } if (key == GLFW_KEY_S && action == GLFW_PRESS) { mycam.s = 1; } if (key == GLFW_KEY_S && action == GLFW_RELEASE) { mycam.s = 0; } if (key == GLFW_KEY_A && action == GLFW_PRESS) { mycam.a = 1; } if (key == GLFW_KEY_A && action == GLFW_RELEASE) { mycam.a = 0; } if (key == GLFW_KEY_D && action == GLFW_PRESS) { mycam.d = 1; } if (key == GLFW_KEY_D && action == GLFW_RELEASE) { mycam.d = 0; } if (key == GLFW_KEY_N && action == GLFW_PRESS) kn = 1; if (key == GLFW_KEY_N && action == GLFW_RELEASE) kn = 0; } // callback for the mouse when clicked move the triangle when helper // functions written void mouseCallback(GLFWwindow *window, int button, int action, int mods) { double posX, posY; float newPt[2]; if (action == GLFW_PRESS && button == GLFW_MOUSE_BUTTON_LEFT) { md = 1; } else if (action == GLFW_RELEASE && button == GLFW_MOUSE_BUTTON_LEFT) { md = 0; } else if (action == GLFW_PRESS && button == GLFW_MOUSE_BUTTON_RIGHT) { rmd = 1; } else if (action == GLFW_RELEASE && button == GLFW_MOUSE_BUTTON_RIGHT) { rmd = 0; } } // if the window is resized, capture the new size and reset the viewport void resizeCallback(GLFWwindow *window, int in_width, int in_height) { // get the window size - may be different then pixels for retina int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); } static inline float map( float value, float min1, float max1, float min2, float max2) { return min2 + (value - min1) * (max2 - min2) / (max1 - min1); } void initTargetManager() { for (int i = 0; i < 0x80; i++) { Target cube = Target(); cube.show = 0; cubes.elements.push_back(cube); } } /*Note that any gl calls must always happen after a GL state is initialized */ void initGeom() { string resourceDirectory = "../resources"; // try t800.obj or F18.obj ... shape.loadMesh(resourceDirectory + "/sphere.obj"); shape.resize(); shape.init(); // generate the VAO glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); // generate vertex buffer to hand off to OGL glGenBuffers(1, &VertexBufferID); // set the current state to focus on our vertex buffer glBindBuffer(GL_ARRAY_BUFFER, VertexBufferID); GLfloat cube_vertices[] = { // front -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, // back -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0, // tube 8 - 11 -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, // 12 - 15 -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0 }; // actually memcopy the data - only do this once glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_DYNAMIC_DRAW); // we need to set up the vertex array glEnableVertexAttribArray(0); // key function to get up how many elements to pull out at a time (3) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void *)0); // color GLfloat cube_colors[] = { // front colors 0.8, 0.8, 1.0, 0.8, 0.8, 1.0, 0.8, 0.8, 1.0, 0.8, 0.8, 1.0, 1, 0.8, 1, 1, 0.8, 1, 1, 0.8, 1, 1, 0.8, 1, 0.5, 1.0, 1.0, 0.5, 1.0, 1.0, 0.5, 1.0, 1.0, 0.5, 1.0, 1.0, 1.0, 1.0, 0.8, 1.0, 1.0, 0.8, 1.0, 1.0, 0.8, 1.0, 1.0, 0.8, }; glGenBuffers(1, &VertexColorIDBox); // set the current state to focus on our vertex buffer glBindBuffer(GL_ARRAY_BUFFER, VertexColorIDBox); glBufferData(GL_ARRAY_BUFFER, sizeof(cube_colors), cube_colors, GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void *)0); glGenBuffers(1, &IndexBufferIDBox); // set the current state to focus on our vertex buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBufferIDBox); GLushort cube_elements[] = { // front 0, 1, 2, 2, 3, 0, // back 7, 6, 5, 5, 4, 7, // tube 8-11, 12-15 8, 12, 13, 8, 13, 9, 9, 13, 14, 9, 14, 10, 10, 14, 15, 10, 15, 11, 11, 15, 12, 11, 12, 8 }; glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_elements), cube_elements, GL_STATIC_DRAW); glBindVertexArray(0); billboard.initEverythingElse(bbprog); skybox.init(skyboxprog); } // General OGL initialization - set OGL state here void init(const std::string &resourceDirectory) { GLSL::checkVersion(); // Set background color. glClearColor(0.1f, 0.1f, 0.1f, 1.0f); // Enable z-buffer test. glEnable(GL_DEPTH_TEST); // Enable blending/transparency glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // glCullFace(GL_FRONT_AND_BACK); // Initialize the GLSL program. prog = std::make_shared<Program>(); prog->setVerbose(true); prog->setShaderNames(resourceDirectory + "/shader_vertex.glsl", resourceDirectory + "/shader_fragment.glsl"); if (!prog->init()) { std::cerr << "One or more shaders failed to compile... exiting!" << std::endl; exit(1); // make a breakpoint here and check the output window for // the error message! } prog->addUniform("P"); prog->addUniform("V"); prog->addUniform("M"); prog->addUniform("bonuscolor"); prog->addAttribute("vertPos"); prog->addAttribute("vertColor"); // Initialize the GLSL program. shapeprog = std::make_shared<Program>(); shapeprog->setVerbose(true); shapeprog->setShaderNames(resourceDirectory + "/shape_vertex.glsl", resourceDirectory + "/shape_fragment.glsl"); if (!shapeprog->init()) { std::cerr << "One or more shaders failed to compile... exiting!" << std::endl; exit(1); // make a breakpoint here and check the output window for // the error message! } shapeprog->addUniform("P"); shapeprog->addUniform("V"); shapeprog->addUniform("M"); shapeprog->addUniform("camPos"); shapeprog->addUniform("bonuscolor"); shapeprog->addAttribute("vertPos"); shapeprog->addAttribute("vertNor"); shapeprog->addAttribute("vertTex"); glowprog = std::make_shared<Program>(); glowprog->setVerbose(true); glowprog->setShaderNames(resourceDirectory + "/glow_vertex.glsl", resourceDirectory + "/glow_fragment.glsl"); if (!glowprog->init()) { std::cerr << "One or more shaders failed to compile... exiting!" << std::endl; exit(1); // make a breakpoint here and check the output window for // the error message! } glowprog->addUniform("P"); glowprog->addUniform("V"); glowprog->addUniform("M"); glowprog->addUniform("camPos"); glowprog->addUniform("bonuscolor"); glowprog->addAttribute("vertPos"); glowprog->addAttribute("vertNor"); glowprog->addAttribute("vertTex"); bbprog = billboard.initShader(resourceDirectory); skyboxprog = std::make_shared<Program>(); skyboxprog->setVerbose(true); skyboxprog->setShaderNames(resourceDirectory + "/skybox_vertex.glsl", resourceDirectory + "/skybox_frag.glsl"); if (!skyboxprog->init()) { std::cerr << "One or more shaders failed to compile... exiting!" << std::endl; exit(1); // make a breakpoint here and check the output window for // the error message! } skyboxprog->addUniform("P"); skyboxprog->addUniform("V"); skyboxprog->addUniform("M"); skyboxprog->addUniform("skybox_texture"); skyboxprog->addAttribute("vertPos"); skyboxprog->addAttribute("vertTex"); } void game_render(double frametime, glm::mat4 P, glm::mat4 V) { // Get current frame buffer size. int width, height; glm::mat4 M; glfwGetFramebufferSize(windowManager->getHandle(), &width, &height); double xpos, ypos; glfwGetCursorPos(windowManager->getHandle(), &xpos, &ypos); float angle = map(xpos, 0, width, sin(-PI_CONST * 0.25), sin(PI_CONST * 0.25)); angle = asin(-angle); angle -= fmod(mycam.rot.y, 2 * PI_CONST); // angle -= mycam.rot.y; angle += PI_CONST; float vangle = map(-ypos, -height, 0, 0, 1); static int sendCursorCount = 0; if (sendCursorCount == 0) { assignBytesFromFloat(tmpWriteBuf, angle, 5); assignBytesFromFloat(tmpWriteBuf + 5, vangle, 5); clientMsgWrite(MSG_CURSOR_UPDATE, tmpWriteBuf, 10); } sendCursorCount = (sendCursorCount + 1) & 0x3; CylCoords myCursor; myCursor.angle = angle; myCursor.height = vangle; myCursor.calc_result(); if (md && msg_context->player_id >= 0) { shots.shootAndSendToServer(myCursor.result.pos, msg_context->player_id, true, glfwGetTime()); } shots.advanceShots(frametime); if (msg_context->player_id >= 0) { shots.fillCollisionHandlerWithMyShots(collision, msg_context->player_id); } if (msg_context->player_id >= 0) { myCursor.calc_result(); M = myCursor.result.calc_scale(myCursor.result.calc_no_scale()); /* This shouldn't need to happen buttttt*/ cursors.data()[msg_context->player_id].show = 1; /* glUniformMatrix4fv(prog->getUniform("M"), 1, GL_FALSE, &M[0][0]); vec3 clr = msg_context->color_list.get_color(msg_context->player_id); glUniform3f(prog->getUniform("bonuscolor"), clr.x, clr.y, clr.z); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, (void *)0);*/ } msg_context->mutex_cursors.lock(); for (int i = 0; i < cursors.size(); i++) { if (cursors.data()[i].show) { // if (msg_context->player_id == i) continue; vec3 clr = msg_context->color_list.get_color(i); cursors.data()[i].calc_result(); if (msg_context->player_id == i) { myCursor.calc_result(); M = myCursor.result.calc_scale( myCursor.result.calc_no_scale()); if (glm::distance(cursors.data()[i].result.pos, myCursor.result.pos) > 1.0f) { float bw = sin(glfwGetTime() * 5); if (bw > 0) { vec3 white = vec3(1, 1, 1); clr = clr + white * bw; } else { clr = clr * (-bw); } } } else { M = cursors.data()[i].result.calc_scale( cursors.data()[i].result.calc_no_scale()); } glUniformMatrix4fv(prog->getUniform("M"), 1, GL_FALSE, &M[0][0]); glUniform3f(prog->getUniform("bonuscolor"), clr.x, clr.y, clr.z); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, (void *)0); } } msg_context->mutex_cursors.unlock(); static int lastRMouse = 0; msg_context->mutex_boxes.lock(); for (int i = 0; i <= cubes.elements.size(); i++) { Target *cube = &cubes.elements.data()[i]; if (cube->show) { if (!cube->hit) { cube->interp += frametime / 5; cube->interpBetween(); } else if (cube->interp < 1) { cube->interp += frametime / 2; cube->interpBetween(); } if (!cube->hit && collision.testCollision(cube->postInterp.pos, COLLISION_RADIUS)) { cube->beShot(i, msg_context->player_id, &msg_context->color_list); } if (cube->hit && cube->interp > 1) { cube->show = 0; } if (cube->hit) { glUniform3f(prog->getUniform("bonuscolor"), cube->bonuscolor.r, cube->bonuscolor.g, cube->bonuscolor.b); } else { glUniform3f(prog->getUniform("bonuscolor"), 1, 1, 1); } cube->drawTarget(prog, cubes.elements, mat4(1)); if (!cube->hit && cube->show && rmd && !lastRMouse) { if (glm::distance(cube->postInterp.pos, myCursor.result.pos) < 2) { vec3 spos = cube->postInterp.pos; spos = 1.1f * (cube->postInterp.pos - vec3(0, -8, 0)); spos += vec3(0, -8, 0); shots.shootAndSendToServer(spos, msg_context->player_id, false, glfwGetTime()); } } } } msg_context->mutex_boxes.unlock(); lastRMouse = rmd; glBindVertexArray(0); prog->unbind(); shapeprog->bind(); glUniformMatrix4fv(prog->getUniform("P"), 1, GL_FALSE, &P[0][0]); glUniformMatrix4fv(prog->getUniform("V"), 1, GL_FALSE, &V[0][0]); shots.drawShots(shapeprog, shape, msg_context->color_list); shapeprog->unbind(); glowprog->bind(); glBindVertexArray(VertexArrayID); glUniformMatrix4fv(prog->getUniform("P"), 1, GL_FALSE, &P[0][0]); glUniformMatrix4fv(prog->getUniform("V"), 1, GL_FALSE, &V[0][0]); msg_context->mutex_cursors.lock(); static float w = 0.0; w += frametime; int win = msg_context->winning_pid; if (win >= 0 && win <= PLAYER_CURSOR_COUNT) { cursors.data()[win].calc_result(); MatrixIngridients c = cursors.data()[win].result; if (win == msg_context->player_id) { myCursor.calc_result(); c = myCursor.result; } c.scale *= 1.0f + map(sin(w * 3), -1, 1, 0.1, .5f); M = c.calc_scale(c.calc_no_scale()); glUniformMatrix4fv(prog->getUniform("M"), 1, GL_FALSE, &M[0][0]); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, (void *)0); } msg_context->mutex_cursors.unlock(); glowprog->unbind(); } /****DRAW This is the most important function in your program - this is where you will actually issue the commands to draw any geometry you have set up to draw ********/ void render() { double frametime = get_last_elapsed_time(); // Get current frame buffer size. int width, height; glfwGetFramebufferSize(windowManager->getHandle(), &width, &height); float aspect = width / (float)height; glViewport(0, 0, width, height); // glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // Clear framebuffer. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Create the matrix stacks - please leave these alone for now glm::mat4 V, M, P; // View, Model and Perspective matrix V = glm::mat4(1); M = glm::mat4(1); // Apply orthographic projection.... P = glm::perspective((float)(3.14159 / 4.), (float)((float)width / (float)height), 0.1f, 1000.0f); // so much type casting... GLM metods // are quite funny ones V = mycam.process(frametime); skybox.draw(skyboxprog, P, V); static float t = 0; t += 0.01; float trans = 0; // sin(t) * 2; glm::mat4 T = glm::mat4(1.0f); // Draw the box using GLSL. prog->bind(); // send the matrices to the shaders glUniformMatrix4fv(prog->getUniform("P"), 1, GL_FALSE, &P[0][0]); glUniformMatrix4fv(prog->getUniform("V"), 1, GL_FALSE, &V[0][0]); glBindVertexArray(VertexArrayID); if (playGame) { game_render(frametime, P, V); } else { int result; result = billboard.draw(bbprog, mycam.pos, frametime, P, V); playGame = result > 2; } } }; int main(int argc, char **argv) { std::string resourceDir = "../resources"; // Where the resources are loaded from if (argc >= 2) { resourceDir = argv[1]; } Application *application = new Application(); /* your main will always include a similar set up to establish your window and GL context, etc. */ WindowManager *windowManager = new WindowManager(); windowManager->init(1920, 1080); windowManager->setEventCallbacks(application); application->windowManager = windowManager; /* This is the code that will likely change program to program as you may need to initialize or set up different data and state */ // Initialize scene. application->init(resourceDir); application->initGeom(); application->initTargetManager(); glfwSetInputMode(application->windowManager->getHandle(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN); MessageContext context; context.color_list = ColorList(); context.player_id = -1; context.winning_pid = -1; application->msg_context = &context; context.boxes = &application->cubes.elements; application->cursors = std::vector<CylCoords>(); for (int i = 0; i < PLAYER_CURSOR_COUNT; i++) { CylCoords c; c.show = 0; application->cursors.push_back(c); } context.cursors = &application->cursors; context.shots = &application->shots; clientbegin(&context); static int count = 0; bool keepReading = 1; std::thread readThread = std::thread(repeatedRead); // std::thread flushThread = std::thread(repeatedWrite); // Loop until the user closes the window. while (!glfwWindowShouldClose(windowManager->getHandle())) { // Render scene. application->render(); // Swap front and back buffers. glfwSwapBuffers(windowManager->getHandle()); // Poll for and process events. glfwPollEvents(); /*if (count == 0) { clientflush(); } count = (count + 1) & 0xF;*/ } stopRepeatedRead(); // stopRepeatedWrite(); readThread.join(); // flushThread.join(); // Quit program. windowManager->shutdown(); return 0; }
32.921196
81
0.50747
[ "geometry", "render", "shape", "vector", "model" ]
d7711d0a6838bfce58448c779fcd95388a31929d
1,124
cpp
C++
templates/void_t.cpp
IgorHersht/proxygen_ih
616a8eb899196d2a130e14c0fabcae1944e34b7d
[ "MIT" ]
7
2017-11-10T05:18:30.000Z
2021-04-29T15:38:25.000Z
templates/void_t.cpp
IgorHersht/proxygen_ih
616a8eb899196d2a130e14c0fabcae1944e34b7d
[ "MIT" ]
null
null
null
templates/void_t.cpp
IgorHersht/proxygen_ih
616a8eb899196d2a130e14c0fabcae1944e34b7d
[ "MIT" ]
null
null
null
#include <vector> #include <list> #include <set> #include <map> #include <unordered_map> #include <unordered_set> #include <deque> #include <forward_list> #include <iostream> #include <type_traits> template<typename T, typename U = void> struct is_map : std::false_type {}; template<typename T> struct is_map<T, std::void_t<typename T::key_type, typename T::mapped_type>>:std::true_type {}; class A {}; template <typename T, typename = void> struct is_iterable : std::false_type {}; template <typename T> struct is_iterable<T, std::void_t<decltype(std::declval<T>().begin()), decltype(std::declval<T>().end())>> : std::true_type {}; int main() { std::map<int, int> m; std::vector<int> v; constexpr bool s1 = is_map<decltype(m)>::value; constexpr bool s2 = is_map<decltype(v)>::value; std::cout << std::boolalpha; std::cout << is_iterable<std::vector<double>>::value << '\n'; std::cout << is_iterable<std::map<int, double>>::value << '\n'; std::cout << is_iterable<double>::value << '\n'; std::cout << is_iterable<A>::value << '\n'; int i = 0; return 0; }
24.434783
96
0.645018
[ "vector" ]
d7720a20ffd9d2a9a099bcc0e04243b973296159
3,207
cpp
C++
Sandbox/src/Example/ExampleLayer.cpp
Naheuldark/PepperMint
63d4133fec0d0d5f2709d235d68f7d90e355fdd5
[ "MIT" ]
2
2020-12-07T11:10:44.000Z
2021-09-23T16:09:12.000Z
Sandbox/src/Example/ExampleLayer.cpp
Naheuldark/PepperMint
63d4133fec0d0d5f2709d235d68f7d90e355fdd5
[ "MIT" ]
null
null
null
Sandbox/src/Example/ExampleLayer.cpp
Naheuldark/PepperMint
63d4133fec0d0d5f2709d235d68f7d90e355fdd5
[ "MIT" ]
null
null
null
#include "ExampleLayer.h" #include <imgui/imgui.h> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> ExampleLayer::ExampleLayer() : Layer("Example"), _cameraController(1280.0f / 720.0f, true) { //////////// // Square // //////////// _squareVA = PepperMint::VertexArray::Create(); // Vertex Buffer float squareVertices[5 * 4] = {-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f}; PepperMint::Ref<PepperMint::VertexBuffer> squareVB = PepperMint::VertexBuffer::Create(squareVertices, sizeof(squareVertices)); squareVB->setLayout({ {PepperMint::ShaderDataType::FLOAT3, "iPosition"}, {PepperMint::ShaderDataType::FLOAT2, "iTexCoord"}, }); _squareVA->addVertexBuffer(squareVB); // Index Buffer uint32_t squareIndices[6] = {0, 1, 2, 2, 3, 0}; PepperMint::Ref<PepperMint::IndexBuffer> squareIB = PepperMint::IndexBuffer::Create(squareIndices, sizeof(squareIndices) / sizeof(uint32_t)); _squareVA->setIndexBuffer(squareIB); ///////////// // Shaders // ///////////// auto flatColorShader = _shaderLibrary.load("assets/shaders/Flat.glsl"); auto textureShader = _shaderLibrary.load("assets/shaders/Texture.glsl"); ////////////// // Textures // ////////////// _texture = PepperMint::Texture2D::Create("assets/textures/Checkerboard.png"); _chernoTexture = PepperMint::Texture2D::Create("assets/textures/ChernoLogo.png"); textureShader->bind(); textureShader->setInt("uTexture", 0); } void ExampleLayer::onAttach() {} void ExampleLayer::onDetach() {} void ExampleLayer::onUpdate(PepperMint::Timestep iTimestep) { // Update _cameraController.onUpdate(iTimestep); // Render PepperMint::RenderCommand::SetClearColor({0.1f, 0.1f, 0.1f, 1}); PepperMint::RenderCommand::Clear(); PepperMint::Renderer::BeginScene(_cameraController.camera()); auto textureShader = _shaderLibrary.get("Texture"); auto flatColorShader = _shaderLibrary.get("Flat"); flatColorShader->bind(); flatColorShader->setFloat3("uColor", _squareColor); // Draw squares glm::mat4 scale = glm::scale(glm::mat4(1.0f), glm::vec3(0.1f)); for (int y = 0; y < 20; y++) { for (int x = 0; x < 20; x++) { glm::vec3 pos(x * 0.11f, y * 0.11f, 0.0f); glm::mat4 transform = glm::translate(glm::mat4(1.0f), pos) * scale; PepperMint::Renderer::Submit(flatColorShader, _squareVA, transform); } } _texture->bind(); PepperMint::Renderer::Submit( textureShader, _squareVA, glm::scale(glm::mat4(1.0f), glm::vec3(1.5f))); _chernoTexture->bind(); PepperMint::Renderer::Submit( textureShader, _squareVA, glm::scale(glm::mat4(1.0f), glm::vec3(1.5f))); PepperMint::Renderer::EndScene(); } void ExampleLayer::onImGuiRender() { ImGui::Begin("Settings"); ImGui::ColorEdit3("Square Color", glm::value_ptr(_squareColor)); ImGui::End(); } void ExampleLayer::onEvent(PepperMint::Event& iEvent) { _cameraController.onEvent(iEvent); }
32.393939
99
0.628313
[ "render", "transform" ]
d775fe1be673845f4f2e9e93a1239a319cf5a363
1,182
cc
C++
components/site_isolation/preloaded_isolated_origins.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/site_isolation/preloaded_isolated_origins.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/site_isolation/preloaded_isolated_origins.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/site_isolation/preloaded_isolated_origins.h" #include "components/site_isolation/buildflags.h" #include "content/public/browser/site_isolation_policy.h" #include "url/gurl.h" #if BUILDFLAG(USE_INTERNAL_ISOLATED_ORIGINS) #include "components/site_isolation/internal/google_chrome_isolated_origins.h" #endif namespace site_isolation { std::vector<url::Origin> GetBrowserSpecificBuiltInIsolatedOrigins() { std::vector<url::Origin> list; #if BUILDFLAG(USE_INTERNAL_ISOLATED_ORIGINS) // Only apply preloaded isolated origins when allowed by site isolation // policy (e.g., when memory requirements are satisfied, and when not using // full site isolation). if (content::SiteIsolationPolicy::ArePreloadedIsolatedOriginsEnabled()) { list.reserve(kNumberOfBuiltInIsolatedOrigins); for (size_t i = 0; i < kNumberOfBuiltInIsolatedOrigins; i++) list.push_back(url::Origin::Create(GURL(kBuiltInIsolatedOrigins[i]))); } #endif return list; } } // namespace site_isolation
33.771429
78
0.780034
[ "vector" ]
d7851dcc51ccb8d5f07b802b48fbb104c13ef58d
33,213
cpp
C++
src/dynode.cpp
SvenKercher/dd4
fe5bc7954ce5b9ebf093cec0e0788446bbb5878b
[ "MIT" ]
1
2018-08-18T04:13:14.000Z
2018-08-18T04:13:14.000Z
src/dynode.cpp
SvenKercher/dd4
fe5bc7954ce5b9ebf093cec0e0788446bbb5878b
[ "MIT" ]
null
null
null
src/dynode.cpp
SvenKercher/dd4
fe5bc7954ce5b9ebf093cec0e0788446bbb5878b
[ "MIT" ]
null
null
null
// Copyright (c) 2016-2018 Duality Blockchain Solutions Developers // Copyright (c) 2014-2017 The Dash Core Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "dynode.h" #include "activedynode.h" #include "base58.h" #include "chain.h" #include "dynode-payments.h" #include "dynode-sync.h" #include "dynodeman.h" #include "fluid.h" #include "init.h" #include "messagesigner.h" #include "netbase.h" #include "script/standard.h" #include "util.h" #include "validation.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif // ENABLE_WALLET #include <boost/lexical_cast.hpp> CDynode::CDynode() : dynode_info_t{ DYNODE_ENABLED, PROTOCOL_VERSION, GetAdjustedTime()}, fAllowMixingTx(true) {} CDynode::CDynode(CService addr, COutPoint outpoint, CPubKey pubKeyCollateralAddress, CPubKey pubKeyDynode, int nProtocolVersionIn) : dynode_info_t{ DYNODE_ENABLED, nProtocolVersionIn, GetAdjustedTime(), outpoint, addr, pubKeyCollateralAddress, pubKeyDynode}, fAllowMixingTx(true) {} CDynode::CDynode(const CDynode& other) : dynode_info_t{other}, lastPing(other.lastPing), vchSig(other.vchSig), nCollateralMinConfBlockHash(other.nCollateralMinConfBlockHash), nBlockLastPaid(other.nBlockLastPaid), nPoSeBanScore(other.nPoSeBanScore), nPoSeBanHeight(other.nPoSeBanHeight), fAllowMixingTx(other.fAllowMixingTx), fUnitTest(other.fUnitTest) {} CDynode::CDynode(const CDynodeBroadcast& dnb) : dynode_info_t{ dnb.nActiveState, dnb.nProtocolVersion, dnb.sigTime, dnb.vin.prevout, dnb.addr, dnb.pubKeyCollateralAddress, dnb.pubKeyDynode}, lastPing(dnb.lastPing), vchSig(dnb.vchSig), fAllowMixingTx(true) {} // // When a new Dynode broadcast is sent, update our information // bool CDynode::UpdateFromNewBroadcast(CDynodeBroadcast& dnb, CConnman& connman) { if(dnb.sigTime <= sigTime && !dnb.fRecovery) return false; pubKeyDynode = dnb.pubKeyDynode; sigTime = dnb.sigTime; vchSig = dnb.vchSig; nProtocolVersion = dnb.nProtocolVersion; addr = dnb.addr; nPoSeBanScore = 0; nPoSeBanHeight = 0; nTimeLastChecked = 0; int nDos = 0; if(dnb.lastPing == CDynodePing() || (dnb.lastPing != CDynodePing() && dnb.lastPing.CheckAndUpdate(this, true, nDos, connman))) { lastPing = dnb.lastPing; dnodeman.mapSeenDynodePing.insert(std::make_pair(lastPing.GetHash(), lastPing)); } // if it matches our Dynode privkey... if(fDynodeMode && pubKeyDynode == activeDynode.pubKeyDynode) { nPoSeBanScore = -DYNODE_POSE_BAN_MAX_SCORE; if(nProtocolVersion == PROTOCOL_VERSION) { // ... and PROTOCOL_VERSION, then we've been remotely activated ... activeDynode.ManageState(connman); } else { // ... otherwise we need to reactivate our node, do not add it to the list and do not relay // but also do not ban the node we get this message from LogPrintf("CDynode::UpdateFromNewBroadcast -- wrong PROTOCOL_VERSION, re-activate your DN: message nProtocolVersion=%d PROTOCOL_VERSION=%d\n", nProtocolVersion, PROTOCOL_VERSION); return false; } } return true; } // // Deterministically calculate a given "score" for a Dynode depending on how close it's hash is to // the proof of work for that block. The further away they are the better, the furthest will win the election // and get paid this block // arith_uint256 CDynode::CalculateScore(const uint256& blockHash) { // Deterministically calculate a "score" for a Dynode based on any given (block)hash CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin.prevout << nCollateralMinConfBlockHash << blockHash; return UintToArith256(ss.GetHash()); } CDynode::CollateralStatus CDynode::CheckCollateral(const COutPoint& outpoint, const CPubKey& pubkey) { int nHeight; return CheckCollateral(outpoint, pubkey, nHeight); } CDynode::CollateralStatus CDynode::CheckCollateral(const COutPoint& outpoint, const CPubKey& pubkey, int& nHeightRet) { AssertLockHeld(cs_main); Coin coin; if(!GetUTXOCoin(outpoint, coin)) { return COLLATERAL_UTXO_NOT_FOUND; } if(coin.out.nValue != 1000 * COIN) { return COLLATERAL_INVALID_AMOUNT; } if(pubkey == CPubKey() || coin.out.scriptPubKey != GetScriptForDestination(pubkey.GetID())) { return COLLATERAL_INVALID_PUBKEY; } nHeightRet = coin.nHeight; return COLLATERAL_OK; } void CDynode::Check(bool fForce) { AssertLockHeld(cs_main); LOCK(cs); if(ShutdownRequested()) return; if(!fForce && (GetTime() - nTimeLastChecked < DYNODE_CHECK_SECONDS)) return; nTimeLastChecked = GetTime(); LogPrint("Dynode", "CDynode::Check -- Dynode %s is in %s state\n", vin.prevout.ToStringShort(), GetStateString()); //once spent, stop doing the checks if(IsOutpointSpent()) return; int nHeight = 0; if(!fUnitTest) { TRY_LOCK(cs_main, lockMain); if(!lockMain) return; Coin coin; if(!GetUTXOCoin(vin.prevout, coin)) { nActiveState = DYNODE_OUTPOINT_SPENT; LogPrint("Dynode", "CDynode::Check -- Failed to find Dynode UTXO, Dynode=%s\n", vin.prevout.ToStringShort()); return; } nHeight = chainActive.Height(); } if(IsPoSeBanned()) { if(nHeight < nPoSeBanHeight) return; // too early? // Otherwise give it a chance to proceed further to do all the usual checks and to change its state. // Dynode still will be on the edge and can be banned back easily if it keeps ignoring dnverify // or connect attempts. Will require few dnverify messages to strengthen its position in dn list. LogPrintf("CDynode::Check -- Dynode %s is unbanned and back in list now\n", vin.prevout.ToStringShort()); DecreasePoSeBanScore(); } else if(nPoSeBanScore >= DYNODE_POSE_BAN_MAX_SCORE) { nActiveState = DYNODE_POSE_BAN; // ban for the whole payment cycle nPoSeBanHeight = nHeight + dnodeman.size(); LogPrintf("CDynode::Check -- Dynode %s is banned till block %d now\n", vin.prevout.ToStringShort(), nPoSeBanHeight); return; } int nActiveStatePrev = nActiveState; bool fOurDynode = fDynodeMode && activeDynode.pubKeyDynode == pubKeyDynode; // Dynode doesn't meet payment protocol requirements ... bool fRequireUpdate = nProtocolVersion < dnpayments.GetMinDynodePaymentsProto() || // or it's our own node and we just updated it to the new protocol but we are still waiting for activation ... (fOurDynode && nProtocolVersion < PROTOCOL_VERSION); if(fRequireUpdate) { nActiveState = DYNODE_UPDATE_REQUIRED; if(nActiveStatePrev != nActiveState) { LogPrint("Dynode", "CDynode::Check -- Dynode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } // keep old Dynodes on start, give them a chance to receive updates... bool fWaitForPing = !dynodeSync.IsDynodeListSynced() && !IsPingedWithin(DYNODE_MIN_DNP_SECONDS); if(fWaitForPing && !fOurDynode) { // ...but if it was already expired before the initial check - return right away if(IsExpired() || IsSentinelPingExpired() || IsNewStartRequired()) { LogPrint("Dynode", "CDynode::Check -- Dynode %s is in %s state, waiting for ping\n", vin.prevout.ToStringShort(), GetStateString()); return; } } // don't expire if we are still in "waiting for ping" mode unless it's our own Dynode if(!fWaitForPing || fOurDynode) { if(!IsPingedWithin(DYNODE_NEW_START_REQUIRED_SECONDS)) { nActiveState = DYNODE_NEW_START_REQUIRED; if(nActiveStatePrev != nActiveState) { LogPrint("Dynode", "CDynode::Check -- Dynode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } if(!IsPingedWithin(DYNODE_EXPIRATION_SECONDS)) { nActiveState = DYNODE_EXPIRED; if(nActiveStatePrev != nActiveState) { LogPrint("Dynode", "CDynode::Check -- Dynode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } } if(lastPing.sigTime - sigTime < DYNODE_MIN_DNP_SECONDS) { nActiveState = DYNODE_PRE_ENABLED; if(nActiveStatePrev != nActiveState) { LogPrint("Dynode", "CDynode::Check -- Dynode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } nActiveState = DYNODE_ENABLED; // OK if(nActiveStatePrev != nActiveState) { LogPrint("Dynode", "CDynode::Check -- Dynode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } } bool CDynode::IsValidNetAddr() { return IsValidNetAddr(addr); } bool CDynode::IsValidNetAddr(CService addrIn) { // TODO: regtest is fine with any addresses for now, // should probably be a bit smarter if one day we start to implement tests for this return Params().NetworkIDString() == CBaseChainParams::REGTEST || (addrIn.IsIPv4() && !addrIn.IsIPv6() && IsReachable(addrIn) && addrIn.IsRoutable()); } dynode_info_t CDynode::GetInfo() { dynode_info_t info{*this}; info.nTimeLastPing = lastPing.sigTime; info.fInfoValid = true; return info; } std::string CDynode::StateToString(int nStateIn) { switch(nStateIn) { case DYNODE_PRE_ENABLED: return "PRE_ENABLED"; case DYNODE_ENABLED: return "ENABLED"; case DYNODE_EXPIRED: return "EXPIRED"; case DYNODE_OUTPOINT_SPENT: return "OUTPOINT_SPENT"; case DYNODE_UPDATE_REQUIRED: return "UPDATE_REQUIRED"; case DYNODE_SENTINEL_PING_EXPIRED: return "SENTINEL_PING_EXPIRED"; case DYNODE_NEW_START_REQUIRED: return "NEW_START_REQUIRED"; case DYNODE_POSE_BAN: return "POSE_BAN"; default: return "UNKNOWN"; } } std::string CDynode::GetStateString() const { return StateToString(nActiveState); } std::string CDynode::GetStatus() const { // TODO: return smth a bit more human readable here return GetStateString(); } void CDynode::UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScanBack) { if(!pindex) return; const CBlockIndex *BlockReading = pindex; CScript dnpayee = GetScriptForDestination(pubKeyCollateralAddress.GetID()); // LogPrint("Dynode", "CDynode::UpdateLastPaidBlock -- searching for block with payment to %s\n", vin.prevout.ToStringShort()); LOCK(cs_mapDynodeBlocks); for (int i = 0; BlockReading && BlockReading->nHeight > nBlockLastPaid && i < nMaxBlocksToScanBack; i++) { if(dnpayments.mapDynodeBlocks.count(BlockReading->nHeight) && dnpayments.mapDynodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(dnpayee, 2)) { CBlock block; if(!ReadBlockFromDisk(block, BlockReading, Params().GetConsensus())) // shouldn't really happen continue; CAmount nDynodePayment = getDynodeSubsidyWithOverride(BlockReading->fluidParams.dynodeReward); BOOST_FOREACH(CTxOut txout, block.vtx[0].vout) if(dnpayee == txout.scriptPubKey && nDynodePayment == txout.nValue) { nBlockLastPaid = BlockReading->nHeight; nTimeLastPaid = BlockReading->nTime; LogPrint("Dynode", "CDynode::UpdateLastPaidBlock -- searching for block with payment to %s -- found new %d\n", vin.prevout.ToStringShort(), nBlockLastPaid); return; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } // Last payment for this Dynode wasn't found in latest dnpayments blocks // or it was found in dnpayments blocks but wasn't found in the blockchain. // LogPrint("Dynode", "CDynode::UpdateLastPaidBlock -- searching for block with payment to %s -- keeping old %d\n", vin.prevout.ToStringShort(), nBlockLastPaid); } #ifdef ENABLE_WALLET bool CDynodeBroadcast::Create(std::string strService, std::string strKeyDynode, std::string strTxHash, std::string strOutputIndex, std::string& strErrorRet, CDynodeBroadcast &dnbRet, bool fOffline) { COutPoint outpoint; CPubKey pubKeyCollateralAddressNew; CKey keyCollateralAddressNew; CPubKey pubKeyDynodeNew; CKey keyDynodeNew; auto Log = [&strErrorRet](std::string sErr)->bool { strErrorRet = sErr; LogPrintf("CDynodeBroadcast::Create -- %s\n", strErrorRet); return false; }; // Wait for sync to finish because dnb simply won't be relayed otherwise if (!fOffline && !dynodeSync.IsSynced()) return Log("Sync in progress. Must wait until sync is complete to start Dynode"); if (!CMessageSigner::GetKeysFromSecret(strKeyDynode, keyDynodeNew, pubKeyDynodeNew)) return Log(strprintf("Invalid Dynode key %s", strKeyDynode)); if (!pwalletMain->GetDynodeOutpointAndKeys(outpoint, pubKeyCollateralAddressNew, keyCollateralAddressNew, strTxHash, strOutputIndex)) return Log(strprintf("Could not allocate outpoint %s:%s for dynode %s", strTxHash, strOutputIndex, strService)); CService service; if (!Lookup(strService.c_str(), service, 0, false)) return Log(strprintf("Invalid address %s for dynode.", strService)); int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if (Params().NetworkIDString() == CBaseChainParams::MAIN) { if (service.GetPort() != mainnetDefaultPort) return Log(strprintf("Invalid port %u for dynode %s, only %d is supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort)); } else if (service.GetPort() == mainnetDefaultPort) return Log(strprintf("Invalid port %u for dynode %s, %d is the only supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort)); return Create(outpoint, service, keyCollateralAddressNew, pubKeyCollateralAddressNew, keyDynodeNew, pubKeyDynodeNew, strErrorRet, dnbRet); } bool CDynodeBroadcast::Create(const COutPoint& outpoint, const CService& service, const CKey& keyCollateralAddressNew, const CPubKey& pubKeyCollateralAddressNew, const CKey& keyDynodeNew, const CPubKey& pubKeyDynodeNew, std::string &strErrorRet, CDynodeBroadcast &dnbRet) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; LogPrint("Dynode", "CDynodeBroadcast::Create -- pubKeyCollateralAddressNew = %s, pubKeyDynodeNew.GetID() = %s\n", CDynamicAddress(pubKeyCollateralAddressNew.GetID()).ToString(), pubKeyDynodeNew.GetID().ToString()); auto Log = [&strErrorRet,&dnbRet](std::string sErr)->bool { strErrorRet = sErr; LogPrintf("CDynodeBroadcast::Create -- %s\n", strErrorRet); dnbRet = CDynodeBroadcast(); return false; }; CDynodePing dnp(outpoint); if (!dnp.Sign(keyDynodeNew, pubKeyDynodeNew)) return Log(strprintf("Failed to sign ping, dynode=%s", outpoint.ToStringShort())); dnbRet = CDynodeBroadcast(service, outpoint, pubKeyCollateralAddressNew, pubKeyDynodeNew, PROTOCOL_VERSION); if (!dnbRet.IsValidNetAddr()) return Log(strprintf("Invalid IP address, dynode=%s", outpoint.ToStringShort())); dnbRet.lastPing = dnp; if(!dnbRet.Sign(keyCollateralAddressNew)) { return Log(strprintf("Failed to sign broadcast, dynode=%s", outpoint.ToStringShort())); LogPrintf("CDynodeBroadcast::Create -- %s\n", strErrorRet); dnbRet = CDynodeBroadcast(); return false; } return true; } #endif // ENABLE_WALLET bool CDynodeBroadcast::SimpleCheck(int& nDos) { nDos = 0; AssertLockHeld(cs_main); // make sure addr is valid if(!IsValidNetAddr()) { LogPrintf("CDynodeBroadcast::SimpleCheck -- Invalid addr, rejected: Dynode=%s addr=%s\n", vin.prevout.ToStringShort(), addr.ToString()); return false; } // make sure signature isn't in the future (past is OK) if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrintf("CDynodeBroadcast::SimpleCheck -- Signature rejected, too far into the future: Dynode=%s\n", vin.prevout.ToStringShort()); nDos = 1; return false; } // empty ping or incorrect sigTime/unknown blockhash if(lastPing == CDynodePing() || !lastPing.SimpleCheck(nDos)) { // one of us is probably forked or smth, just mark it as expired and check the rest of the rules nActiveState = DYNODE_EXPIRED; } if(nProtocolVersion < dnpayments.GetMinDynodePaymentsProto()) { LogPrintf("CDynodeBroadcast::SimpleCheck -- outdated Dynode: Dynode=%s nProtocolVersion=%d\n", vin.prevout.ToStringShort(), nProtocolVersion); nActiveState = DYNODE_UPDATE_REQUIRED; } CScript pubkeyScript; pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); if(pubkeyScript.size() != 25) { LogPrintf("CDynodeBroadcast::SimpleCheck -- pubKeyCollateralAddress has the wrong size\n"); nDos = 100; return false; } CScript pubkeyScript2; pubkeyScript2 = GetScriptForDestination(pubKeyDynode.GetID()); if(pubkeyScript2.size() != 25) { LogPrintf("CDynodeBroadcast::SimpleCheck -- pubKeyDynode has the wrong size\n"); nDos = 100; return false; } if(!vin.scriptSig.empty()) { LogPrintf("CDynodeBroadcast::SimpleCheck -- Ignore Not Empty ScriptSig %s\n",vin.ToString()); nDos = 100; return false; } int mainnetDefaultPort = DEFAULT_P2P_PORT; if(Params().NetworkIDString() == CBaseChainParams::MAIN) { if(addr.GetPort() != mainnetDefaultPort) return false; } else if(addr.GetPort() == mainnetDefaultPort) return false; return true; } bool CDynodeBroadcast::Update(CDynode* pdn, int& nDos, CConnman& connman) { nDos = 0; AssertLockHeld(cs_main); if(pdn->sigTime == sigTime && !fRecovery) { // mapSeenDynodeBroadcast in CDynodeMan::CheckDnbAndUpdateDynodeList should filter legit duplicates // but this still can happen if we just started, which is ok, just do nothing here. return false; } // this broadcast is older than the one that we already have - it's bad and should never happen // unless someone is doing something fishy if(pdn->sigTime > sigTime) { LogPrintf("CDynodeBroadcast::Update -- Bad sigTime %d (existing broadcast is at %d) for Dynode %s %s\n", sigTime, pdn->sigTime, vin.prevout.ToStringShort(), addr.ToString()); return false; } pdn->Check(); // Dynode is banned by PoSe if(pdn->IsPoSeBanned()) { LogPrintf("CDynodeBroadcast::Update -- Banned by PoSe, Dynode=%s\n", vin.prevout.ToStringShort()); return false; } // IsVnAssociatedWithPubkey is validated once in CheckOutpoint, after that they just need to match if(pdn->pubKeyCollateralAddress != pubKeyCollateralAddress) { LogPrintf("CDynodeBroadcast::Update -- Got mismatched pubKeyCollateralAddress and vin\n"); nDos = 33; return false; } AssertLockHeld(cs_main); int nHeight; CollateralStatus err = CheckCollateral(vin.prevout, pubKeyCollateralAddress, nHeight); if (err == COLLATERAL_UTXO_NOT_FOUND) { LogPrint("dynode", "CDynodeBroadcast::CheckOutpoint -- Failed to find Dynode UTXO, dynode=%s\n", vin.prevout.ToStringShort()); return false; } // if there was no Dynode broadcast recently or if it matches our Dynode privkey... if(!pdn->IsBroadcastedWithin(DYNODE_MIN_DNB_SECONDS) || (fDynodeMode && pubKeyDynode == activeDynode.pubKeyDynode)) { // take the newest entry LogPrintf("CDynodeBroadcast::Update -- Got UPDATED Dynode entry: addr=%s\n", addr.ToString()); if(pdn->UpdateFromNewBroadcast(*this, connman)) { pdn->Check(); Relay(connman); } dynodeSync.BumpAssetLastTime("CDynodeBroadcast::Update"); } return true; } bool CDynodeBroadcast::CheckOutpoint(int& nDos) { // we are a Dynode with the same vin (i.e. already activated) and this dnb is ours (matches our Dynodes privkey) // so nothing to do here for us if(fDynodeMode && vin.prevout == activeDynode.outpoint && pubKeyDynode == activeDynode.pubKeyDynode) { return false; } AssertLockHeld(cs_main); int nHeight; CollateralStatus err = CheckCollateral(vin.prevout, pubKeyCollateralAddress, nHeight); if (err == COLLATERAL_UTXO_NOT_FOUND) { LogPrint("dynode", "CDynodeBroadcast::CheckOutpoint -- Failed to find Dynode UTXO, dynode=%s\n", vin.prevout.ToStringShort()); return false; } if (err == COLLATERAL_INVALID_AMOUNT) { LogPrint("dynode", "CDynodeBroadcast::CheckOutpoint -- Dynode UTXO should have 1000 DYN, dynode=%s\n", vin.prevout.ToStringShort()); nDos = 33; return false; } if(err == COLLATERAL_INVALID_PUBKEY) { LogPrint("dynode", "CDynodeBroadcast::CheckOutpoint -- Dynode UTXO should match pubKeyCollateralAddress, dynode=%s\n", vin.prevout.ToStringShort()); nDos = 33; return false; } if(chainActive.Height() - nHeight + 1 < Params().GetConsensus().nDynodeMinimumConfirmations) { LogPrintf("CDynodeBroadcast::CheckOutpoint -- Dynode UTXO must have at least %d confirmations, dynode=%s\n", Params().GetConsensus().nDynodeMinimumConfirmations, vin.prevout.ToStringShort()); // UTXO is legit but has not enough confirmations. // Maybe we miss few blocks, let this dnb be checked again later. dnodeman.mapSeenDynodeBroadcast.erase(GetHash()); return false; } LogPrint("Dynode", "CDynodeBroadcast::CheckOutpoint -- Dynode UTXO verified\n"); // Verify that sig time is legit, should be at least not earlier than the timestamp of the block // at which collateral became nDynodeMinimumConfirmations blocks deep. // NOTE: this is not accurate because block timestamp is NOT guaranteed to be 100% correct one. CBlockIndex* pRequredConfIndex = chainActive[nHeight + Params().GetConsensus().nDynodeMinimumConfirmations - 1]; // block where tx got nDynodeMinimumConfirmations if(pRequredConfIndex->GetBlockTime() > sigTime) { LogPrintf("CDynodeBroadcast::CheckOutpoint -- Bad sigTime %d (%d conf block is at %d) for Dynode %s %s\n", sigTime, Params().GetConsensus().nDynodeMinimumConfirmations, pRequredConfIndex->GetBlockTime(), vin.prevout.ToStringShort(), addr.ToString()); return false; } if (!CheckSignature(nDos)) { LogPrintf("CDynodeBroadcast::CheckOutpoint -- CheckSignature() failed, dynode=%s\n", vin.prevout.ToStringShort()); return false; } // remember the block hash when collateral for this dynode had minimum required confirmations nCollateralMinConfBlockHash = pRequredConfIndex->GetBlockHash(); return true; } bool CDynodeBroadcast::IsVinAssociatedWithPubkey(const CTxIn& txin, const CPubKey& pubkey) { CScript payee; payee = GetScriptForDestination(pubkey.GetID()); CTransaction tx; uint256 hash; if(GetTransaction(txin.prevout.hash, tx, Params().GetConsensus(), hash, true)) { BOOST_FOREACH(CTxOut out, tx.vout) if(out.nValue == 1000*COIN && out.scriptPubKey == payee) return true; } return false; } bool CDynodeBroadcast::Sign(const CKey& keyCollateralAddress) { std::string strError; std::string strMessage; sigTime = GetAdjustedTime(); strMessage = addr.ToString(false) + boost::lexical_cast<std::string>(sigTime) + pubKeyCollateralAddress.GetID().ToString() + pubKeyDynode.GetID().ToString() + boost::lexical_cast<std::string>(nProtocolVersion); if(!CMessageSigner::SignMessage(strMessage, vchSig, keyCollateralAddress)) { LogPrintf("CDynodeBroadcast::Sign -- SignMessage() failed\n"); return false; } if(!CMessageSigner::VerifyMessage(pubKeyCollateralAddress, vchSig, strMessage, strError)) { LogPrintf("CDynodeBroadcast::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } bool CDynodeBroadcast::CheckSignature(int& nDos) { std::string strMessage; std::string strError = ""; nDos = 0; strMessage = addr.ToString(false) + boost::lexical_cast<std::string>(sigTime) + pubKeyCollateralAddress.GetID().ToString() + pubKeyDynode.GetID().ToString() + boost::lexical_cast<std::string>(nProtocolVersion); LogPrint("Dynode", "CDynodeBroadcast::CheckSignature -- strMessage: %s pubKeyCollateralAddress address: %s sig: %s\n", strMessage, CDynamicAddress(pubKeyCollateralAddress.GetID()).ToString(), EncodeBase64(&vchSig[0], vchSig.size())); if(!CMessageSigner::VerifyMessage(pubKeyCollateralAddress, vchSig, strMessage, strError)){ LogPrintf("CDynodeBroadcast::CheckSignature -- Got bad Dynode announce signature, error: %s\n", strError); nDos = 100; return false; } return true; } void CDynodeBroadcast::Relay(CConnman& connman) { // Do not relay until fully synced if(!dynodeSync.IsSynced()) { LogPrint("dynode", "CDynodeBroadcast::Relay -- won't relay until fully synced\n"); return; } CInv inv(MSG_DYNODE_ANNOUNCE, GetHash()); connman.RelayInv(inv); } CDynodePing::CDynodePing(const COutPoint& outpoint) { LOCK(cs_main); if (!chainActive.Tip() || chainActive.Height() < 12) return; vin = CTxIn(outpoint); blockHash = chainActive[chainActive.Height() - 12]->GetBlockHash(); sigTime = GetAdjustedTime(); } bool CDynodePing::Sign(const CKey& keyDynode, const CPubKey& pubKeyDynode) { std::string strError; std::string strDyNodeSignMessage; // TODO: add sentinel data sigTime = GetAdjustedTime(); std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime); if(!CMessageSigner::SignMessage(strMessage, vchSig, keyDynode)) { LogPrintf("CDynodePing::Sign -- SignMessage() failed\n"); return false; } if(!CMessageSigner::VerifyMessage(pubKeyDynode, vchSig, strMessage, strError)) { LogPrintf("CDynodePing::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } bool CDynodePing::CheckSignature(CPubKey& pubKeyDynode, int &nDos) { // TODO: add sentinel data std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime); std::string strError = ""; nDos = 0; if(!CMessageSigner::VerifyMessage(pubKeyDynode, vchSig, strMessage, strError)) { LogPrintf("CDynodePing::CheckSignature -- Got bad Dynode ping signature, Dynode=%s, error: %s\n", vin.prevout.ToStringShort(), strError); nDos = 33; return false; } return true; } bool CDynodePing::SimpleCheck(int& nDos) { // don't ban by default nDos = 0; if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrintf("CDynodePing::SimpleCheck -- Signature rejected, too far into the future, Dynode=%s\n", vin.prevout.ToStringShort()); nDos = 1; return false; } { AssertLockHeld(cs_main); BlockMap::iterator mi = mapBlockIndex.find(blockHash); if (mi == mapBlockIndex.end()) { LogPrint("Dynode", "DynodePing::SimpleCheck -- Dynode ping is invalid, unknown block hash: Dynode=%s blockHash=%s\n", vin.prevout.ToStringShort(), blockHash.ToString()); // maybe we stuck or forked so we shouldn't ban this node, just fail to accept this ping // TODO: or should we also request this block? return false; } } LogPrint("Dynode", "CDynodePing::SimpleCheck -- Dynode ping verified: Dynode=%s blockHash=%s sigTime=%d\n", vin.prevout.ToStringShort(), blockHash.ToString(), sigTime); return true; } bool CDynodePing::CheckAndUpdate(CDynode* pdn, bool fFromNewBroadcast, int& nDos, CConnman& connman) { AssertLockHeld(cs_main); // don't ban by default nDos = 0; if (!SimpleCheck(nDos)) { return false; } if (pdn == NULL) { LogPrint("Dynode", "CDynodePing::CheckAndUpdate -- Couldn't find Dynode entry, Dynode=%s\n", vin.prevout.ToStringShort()); return false; } if(!fFromNewBroadcast) { if (pdn->IsUpdateRequired()) { LogPrint("Dynode", "CDynodePing::CheckAndUpdate -- Dynode protocol is outdated, Dynode=%s\n", vin.prevout.ToStringShort()); return false; } if (pdn->IsNewStartRequired()) { LogPrint("Dynode", "CDynodePing::CheckAndUpdate -- Dynode is completely expired, new start is required, Dynode=%s\n", vin.prevout.ToStringShort()); return false; } } LogPrint("Dynode", "CDynodePing::CheckAndUpdate -- New ping: Dynode=%s blockHash=%s sigTime=%d\n", vin.prevout.ToStringShort(), blockHash.ToString(), sigTime); // LogPrintf("dnping - Found corresponding dn for vin: %s\n", vin.prevout.ToStringShort()); // update only if there is no known ping for this Dynode or // last ping was more then DYNODE_MIN_DNP_SECONDS-60 ago comparing to this one if (pdn->IsPingedWithin(DYNODE_MIN_DNP_SECONDS - 60, sigTime)) { LogPrint("Dynode", "CDynodePing::CheckAndUpdate -- Dynode ping arrived too early, Dynode=%s\n", vin.prevout.ToStringShort()); //nDos = 1; //disable, this is happening frequently and causing banned peers return false; } if (!CheckSignature(pdn->pubKeyDynode, nDos)) return false; // so, ping seems to be ok // if we are still syncing and there was no known ping for this dn for quite a while // (NOTE: assuming that DYNODE_EXPIRATION_SECONDS/2 should be enough to finish dn list sync) if(!dynodeSync.IsDynodeListSynced() && !pdn->IsPingedWithin(DYNODE_EXPIRATION_SECONDS/2)) { // let's bump sync timeout LogPrint("Dynode", "CDynodePing::CheckAndUpdate -- bumping sync timeout, dynode=%s\n", vin.prevout.ToStringShort()); dynodeSync.BumpAssetLastTime("CDynodePing::CheckAndUpdate"); } // let's store this ping as the last one LogPrint("Dynode", "CDynodePing::CheckAndUpdate -- Dynode ping accepted, Dynode=%s\n", vin.prevout.ToStringShort()); pdn->lastPing = *this; // and update dnodeman.mapSeenDynodeBroadcast.lastPing which is probably outdated CDynodeBroadcast dnb(*pdn); uint256 hash = dnb.GetHash(); if (dnodeman.mapSeenDynodeBroadcast.count(hash)) { dnodeman.mapSeenDynodeBroadcast[hash].second.lastPing = *this; } // force update, ignoring cache pdn->Check(true); // relay ping for nodes in ENABLED/EXPIRED/SENTINEL_PING_EXPIRED state only, skip everyone else if (!pdn->IsEnabled() && !pdn->IsExpired() && !pdn->IsSentinelPingExpired()) return false; LogPrint("Dynode", "CDynodePing::CheckAndUpdate -- Dynode ping acceepted and relayed, Dynode=%s\n", vin.prevout.ToStringShort()); Relay(connman); return true; } void CDynodePing::Relay(CConnman& connman) { // Do not relay until fully synced if(!dynodeSync.IsSynced()) { LogPrint("dynode", "CDynodePing::Relay -- won't relay until fully synced\n"); return; } CInv inv(MSG_DYNODE_PING, GetHash()); connman.RelayInv(inv); } void CDynode::AddGovernanceVote(uint256 nGovernanceObjectHash) { if(mapGovernanceObjectsVotedOn.count(nGovernanceObjectHash)) { mapGovernanceObjectsVotedOn[nGovernanceObjectHash]++; } else { mapGovernanceObjectsVotedOn.insert(std::make_pair(nGovernanceObjectHash, 1)); } } void CDynode::RemoveGovernanceObject(uint256 nGovernanceObjectHash) { std::map<uint256, int>::iterator it = mapGovernanceObjectsVotedOn.find(nGovernanceObjectHash); if(it == mapGovernanceObjectsVotedOn.end()) { return; } mapGovernanceObjectsVotedOn.erase(it); } /** * FLAG GOVERNANCE ITEMS AS DIRTY * * - When Dynode come and go on the network, we must flag the items they voted on to recalc it's cached flags * */ void CDynode::FlagGovernanceItemsAsDirty() { std::vector<uint256> vecDirty; { std::map<uint256, int>::iterator it = mapGovernanceObjectsVotedOn.begin(); while(it != mapGovernanceObjectsVotedOn.end()) { vecDirty.push_back(it->first); ++it; } } for(size_t i = 0; i < vecDirty.size(); ++i) { dnodeman.AddDirtyGovernanceObjectHash(vecDirty[i]); } }
38.936694
271
0.675278
[ "vector" ]
d78e18a356fcebb90ad3b57a0993a7c52e640405
52,235
cpp
C++
3rdparty/meshlab-master/src/plugins_experimental/filter_multiscale_align/multiscale_align.cpp
HoEmpire/slambook2
96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4
[ "MIT" ]
null
null
null
3rdparty/meshlab-master/src/plugins_experimental/filter_multiscale_align/multiscale_align.cpp
HoEmpire/slambook2
96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4
[ "MIT" ]
null
null
null
3rdparty/meshlab-master/src/plugins_experimental/filter_multiscale_align/multiscale_align.cpp
HoEmpire/slambook2
96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4
[ "MIT" ]
null
null
null
//#define _DEBUG_GLS //#define DEBUG_SINGLE_POINT #include "multiscale_align.h" #include <vcg/complex/algorithms/point_sampling.h> #include <vcg/complex/algorithms/create/resampler.h> //#include <vcg/space/index/kdtree/kdtree.h> #include <iostream> #include <stdlib.h> #include <time.h> #include <fstream> #include "utils.h" using namespace vcg; using namespace std; using namespace Grenaille; class BaseSampler { public: BaseSampler(CMeshO* _m){m=_m; uvSpaceFlag = false; qualitySampling=false; tex=0;} CMeshO *m; QImage* tex; int texSamplingWidth; int texSamplingHeight; bool uvSpaceFlag; bool qualitySampling; void AddVert(const CMeshO::VertexType &p) { tri::Allocator<CMeshO>::AddVertices(*m,1); m->vert.back().ImportData(p); } }; // end class BaseSampler // Default Constructor MultiscaleAlign::MultiscaleAlign() { srand (time(NULL)); } //! This defines the min and max where to perform the comparison void computeScaleBounds(const DescriptorBase &reference, const DescriptorBase &toAlign, float maxScaleRef, float maxScaleToAl, int& xMin, int& xMax, int& yMin, int& yMax ){ double logBase=std::log((double)toAlign.multiplier); double minGlobScale=min(reference.minScale,toAlign.minScale); xMax= (int)(std::log(maxScaleRef/minGlobScale) / logBase); yMax= (int)(std::log(maxScaleToAl/minGlobScale) / logBase); xMin= (int)(std::log(reference.minScale/minGlobScale) / logBase) +1 ; yMin= (int)(std::log(toAlign.minScale/minGlobScale) / logBase) +1; } // Precompute the GLS descriptor, only for the selected points template <class Fit> void MultiscaleAlign::computeSimilarityMap(const DescriptorBase& reference, const DescriptorBase& toAlign, std::vector<Fit>* toAlignDescr, float maxscaleToAl){ CMeshO::PerVertexAttributeHandle<std::vector<DerivableSphereFit>* > descriptorsHandler; descriptorsHandler = tri::Allocator<CMeshO>::GetPerVertexAttribute<std::vector<DerivableSphereFit>* >(reference.model->cm, std::string("GLSDescr")); //reset quality to 0 for (CMeshO::VertexIterator vj = reference.model->cm.vert.begin(); vj != reference.model->cm.vert.end(); ++vj) if(! (*vj).IsS()){ (*vj).Q() = 0; (*vj).C() = Color4b(255,255,255,1); } #pragma omp parallel for for(int i = 0; i < reference.selection.size(); i++){ unsigned int ind = reference.selection[i]; CVertexO &vj=reference.model->cm.vert[ind]; // Use a local variable for each thread float maxScale = vj.Q(); int xMin, yMin, xMax, yMax; computeScaleBounds(reference, toAlign, maxScale, maxscaleToAl, xMin, xMax, yMin, yMax); std::vector<DerivableSphereFit> *descr = descriptorsHandler[ind]; DynamicSolver ds; ds.solve(*toAlignDescr, toAlignDescr->size(), *descr, descr->size(), toAlign.multiplier, xMin, xMax, yMin, yMax); //std::cout << ind << " " << ds.confidence << std::endl; //DynamicProg::VotingStretchEstimation<Scalar> vse; //float scale = vse.estimate(ds.xBest, ds.yBest, toAlign.multiplier); reference.model->cm.vert[ind].Q() = ds.confidence; //reference.model->cm.vert[ind].Q() = 1.f/scale; reference.model->cm.vert[ind].C() = Color4b(0,0,255*ds.confidence,1); } } ////// This function is not used now, but it should analyse the points find the border ones, and assign a maxscale w.r.t. borders void MultiscaleAlign::checkBorders(DescriptorBase model, float radius){ int borderPoints=0; std::cout << "Check borders, scale " << 4.2*radius*radius << endl; for (CMeshO::VertexIterator vj = model.model->cm.vert.begin(); vj != model.model->cm.vert.end(); ++vj) { std::vector<unsigned int> n; std::vector<Scalar> squaredDist; model.kdTree->doQueryDist((*vj).P(), 2.1*radius, n, squaredDist); //std::cout << "Neighbors " << n.size() << endl; if (n.size()<22) { //(*vj).C()=Color4b(255,0,0,1); (*vj).Q()=0.0; //(*vj).C()=Color4b(0,255,0,1); borderPoints++; } else { //(*vj).C()=Color4b(255,0,0,1); (*vj).Q()=-1.0; } } std::cout << "Border points " << borderPoints << endl; std::vector<unsigned int> n; std::vector<Scalar> squaredDist; if (borderPoints == 0) { float bigRad = 1.5*model.model->cm.bbox.Diag(); for (CMeshO::VertexIterator vj = model.model->cm.vert.begin(); vj != model.model->cm.vert.end(); ++vj) { //MyPoint query = model.model->cm.vert[k]; model.kdTree->doQueryDist((*vj).P(), bigRad, n, squaredDist); //std::cout << "RefCoarse: " << refCoarse << " N size " << n.size() << std::endl; //model.model->cm.vert[n.back()].C() = Color4b(0, 0, 255, 255); //std::sort(squaredDist.begin(), squaredDist.end()); (*vj).Q() = sqrt(squaredDist.back()); //std::cout << "RefCoarse: " << reference.maxScale << " N size " << n.size() << std::endl; n.clear(); } } else { float radiusSearch = radius; float bestRadius = 0; //std::vector<unsigned int> n; while (n.size()<model.model->cm.vert.size()) { n.clear(); //std::cout << "Radius " << radiusSearch << endl; for (CMeshO::VertexIterator vj = model.model->cm.vert.begin(); vj != model.model->cm.vert.end(); ++vj) { if ((*vj).Q() == 0.0) { model.kdTree->doQueryDist((*vj).P(), radiusSearch, n, squaredDist); if (n.size() >= model.model->cm.vert.size()) break; for (int i = 0; i < n.size(); i++) { //std::cout << "In N " << endl; if (model.model->cm.vert[n[i]].Q() < 0.0f) { //std::cout << "Set " << radiusSearch << endl; model.model->cm.vert[n[i]].Q() = radiusSearch; bestRadius = radiusSearch; } } n.clear(); } } radiusSearch *= 1.1; } for (CMeshO::VertexIterator vj = model.model->cm.vert.begin(); vj != model.model->cm.vert.end(); ++vj) { if ((*vj).Q() < bestRadius/4.0f) { (*vj).Q() = 0.0; } } } } //////// This is the main function decribed inside float MultiscaleAlign::process_scale(MeshModel* _reference, float radiusRef, float refCoarse, MeshModel* _toAlign, float radiusToAlign, float toAlignCoarse, float multiplier, unsigned int nbScales, Options opt){ float scaleFact=0.0; bool done=false; /////// Create the scales vector, and the DescriptorBase objects DescriptorBase toAlign(_toAlign, radiusToAlign, toAlignCoarse, multiplier, nbScales); std::cout << "Compute toAlign KdTree..." << std::flush; vcg::ConstDataWrapper<CMeshO::VertexType::CoordType> wrapperVcg(&toAlign.model->cm.vert[0].P(), toAlign.model->cm.vert.size(), size_t(toAlign.model->cm.vert[1].P().V()) - size_t(toAlign.model->cm.vert[0].P().V())); toAlign.kdTree = new vcg::KdTree<CMeshO::ScalarType>(wrapperVcg); std::cout << "DONE" << std::endl; DescriptorBase reference(_reference, radiusRef, refCoarse, multiplier, nbScales); std::cout << "Compute reference KdTree..." << std::flush; vcg::ConstDataWrapper<CMeshO::VertexType::CoordType> wrapperVcgR(&reference.model->cm.vert[0].P(), reference.model->cm.vert.size(), size_t(reference.model->cm.vert[1].P().V()) - size_t(reference.model->cm.vert[0].P().V())); reference.kdTree = new vcg::KdTree<CMeshO::ScalarType>(wrapperVcgR); std::cout << "DONE" << std::endl; if (opt.checkBorders) { checkBorders(reference, radiusRef); checkBorders(toAlign, radiusToAlign); //return 1; } std::vector<DescrPoint> descrList; std::vector< int > seeds; #define ONLY_ONE #ifdef ONLY_ONE //int toAlignId = 6701; // gargoself //int toAlignId = 12111; // gargo200k //int toAlignId = 16028; // gargo200k_cut //int toAlignId = 16026; // gargo200k_cut_noscale //int referenceId = 26051; int referenceId = 274; // Surrey //int referenceId = 169; //200 samples typedef typename std::vector<DerivableSphereFit> Container; using vcg::tri::Allocator; //std::vector<unsigned int> n; //std::vector<Scalar> squaredDist; //MyPoint query = reference.model->cm.vert[referenceId]; //reference.kdTree->doQueryDist(reference.model->cm.vert[referenceId].P(), refCoarse, n, squaredDist); // ////std::cout << "RefCoarse: " << refCoarse << " N size " << n.size() << std::endl; //reference.model->cm.vert[n.back()].C() = Color4b(0, 0, 255, 255); //reference.maxScale = Distance(reference.model->cm.vert[referenceId].P(), reference.model->cm.vert[n.back()].P()) / 1.5f; ////std::cout << "RefCoarse: " << reference.maxScale << " N size " << n.size() << std::endl; reference.maxScale = reference.model->cm.vert[referenceId].Q(); std::vector<float>Scales; Utils::sampleScaleInterval(min(radiusToAlign, radiusRef), max(toAlignCoarse, reference.model->cm.vert[referenceId].Q()), multiplier, nbScales, Scales); /*CMeshO::PerVertexAttributeHandle<Container* > descriptorsHandler; descriptorsHandler = Allocator<CMeshO>::GetPerVertexAttribute<Container* > (reference.model->cm, std::string("GLSDescr")); descriptorsHandler[referenceId] = new std::vector<DerivableSphereFit>(); computeDescriptor(reference.model->cm.vert[referenceId], Scales, reference, descriptorsHandler[referenceId]);*/ #endif //std::cout << "Start" << std::endl; //unsigned int ind = 13785; CMeshO::PerVertexAttributeHandle<std::vector<DerivableSphereFit>* > referenceDescriptorsHandler; referenceDescriptorsHandler = tri::Allocator<CMeshO>::GetPerVertexAttribute<std::vector<DerivableSphereFit>* >(reference.model->cm, std::string("GLSDescr")); referenceDescriptorsHandler[referenceId] = new std::vector<DerivableSphereFit>(); computeDescriptor(reference.model->cm.vert[referenceId], Scales, reference, referenceDescriptorsHandler[referenceId]); reference.model->cm.vert[referenceId].C() = Color4b(0, 255, 0, 1); //toAlign.model->cm.vert[toAlignId].C() = Color4b(0, 255, 0, 1); //float maxScale = MAX_SCALE_MULTIPLIER*reference.model->cm.bbox.Diag(); /*for (CMeshO::VertexIterator vj = toAlign.model->cm.vert.begin(); vj != toAlign.model->cm.vert.end(); ++vj) (*vj).Q()=0.0;*/ std::vector<std::pair<std::pair<float,float>, float>> bestScales; std::pair<int, float> init(0, 0.0); std::pair<std::pair<int, float>, float> init2(init, 0.0); for (int i = 0; i < 20; i++) bestScales.push_back(init2); /*toAlign.selection.clear(); toAlign.selection.push_back(4775); toAlign.model->cm.vert[4775].C() = Color4b(0, 255, 0, 255); */ //std::cout << "Selected points: " << toAlign.selection.size() << std::endl; // output seeds for debug purpose for (int i = 0; i < toAlign.selection.size(); i++) { std::cout << "Seed " << i+1 << " out of " << toAlign.selection.size() << std::endl; int indToAl = toAlign.selection[i]; if (toAlign.model->cm.vert[indToAl].Q() > 0) { //n.clear(); //squaredDist.clear(); //query = toAlign.model->cm.vert[indToAl]; //toAlign.kdTree->doQueryDist(toAlign.model->cm.vert[indToAl].P(), toAlignCoarse, n, squaredDist); ////std::cout << "toAlignCoarse: " << toAlignCoarse << " N size " << n.size() << std::endl; //toAlign.model->cm.vert[n.back()].C() = Color4b(0, 0, 255, 255); //toAlign.maxScale = Distance(toAlign.model->cm.vert[indToAl].P(), toAlign.model->cm.vert[n.back()].P())/1.5f; ////std::cout << "toAlignCoarse: " << toAlign.maxScale << " N size " << n.size() << std::endl; toAlign.maxScale = toAlign.model->cm.vert[indToAl].Q(); // Use a local variable for each thread //float maxscaleToAl = MAX_SCALE_MULTIPLIER*toAlign.model->cm.bbox.Diag(); int xMin, yMin, xMax, yMax; computeScaleBounds(reference, toAlign, reference.maxScale, toAlign.maxScale, xMin, xMax, yMin, yMax); //std::cout << "Computed Scale bounds!: " << std::endl; //std::cout << "Computing GLS...: " << std::endl; CMeshO::PerVertexAttributeHandle<std::vector<DerivableSphereFit>* > descriptorsHandlerAlign; descriptorsHandlerAlign = tri::Allocator<CMeshO>::GetPerVertexAttribute<std::vector<DerivableSphereFit>* >(toAlign.model->cm, std::string("GLSDescr")); descriptorsHandlerAlign[indToAl] = new std::vector<DerivableSphereFit>(); computeDescriptor(toAlign.model->cm.vert[indToAl], Scales, toAlign, descriptorsHandlerAlign[indToAl]); //reference.model->cm.vert[ind].C() = Color4b(0, 255, 0, 1); std::vector<DerivableSphereFit> *descrAlign = descriptorsHandlerAlign[indToAl]; //std::cout << "Done!: " << std::endl; //std::cout << "xMin: " << xMin << "xMax: " << xMax << "yMin: " << yMin << "yMax: " << yMax << "Maxscale: " << reference.maxScale << "MaxScaleToAl: " << toAlign.maxScale << std::endl; DynamicSolver ds; ds.solve(*referenceDescriptorsHandler[referenceId], referenceDescriptorsHandler[referenceId]->size(), *descrAlign, descrAlign->size(), toAlign.multiplier, xMin, xMax, yMin, yMax); while (ds.estScales.size() > 10) ds.estScales.pop_back(); for (int i = 0; i < ds.estScales.size(); i++) { //std::cout << "Confidence " << ds.estScales[i].second << std::endl; ds.estScales[i].second = recalcConfidence(reference, toAlign, ds.estScales[i].first, nbScales, referenceId, indToAl); //std::cout << "Confidence after " << ds.estScales[i].second << std::endl; } std::sort(ds.estScales.begin(), ds.estScales.end(), [](auto &left, auto &right) { return left.second > right.second; }); /*for (int j = 0; j != ds.estScales.size(); j++) {*/ std::pair<int, float> bestFirst(indToAl, ds.estScales[0].first); if (ds.estScales[0].second > bestScales.back().second) { std::pair<std::pair<int, float>, float> best(bestFirst, ds.estScales[0].second); bestScales.push_back(best); std::sort(bestScales.begin(), bestScales.end(), [](auto &left, auto &right) { return left.second > right.second; }); bestScales.pop_back(); } //std::cout << "Scale: " << ds.estScales[j].first << " Confidence: " << ds.estScales[j].second << endl; //} } } for (int j = 0; j != bestScales.size(); j++) { toAlign.model->cm.vert[bestScales[j].first.first].C() = Color4b(bestScales[j].second*255, 0, 0, 1); //toAlign.model->cm.vert[bestScales[j].first.first].Q() = bestScales[j].first.second; std::cout << "Id: " << bestScales[j].first.first << " Scale: " << bestScales[j].first.second << " Confidence: " << bestScales[j].second << endl; } return 1.; } float MultiscaleAlign::recalcConfidence(DescriptorBase _reference, DescriptorBase _toAlign, float scale, unsigned int nbScales, int referenceID, int toAlignID) { float newRadiusToAlign = _toAlign.minScale*scale; float newToAlignCoarse = _toAlign.maxScale*scale; //std::cout << "MinScaleD " << _reference.minScale << " MaxScaleD " << _reference.maxScale << " MinScaleA " << _toAlign.minScale << " MaxScaleA " << _toAlign.maxScale << std::endl; //std::cout << "Scale " << scale << " oldMin " << _toAlign.minScale << " newMin " << newRadiusToAlign << " oldMax " << _toAlign.maxScale << " newMax " << newToAlignCoarse << std::endl; float minRadius = std::max(_reference.minScale, newRadiusToAlign); float maxRadius = std::min(_reference.maxScale, newToAlignCoarse); float step = (maxRadius - minRadius) / nbScales; //std::cout << "Step " << step << std::endl; //std::cout << "MinRadius " << minRadius << " MaxRadius " << maxRadius << std::endl; std::vector<float>ScalesDesc; std::vector<float>ScalesToAl; for (int i = 0; i < nbScales; i++) { ScalesDesc.push_back(minRadius + i*step); ScalesToAl.push_back(ScalesDesc[i] / scale); //std::cout << "ScaleDescr " << ScalesDesc[i] << " ScaleToAl " << ScalesToAl[i] << std::endl; } //std::cout << "NbScales " << ScalesDesc.size() << std::endl; _toAlign.minScale = ScalesDesc[0]/ scale; _toAlign.maxScale = ScalesDesc.back() / scale; _reference.minScale = ScalesDesc[0]; _reference.maxScale = ScalesDesc.back(); std::vector<DerivableSphereFit> *refDescr = new std::vector<DerivableSphereFit>(); std::vector<DerivableSphereFit>* toAlDescr = new std::vector<DerivableSphereFit>(); computeDescriptor(_reference.model->cm.vert[referenceID], ScalesDesc, _reference, refDescr); computeDescriptor(_toAlign.model->cm.vert[toAlignID], ScalesToAl, _toAlign, toAlDescr); DynamicSolver ds; ds.solve_givenScale(*refDescr, *toAlDescr, 0, 1, 0, ScalesDesc.size(), 0, ScalesDesc.size()); //std::cout << "Confidence " << ds.confidence << std::endl; return ds.confidence/ ScalesDesc.size(); } ////// This function makes the main search for points, see comments inside std::vector < Cand > MultiscaleAlign::searchMatches(DescriptorBase toAlign, DescriptorBase reference, int ind, std::vector<float>Scales, bool computeAlignDescr) { std::cout << "Computing toAlign descriptor" << std::endl; CMeshO::PerVertexAttributeHandle<std::vector<DerivableSphereFit>* > descriptorsToAlign; descriptorsToAlign = tri::Allocator<CMeshO>::GetPerVertexAttribute<std::vector<DerivableSphereFit>* >(toAlign.model->cm, std::string("GLSDescr")); if (computeAlignDescr){ descriptorsToAlign[ind] = new std::vector<DerivableSphereFit>(); computeDescriptor(toAlign.model->cm.vert[ind], Scales, toAlign, descriptorsToAlign[ind]); } CMeshO::PerVertexAttributeHandle<std::vector<DerivableSphereFit>* > descriptorsReference; descriptorsReference = tri::Allocator<CMeshO>::GetPerVertexAttribute<std::vector<DerivableSphereFit>* >(reference.model->cm, std::string("GLSDescr")); float maxscaleToAl=toAlign.model->cm.vert[ind].Q(); //////// // FIRST POINT: Given the first point, all the seams in the reference model are checked, and the best FIRST_POINTS points are put in a list ////////////// std::vector < Cand > firstPoints; Cand cpoint; cpoint.confidence=0.0; cpoint.ind=-1; firstPoints.push_back(cpoint); std::cout << "Searching first point..." << std::endl; #pragma omp parallel for//num_threads(2) for(int selK = 0; selK < reference.selection.size(); selK++){ //for (int k =0; k < reference.model->cm.vn; k++) { unsigned int k = reference.selection[selK]; CVertexO vj=reference.model->cm.vert[k]; // Use a local variable for each thread float maxScaleRef = vj.Q(); int xMin, yMin, xMax, yMax; computeScaleBounds(reference, toAlign, maxScaleRef, maxscaleToAl, xMin, xMax, yMin, yMax); std::vector<DerivableSphereFit> *descr = descriptorsReference[k]; std::vector<DerivableSphereFit>* result = descriptorsToAlign[ind]; DynamicSolver ds; ds.solve(*descr, descr->size(), *result, result->size(), toAlign.multiplier, xMin, xMax, yMin, yMax); #pragma omp critical { std::vector<Cand>::iterator it; it = firstPoints.begin(); //std::cout << "Confidence " << ds.confidence() <<std::endl; if (firstPoints.back().confidence < ds.confidence) { DynamicProg::ConvolutionStretchEstimation<Scalar> vse; cpoint.confidence=ds.confidence; cpoint.ind = k; //std::cout << "Pre-estimate " <<std::endl; cpoint.scale=vse.estimate(ds.stepMatrix(), toAlign.multiplier); //std::cout << "Post-estimate " <<std::endl; if (firstPoints.back().ind==-1) { //std::cout << "First" <<std::endl; firstPoints[0].confidence=cpoint.confidence; firstPoints[0].ind=cpoint.ind; firstPoints[0].scale=cpoint.scale; //firstPoints.erase(it+1); } else for(unsigned int r=0; r<firstPoints.size(); r++) { //std::cout << "Gotcha" <<std::endl; if(firstPoints[r].confidence<cpoint.confidence) { firstPoints.insert(it+r, cpoint); if(firstPoints.size()>FIRST_POINTS) firstPoints.pop_back(); break; } } } } //}else // std::cout << "Reject Ind: " << k << std::endl; } if (firstPoints[0].ind != -1){ std::cout << "Ind of Candidate " << ind << std::endl; for(unsigned int l=0; l<firstPoints.size(); l++) { reference.model->cm.vert[firstPoints[l].ind].C() = Color4b(255,0,0,1); //// This saves the data of the list of matched points in a cvs file #ifdef SAVE_CVS QString filename1=QString("File_Fitness%1.csv") .arg(l); QString filename2=QString("File_Kappa%1.csv") .arg(l); QString filename3=QString("File_Tau%1.csv") .arg(l); QFile file1(filename1); QFile file2(filename2); QFile file3(filename3); file1.open(QFile::WriteOnly); QTextStream stream1(&file1); file2.open(QFile::WriteOnly); QTextStream stream2(&file2); file3.open(QFile::WriteOnly); QTextStream stream3(&file3); double dMax=0.0; for (unsigned int i=0; i<descriptorsToAlign[ind]->size(); i++) { if(descriptorsToAlign[ind]->at(i).geomVar()>dMax) { dMax=descriptorsToAlign[ind]->at(i).geomVar(); } } MyPoint query (reference.model->cm.vert[firstPoints[l].ind]); query.normal().normalize(); reference.maxScale=reference.model->cm.vert[firstPoints[l].ind].Q(); std::vector<DerivableSphereFit> descr; computeDescriptor(query, Scales, reference, &descr); for (unsigned int i = 0; i<Scales.size(); i++) { stream1 << Scales[i] << "\t" ; // this writes first line with stream2 << Scales[i] << "\t" ; // this writes first line with stream3 << Scales[i] << "\t" ; // this writes first line with } stream1 << "\n" ; stream2 << "\n" ; stream3 << "\n" ; for (unsigned int i = 0; i<descriptorsToAlign[ind]->size(); i++) { stream1 << descriptorsToAlign[ind]->at(i).fitness() << "\t" ; // this writes first line with stream2 << descriptorsToAlign[ind]->at(i).kappa() << "\t" ; // this writes first line with stream3 << descriptorsToAlign[ind]->at(i).tau() << "\t" ; // this writes first line with } stream1 << "\n" ; stream2 << "\n" ; stream3 << "\n" ; //std::cout << "Eval first column" << std::endl; for (unsigned int j = 0; j<descr.size(); j++) { stream1 << descr[j].fitness() << "\t" ; // this writes first line with stream2 << descr[j].kappa() << "\t" ; // this writes first line with stream3 << descr[j].tau() << "\t" ; // this writes first line with } stream1 << "\n" ; stream2 << "\n" ; stream3 << "\n" ; file1.close(); file2.close(); file3.close(); #endif std::cout << firstPoints[l].ind << " confidence " << firstPoints[l].confidence << " scale " << firstPoints[l].scale //<< " max " << simSolver.path()[0].value << std::endl; } }else {// Show the un-matched point in black //reference->cm.vert[queryId].C()=Color4b(0,0,0,1); std::cout << "Point not matched !! (conf:" // << ds.confidence << ")" << std::endl; } return firstPoints; } bool MultiscaleAlign::searchTranf(const DescriptorBase &toAlign, const DescriptorBase &reference, const std::vector<int> &seeds, const std::vector<std::vector<Cand> > &seedList, const std::vector<float> &Scales, Options opt) { const int candSeed=seedList.size()-1; //std::cout << "Candseed " << candSeed << std::endl; for (int i=0; i<seedList[candSeed].size(); i++) { const Cand &sPoint=seedList[candSeed][i]; for(int j=0; j<candSeed; j++) { for(int k=0; k<seedList[j].size(); k++) { //std::cout << "Try a scale " << seedList[j][k].scale << " versus " << opt.expectedScale*1.4 << " and " << opt.expectedScale/1.4 << std::endl; if(seedList[j][k].scale<(opt.expectedScale*1.4) && seedList[j][k].scale>(opt.expectedScale/1.4)) { std::vector <std::pair<int, int> > corrs; //std::cout << "Try a scale " << seedList[j][k].scale << std::endl; corrs.reserve(seedList[j].size()); //std::cout << "Try..." << sPoint.scale << " " << seedList[j][k].scale << std::endl; if( isScaleOk(sPoint.scale,seedList[j][k].scale,toAlign.multiplier) && isCoupleOk(toAlign.model->cm.vert[seeds[j]], reference.model->cm.vert[seedList[j][k].ind], toAlign.model->cm.vert[seeds[candSeed]], reference.model->cm.vert[sPoint.ind], sPoint.scale ) ) { //std::cout << "Selected!" << std::endl; corrs.push_back( std::pair<int, int>( seeds[j], seedList[j][k].ind)); corrs.push_back( std::pair<int, int>( seeds[candSeed], sPoint.ind)); //std::cout << "Searching third points..." << std::endl; for(unsigned int s2=0; s2<seeds.size(); s2++) { if(seeds[s2]!=corrs[0].first && seeds[s2]!=corrs[1].first) { //std::cout << "Trying with seed " << s2 << std::endl; std::vector < Cand > thirdPoints = getCandidates(toAlign, reference, seeds[s2], corrs, sPoint.scale, Scales); if(thirdPoints[0].ind!=-1) { //std::cout << "Third point list size " << thirdPoints.size() << std::endl; corrs.push_back(std::pair<int, int>(seeds[s2], thirdPoints[0].ind)); if(!opt.useQuadriplets) { //std::cout << "Checking Triplets " << g+1 << " out of " << thirdPoints.size() << std::endl; if(checkTriplets(toAlign, reference, corrs, thirdPoints,sPoint.scale, opt.alignError)) { return true; } //corrs.pop_back(); } else for (unsigned int g=0; g<thirdPoints.size(); g++) { corrs[2].second=thirdPoints[g].ind; for(unsigned int s3=0; s3<seeds.size(); s3++) { if(seeds[s3]!=corrs[0].first && seeds[s3]!=corrs[1].first && seeds[s3]!=corrs[2].first) { //std::cout << "Fourth point for seed " << s3 << std::endl; std::vector < Cand >fourthPoints = getCandidates(toAlign, reference, seeds[s3], corrs, sPoint.scale, Scales); if(fourthPoints[0].ind!=-1) { corrs.push_back(std::pair<int, int>(seeds[s3], fourthPoints[0].ind)); //std::cout << "Fourth point list size " << fourthPoints.size() << std::endl; //std::cout << "Checking Quadriplets " << t+1 << " out of " << fourthPoints.size() << std::endl; if(checkQuadriplets(toAlign, reference, corrs, fourthPoints,sPoint.scale, opt.alignError)) { return true; } corrs.pop_back(); } } } //corrs.pop_back(); } corrs.pop_back(); } } } } } } } } return false; } ////// Given a set of couples of points and a point on the toAlign model, it finds a list of matches in the right area std::vector<Cand> MultiscaleAlign::getCandidates(const DescriptorBase& toAlign, const DescriptorBase& reference, int ind, const std::vector <std::pair<int, int> >& corrs, float scaleFact, const std::vector<float> &Scales) { std::vector<Cand> output; output.clear(); // DynamicProg::VotingStretchEstimation<Scalar> vse; Cand cpoint; cpoint.confidence=0.0; cpoint.ind=-1; output.push_back(cpoint); //toAlign.model->cm.vert[ind].C()=Color4b(0,0,255,1); CMeshO::PerVertexAttributeHandle<std::vector<DerivableSphereFit>* > descriptorsToAlign; descriptorsToAlign = tri::Allocator<CMeshO>::GetPerVertexAttribute<std::vector<DerivableSphereFit>* >(toAlign.model->cm, std::string("GLSDescr")); descriptorsToAlign[ind] = new std::vector<DerivableSphereFit>(); computeDescriptor(toAlign.model->cm.vert[ind], Scales, toAlign, descriptorsToAlign[ind]); CMeshO::PerVertexAttributeHandle<std::vector<DerivableSphereFit>* > descriptorsReference; descriptorsReference = tri::Allocator<CMeshO>::GetPerVertexAttribute<std::vector<DerivableSphereFit>* >(reference.model->cm, std::string("GLSDescr")); float maxscaleToAl=toAlign.model->cm.vert[ind].Q(); #pragma omp parallel for //for (int l =0; l < reference.model->cm.vn; l++) for(int selK = 0; selK < reference.selection.size(); selK++) { unsigned int l = reference.selection[selK]; if(/*reference.model->cm.vert[l].IsS() && */isReferenceOk(l, reference.model, ind, toAlign.model, corrs, scaleFact)) { //std::cout << "Try " << l << " of " << reference.model->cm.vn << std::endl; //reference->cm.vert[l].C()=Color4b(0,0,255,1); //std::cout << "Candidato" << std::endl; CVertexO vj=reference.model->cm.vert[l]; MyPoint query (vj); query.normal().normalize(); float maxScaleRef = vj.Q(); std::vector<DerivableSphereFit> *descr = descriptorsReference[l]; // std::vector<DerivableSphereFit> descr; // computeDescriptor(query, Scales, reference, &descr); std::vector<DerivableSphereFit>* result = descriptorsToAlign[ind]; // double logBase=std::log((double)toAlign.multiplier); // double minGlobScale=min(reference.minScale,toAlign.minScale); // int xMax= (int)(std::log(reference.maxScale/minGlobScale) / logBase) + 1; // int yMax= (int)(std::log(toAlign.maxScale/minGlobScale) / logBase) + 1; // int xMin= (int)(std::log(reference.minScale/minGlobScale) / logBase) +1 ; // int yMin= (int)(std::log(toAlign.minScale/minGlobScale) / logBase) +1; int xMin, yMin, xMax, yMax; computeScaleBounds(reference, toAlign, maxScaleRef, maxscaleToAl, xMin, xMax, yMin, yMax); //std::cout << "Solve " << std::endl; /////// This calculates the confidence only for the scale defined by the first match DynamicSolver ds; ds.solve_givenScale(*descr, *result, toAlign.multiplier, scaleFact, xMin, xMax, yMin, yMax); //std::cout << ds.confidence << std::endl; #pragma omp critical { std::vector<Cand>::iterator it; it = output.begin(); //std::cout << "Confidence " << ds.confidence() <<std::endl; if (output.back().confidence < ds.confidence) { cpoint.confidence=ds.confidence; cpoint.ind = l; //std::cout << "Pre-estimate " <<std::endl; cpoint.scale=scaleFact; //std::cout << "Post-estimate " <<std::endl; if (output.back().ind==-1) { //std::cout << "First" <<std::endl; output[0].confidence=cpoint.confidence; output[0].ind=cpoint.ind; output[0].scale=cpoint.scale; //firstPoints.erase(it+1); } else for(unsigned int r=0; r<output.size(); r++) { //std::cout << "Gotcha" <<std::endl; if(output[r].confidence<cpoint.confidence) { output.insert(it+r, cpoint); if(output.size()>OTHER_POINTS) output.pop_back(); break; } } } } } } return output; } /*! * \brief MultiscaleAlign::extractSIFTPoints * \param mesh * \param list * * This method assumes that the mesh descriptor has already been computed. * Need to construct a dedicated kdtree containing only the selected points */ //void MultiscaleAlign::extractSIFTPoints(const DescriptorBase& mesh, // std::vector< SiftPoint > &list){ // // //std::cout << "Init local KdTree" << std::endl; // // // Init the local KdTree // MultiscaleAlignNamespace::KdTree<float> tree (mesh.selection.size()); // for(int i = 0; i < mesh.selection.size(); i++){ // const unsigned int& ind = mesh.selection[i]; // tree.set(ind, mesh.model->cm.vert[ind].cP()); // } // tree.finalize(); // //std::cout << "Done" << std::endl; // // CMeshO::PerVertexAttributeHandle<std::vector<DerivableSphereFit>* > descriptors; // descriptors = tri::Allocator<CMeshO>::GetPerVertexAttribute<std::vector<DerivableSphereFit>* >(mesh.model->cm, std::string("GLSDescr")); // // // number of vertices to compare // tree.setMaxNofNeighbors(16); // // //std::cout << "1" << std::endl; // ////#pragma omp parallel for // for(int i = 0; i < mesh.selection.size(); i++) // { // const unsigned int& ind = mesh.selection[i]; // //std::cout << "Analyse element " << ind << std::endl; // // std::vector<DerivableSphereFit>* descr = descriptors[ind]; // // unsigned int nbScale = descr->size(); // // // Collect the neighborhood only when needed // bool neiCollected = false; // // //std::cout << "Data collected" << std::endl; // // /// 1 Detect if we are on a local curvature minimum along scale axis // for(unsigned int s = nbScale-2; s > 0 ; s--){ // // float kprev = descr->at(s-1).kappa(); // float k = descr->at(s ).kappa(); // float knext = descr->at(s+1).kappa(); // // if(! isnan(kprev) && ! isnan(k) && ! isnan(knext) ){ // // bool isMin = ( kprev > k && knext > k ); // bool isMax = ( kprev < k && knext < k ); // // if ( isMin || isMax ){ // //std::cout << "This guy is an extrema at scale "<< s << std::endl; // // bool currentExtr = true; // // if (! neiCollected){ // //std::cout << "We need to collect its neighborhood" << std::endl; // neiCollected = true; // MyPoint query(mesh.model->cm.vert[ind]); // //#pragma omp critical // tree.doQueryK(query.pos()); // // //std::cout << "Done" << std::endl; // } // // for(unsigned int ki = 0; ki!=tree.getNofFoundNeighbors(); ki++){ // unsigned int nId = tree.getNeighbor(ki).originalId; // // //std::cout << "Compare with neighbor " << nId << std::endl; // // if (isMin){ // if (k > descriptors[nId]->at(s-1).kappa() || // k > descriptors[nId]->at(s ).kappa() || // k > descriptors[nId]->at(s+1).kappa()) { // currentExtr = false; // //std::cout << "Minimum rejected" << std::endl; // break; // } // }else if (isMax){ // if (k < descriptors[nId]->at(s-1).kappa() || // k < descriptors[nId]->at(s ).kappa() || // k < descriptors[nId]->at(s+1).kappa()) { // currentExtr = false; // //std::cout << "Maximum rejected" << std::endl; // break; // } // } // } // // // We are currently on a local extrema // if (currentExtr){ // //std::cout << "Extrema selected and kept !" << std::endl; // // SiftPoint sp; // sp.ind = ind; // sp.scaleId = s; // //#pragma omp critical // list.push_back(sp); // // //std::cout << "Update Its color" << std::endl; // mesh.model->cm.vert[ind].C()=Color4b(255, // 255*int(float(s+1)/float(nbScale)), // 255*int(float(s+1)/float(nbScale)), // 1); // break; // } // } // } // }// for scales // }// for points //} /*! * \brief MultiscaleAlign::extractSIFTPoints * \param mesh * \param list * * This method assumes that the mesh descriptor has already been computed. * Need to construct a dedicated kdtree containing only the selected points */ void MultiscaleAlign::extractDescriptivePoints(const DescriptorBase& mesh, std::vector< DescrPoint > &list){ const float numSel = (float)mesh.selection.size(); //std::cout << "Got size" << std::endl; CMeshO::PerVertexAttributeHandle<std::vector<DerivableSphereFit>* > descriptor; descriptor = tri::Allocator<CMeshO>::GetPerVertexAttribute<std::vector<DerivableSphereFit>* >(mesh.model->cm, std::string("GLSDescr")); std::vector<DerivableSphereFit> *descr = descriptor[mesh.selection[0]]; //std::cout << "Got descriptor" << std::endl; std::vector<float> meanK; std::vector<float> meanT; for(int k=0; k<descr->size(); k++) { meanK.push_back(0.0); meanT.push_back(0.0); } //std::cout << "Initialize" << std::endl; //#pragma omp parallel for std::vector<float>::iterator kIt, tIt; for(int i = 0; i < mesh.selection.size(); i++) { const unsigned int& ind = mesh.selection[i]; //std::cout << "Analyse element " << ind << std::endl; descr = descriptor[ind]; kIt = meanK.begin(); tIt = meanT.begin(); for(std::vector<DerivableSphereFit>::const_iterator it=descr->begin(); it != descr->end(); it++, kIt++, tIt++) { if(!isnan((*it).kappa())) { (*kIt) += ((*it).kappa()/numSel); (*tIt) += ((*it).tau()/numSel); } } } /*for(int i = 0; i <mesh.model->cm.vn; i++) { mesh.model->cm.vert[i].C()=Color4b(0,0,0,1); }*/ //#pragma omp parallel for for(int i = 0; i < mesh.selection.size(); i++) { const unsigned int& ind = mesh.selection[i]; kIt = meanK.begin(); tIt = meanT.begin(); float descript=0.0; float diffK, diffT; descr = descriptor[ind]; for(std::vector<DerivableSphereFit>::const_iterator it=descr->begin(); it != descr->end(); it++, kIt++, tIt++) { if(!isnan((*it).kappa())) { diffK = (*it).kappa()- (*kIt); diffT = (*it).tau() - (*tIt); descript += (diffK*diffK+diffT*diffT); } } DescrPoint p; p.ind=ind; p.descrip=descript; list.push_back(p); /*mesh.model->cm.vert[mesh.selection[i]].Q()=descript; mesh.model->cm.vert[mesh.selection[i]].C()=Color4b(255*descript,255*descript,255*descript,1);*/ //std::cout << "Descriptiveness " << descript << std::endl; } } // ////////// This is the main function decribed inside //float MultiscaleAlign::process_scale(MeshModel* _reference, float radiusRef, float refCoarse, // MeshModel* _toAlign, float radiusToAlign, float toAlignCoarse, // float multiplier, unsigned int nbScales, Options opt) { // // // // float scaleFact = 0.0; bool done = false; // // /////// Create the scales vector, and the DescriptorBase objects // std::vector<float>Scales; // Utils::sampleScaleInterval(min(radiusToAlign, radiusRef), // max(toAlignCoarse, refCoarse), // multiplier, // nbScales, // Scales); // // DescriptorBase toAlign(_toAlign, radiusToAlign, toAlignCoarse, multiplier, nbScales); // std::cout << "Compute toAlign KdTree..." << std::flush; // toAlign.kdTree = Utils::makeKNNTree<float>(toAlign.model); // std::cout << "DONE" << std::endl; // // DescriptorBase reference(_reference, radiusRef, refCoarse, multiplier, nbScales); // std::cout << "Compute reference KdTree..." << std::flush; // reference.kdTree = Utils::makeKNNTree<float>(reference.model); // std::cout << "DONE" << std::endl; // // std::vector<DescrPoint> descrList; // std::vector< int > seeds; //#define ONLY_ONE //#ifdef ONLY_ONE // // int toAlignId = 12111; // int referenceId = 13785; // // typedef typename std::vector<DerivableSphereFit> Container; // using vcg::tri::Allocator; // // CMeshO::PerVertexAttributeHandle<Container* > descriptorsHandler; // descriptorsHandler = // Allocator<CMeshO>::GetPerVertexAttribute<Container* > // (reference.model->cm, std::string("GLSDescr")); // // descriptorsHandler[referenceId] = new std::vector<DerivableSphereFit>(); // // computeDescriptor(reference.model->cm.vert[referenceId], // Scales, // reference, // descriptorsHandler[referenceId]); // // CMeshO::PerVertexAttributeHandle<Container* > descriptorsHandler2; // descriptorsHandler2 = // Allocator<CMeshO>::GetPerVertexAttribute<Container* > // (toAlign.model->cm, std::string("GLSDescr")); // // descriptorsHandler2[toAlignId] = new std::vector<DerivableSphereFit>(); // // computeDescriptor(toAlign.model->cm.vert[toAlignId], // Scales, // toAlign, // descriptorsHandler2[toAlignId]); // //#else // QTime time; // time.start(); // std::cout << "[ToAlign] Computing GLS descriptors ..." << std::endl; // preComputeDescriptor(toAlign, Scales, true); // std::cout << "[ToAlign] GLS decriptors computed in " << time.elapsed() / 1000 << " secondes " << endl; // // //if (opt.useDescriptive) // //{ // // /// Compute GLS descriptor for the toAlign model // // // // //time.start(); // // std::cout << "[ToAlign] Computing GLS descriptors ..." << std::endl; // // preComputeDescriptor(toAlign, Scales, true); // // //std::cout << "[ToAlign] GLS decriptors computed in " <<time.elapsed()/1000 << " secondes " << endl; // // // // // /// Extract Sift Point in the ToAlign model // // // // //time.start(); // // std::cout << "[ToAlign] Extract Descriptive Points ..." << std::endl; // // extractDescriptivePoints(toAlign, descrList); // // // seeds=selectSeedsDescr(toAlign, descrList, false); // // // //} // // // //else // //{ // // // // // // /// Init memory to store the GLS descriptor for the toAlignModel // // //the PerVertexAttribute handles is create and each of the vector capacity set to the maximum possible // // std::cout << "[ToAlign] Preparing GLS descriptors ..." << std::endl; // // CMeshO::PerVertexAttributeHandle<std::vector<DerivableSphereFit>* > descriptorsToAlign; // // descriptorsToAlign = tri::Allocator<CMeshO>::GetPerVertexAttribute<std::vector<DerivableSphereFit>* >(toAlign.model->cm, std::string("GLSDescr")); // // std::cout << "Done." << endl; // // // // // int init=rand() % toAlign.selection.size(); // // std::cout << "init= " << init << " ind= " << toAlign.selection[init] << std::endl; // // //#ifdef DEBUG_SINGLE_POINT // // // seeds.resize(1); // // // seeds[0] = 23285; // // int seeId = seeds[0]; // // // _toAlign->cm.vert[seeId].Q()=MAX_SCALE_MULTIPLIER*_toAlign->cm.bbox.Diag(); // // std::cout << "Quality of seed: " << _toAlign->cm.vert[seeId].Q() << std::endl; // // // reference.selection.clear(); // // reference.selection.push_back(seeId); // // // for (CMeshO::VertexIterator vj = _reference->cm.vert.begin(); vj != _reference->cm.vert.end(); ++vj) // // (*vj).ClearS(); // // // _reference->cm.vert[seeId].SetS(); // // _reference->cm.vert[seeId].Q()=MAX_SCALE_MULTIPLIER*_reference->cm.bbox.Diag(); // // _reference->cm.vert[seeId].C()=Color4b(255,255,0,1); // // // CMeshO::PerVertexAttributeHandle<std::vector<DerivableSphereFit>* > referenceDescriptorsHandler; // // referenceDescriptorsHandler = tri::Allocator<CMeshO>::GetPerVertexAttribute<std::vector<DerivableSphereFit>* >(reference.model->cm, std::string("GLSDescr")); // // // referenceDescriptorsHandler[seeId] = new std::vector<DerivableSphereFit>(); // // computeDescriptor(reference.model->cm.vert[seeId], Scales, reference, referenceDescriptorsHandler[seeId]); // // // std::cout << "Testing on one point only" << std::flush; // // //#else // // seeds = selectSeeds(toAlign.model, reference.model, toAlign.selection[init]); // // //seeds = selectSeeds(toAlign.model, reference.model, -1); // //#endif // //} // // // /// Compute GLS descriptor for the reference model // //QTime time; // time.start(); // std::cout << "[Reference] Computing GLS descriptors ..." << std::endl; // preComputeDescriptor(reference, Scales, true); // std::cout << "[Reference] GLS decriptors computed in " << time.elapsed() / 1000 << " secondes " << endl; // // // // //#ifdef DEBUG_SIMILARITY_MAP // seeds.resize(1); // seeds[0] = 6639; //#endif // // // output seeds for debug purpose // for (unsigned int j = 0; j < seeds.size(); j++) { // std::cout << "Seed " << j << ": ind " << seeds[j] << ", quality " << toAlign.model->cm.vert[seeds[j]].Q() << std::endl; // toAlign.model->cm.vert[seeds[j]].C() = Color4b(255, 0, 0, 1); // } // // //return -1; //#endif //#define TEST //#ifdef TEST // /// Build simimarity map // // std::cout << "Start" << std::endl; // // //unsigned int ind = 13785; // CMeshO::PerVertexAttributeHandle<std::vector<DerivableSphereFit>* > referenceDescriptorsHandler; // referenceDescriptorsHandler = tri::Allocator<CMeshO>::GetPerVertexAttribute<std::vector<DerivableSphereFit>* >(reference.model->cm, std::string("GLSDescr")); // // referenceDescriptorsHandler[referenceId] = new std::vector<DerivableSphereFit>(); // computeDescriptor(reference.model->cm.vert[referenceId], Scales, reference, referenceDescriptorsHandler[referenceId]); // // reference.model->cm.vert[referenceId].C() = Color4b(0, 255, 0, 1); // //float maxScale = MAX_SCALE_MULTIPLIER*reference.model->cm.bbox.Diag(); // // for (CMeshO::VertexIterator vj = toAlign.model->cm.vert.begin(); vj != toAlign.model->cm.vert.end(); ++vj) // (*vj).Q() = 0.0; // // std::cout << "Selected points: " << toAlign.selection.size() << std::endl; // toAlign.selection.clear(); // toAlign.selection.push_back(toAlignId); // //toAlign.selection.push_back(2026); // // // output seeds for debug purpose // for (int i = 0; i < toAlign.selection.size(); i++) { // // unsigned int indToAl = toAlign.selection[i]; // // // Use a local variable for each thread // //float maxscaleToAl = MAX_SCALE_MULTIPLIER*toAlign.model->cm.bbox.Diag(); // int xMin, yMin, xMax, yMax; // computeScaleBounds(reference, toAlign, refCoarse, toAlignCoarse, xMin, xMax, yMin, yMax); // // CMeshO::PerVertexAttributeHandle<std::vector<DerivableSphereFit>* > descriptorsHandlerAlign; // descriptorsHandlerAlign = tri::Allocator<CMeshO>::GetPerVertexAttribute<std::vector<DerivableSphereFit>* >(toAlign.model->cm, std::string("GLSDescr")); // // //reference.model->cm.vert[ind].C() = Color4b(0, 255, 0, 1); // std::vector<DerivableSphereFit> *descrAlign = descriptorsHandlerAlign[indToAl]; // // //std::cout << "xMin: " << xMin << "xMax: " << xMax << "yMin: " << yMin << "yMax: " << yMax << "Maxscale: " << maxScale << "MaxScaleToAl: " << maxscaleToAl << std::endl; // DynamicSolver ds; // ds.solve(*referenceDescriptorsHandler[referenceId], referenceDescriptorsHandler[referenceId]->size(), // *descrAlign, descrAlign->size(), // toAlign.multiplier, xMin, xMax, yMin, yMax); // // //std::cout << "xBest: " << ds.xBest << "yBest: " << ds.yBest << "multiplier: " << toAlign.multiplier << std::endl; // // float scaleEst = Scalar(1.0) / std::pow(toAlign.multiplier, ds.yBest - ds.xBest); // std::cout << "Scale: " << scaleEst << std::endl; // toAlign.model->cm.vert[indToAl].Q() = scaleEst; // int confi = (int)(ds.confidence*255.0); // toAlign.model->cm.vert[indToAl].C() = Color4b(confi, confi, confi, 1); // // } // // //culo // // //toAlign.model->cm.vert[seeds[0]].C() = Color4b(0, 255, 0, 1); // //toAlign.model->cm.vert[seeds[0]].Q() = 10; // // // return 1.; //#endif // //#ifdef DEBUG_SIMILARITY_MAP // /// Build simimarity map // std::vector<DerivableSphereFit>* descr = new std::vector<DerivableSphereFit>(); // computeDescriptor(toAlign.model->cm.vert[seeds[0]], Scales, toAlign, descr); // // float maxscaleToAl = toAlign.model->cm.vert[seeds[0]].Q(); // // // Compute the similarity and put it into the quality field // computeSimilarityMap(reference, toAlign, descr, maxscaleToAl); // // toAlign.model->cm.vert[seeds[0]].C() = Color4b(0, 255, 0, 1); // //toAlign.model->cm.vert[seeds[0]].Q() = 10; // // // return 1.; //#endif // //unsigned int count=1; // //done=true; // // //#define ONLY_THE_FIRST_SEARCH //#ifdef ONLY_THE_FIRST_SEARCH // CVertexO vj = reference.model->cm.vert[seeds[0]]; // // MyPoint query(vj); // query.normal().normalize(); // // // Use a local variable for each thread // float maxScaleRef = vj.Q(); // float maxscaleToAl = toAlign.model->cm.vert[seeds[0]].Q(); // int xMin, yMin, xMax, yMax; // computeScaleBounds(reference, toAlign, maxScaleRef, maxscaleToAl, xMin, xMax, yMin, yMax); // //std::cout << "xMin: " << xMin << " xMax: " << xMax << " yMin: " << yMin << " yMax: " << yMax <<std::endl; // // std::vector<DerivableSphereFit> descrRef, descrAlign; // computeDescriptor(query, Scales, reference, &descrRef); // computeDescriptor(toAlign.model->cm.vert[seeds[0]], Scales, toAlign, &descrAlign); // // DynamicSolver ds; // ds.solve(descrRef, descrRef.size(), // descrAlign, descrAlign.size(), // toAlign.multiplier, xMin, xMax, yMin, yMax); // // float scale = Scalar(1.0) / std::pow(toAlign.multiplier, ds.yBest - ds.xBest); // std::cout << "Scale: " << scale << std::endl; // // return -1; //#else // // std::vector< std::vector < Cand > > seedList; int reIter = 0; // for (int i = 0; i<seeds.size(); i++) // { // if (done || reIter == 5) // { // break; // } // // // //// The first seed is chosen // //toAlign.maxScale=toAlign.model->cm.vert[seeds[i]].Q(); // std::cout << "Computing seed " << i + 1 << " of " << seeds.size() << std::endl; // //std::cout << "Seed point: " << seeds[0] << " toAlignCoarse: " << toAlign.model->cm.vert[seeds[0]].Q() << std::endl; // // ///// Given the first seed, we search for the scale and transformation to find the alignmen // /// The last parameter avoid to recompute the toAlign descriptor when it is already done // seedList.push_back(searchMatches(toAlign, reference, seeds[i], Scales, !opt.useDescriptive)); // // // // //std::cout << "Done searchcorr" << std::endl; // if (seedList.size()>1) // { // done = searchTranf(toAlign, reference, seeds, seedList, Scales, opt); // //done=true; // // } // // if (i == seeds.size() - 1) // { // reIter++; // std::cout << "Shuffling the seeds, try n. " << reIter + 1 << std::endl; // seeds.clear(); // seedList.clear(); // //std::cout << "Seeds size " << seeds.size() << std::endl; // if (!opt.useDescriptive) // { // int init = rand() % toAlign.selection.size(); // std::cout << "init= " << init << " ind= " << toAlign.selection[init] << std::endl; // seeds = selectSeeds(toAlign.model, reference.model, toAlign.selection[init]); // i = -1; // } // else // { // //reIter=5; // seeds = selectSeedsDescr(toAlign, descrList, true); // i = -1; // } // // // } // // // // } // // // ///// Actually, no scale factor is returned by the function, but the transformation is applied // if (done == false) // return -1; // else // return getScaleFromTransf(toAlign.model->cm.Tr); // //#endif //}
36.70766
224
0.592955
[ "mesh", "vector", "model" ]
d7a1c9591d3835062d714f47a526e5b07dcf4894
1,555
cc
C++
hbase/src/model/DescribeSecurityGroupsResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
hbase/src/model/DescribeSecurityGroupsResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
hbase/src/model/DescribeSecurityGroupsResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/hbase/model/DescribeSecurityGroupsResult.h> #include <json/json.h> using namespace AlibabaCloud::HBase; using namespace AlibabaCloud::HBase::Model; DescribeSecurityGroupsResult::DescribeSecurityGroupsResult() : ServiceResult() {} DescribeSecurityGroupsResult::DescribeSecurityGroupsResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeSecurityGroupsResult::~DescribeSecurityGroupsResult() {} void DescribeSecurityGroupsResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allSecurityGroupIds = value["SecurityGroupIds"]["SecurityGroupId"]; for (const auto &item : allSecurityGroupIds) securityGroupIds_.push_back(item.asString()); } std::vector<std::string> DescribeSecurityGroupsResult::getSecurityGroupIds()const { return securityGroupIds_; }
29.339623
88
0.771704
[ "vector", "model" ]
d7a73d75c9d9dc49c5a574c46b5ab45fd7fa2aeb
22,606
cc
C++
src/x64/deoptimizer-x64.cc
FurkanOM/v8
3b92806ab995ec32ee0968b61af400e99d52fbca
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
1
2022-03-29T18:30:29.000Z
2022-03-29T18:30:29.000Z
src/x64/deoptimizer-x64.cc
FurkanOM/v8
3b92806ab995ec32ee0968b61af400e99d52fbca
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
src/x64/deoptimizer-x64.cc
FurkanOM/v8
3b92806ab995ec32ee0968b61af400e99d52fbca
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
// Copyright 2012 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #if V8_TARGET_ARCH_X64 #include "codegen.h" #include "deoptimizer.h" #include "full-codegen.h" #include "safepoint-table.h" namespace v8 { namespace internal { const int Deoptimizer::table_entry_size_ = 10; int Deoptimizer::patch_size() { return Assembler::kCallInstructionLength; } void Deoptimizer::DeoptimizeFunctionWithPreparedFunctionList( JSFunction* function) { Isolate* isolate = function->GetIsolate(); HandleScope scope(isolate); DisallowHeapAllocation nha; ASSERT(function->IsOptimized()); ASSERT(function->FunctionsInFunctionListShareSameCode()); // Get the optimized code. Code* code = function->code(); // The optimized code is going to be patched, so we cannot use it any more. function->shared()->EvictFromOptimizedCodeMap(code, "deoptimized function"); // Invalidate the relocation information, as it will become invalid by the // code patching below, and is not needed any more. code->InvalidateRelocation(); // For each LLazyBailout instruction insert a absolute call to the // corresponding deoptimization entry, or a short call to an absolute // jump if space is short. The absolute jumps are put in a table just // before the safepoint table (space was allocated there when the Code // object was created, if necessary). Address instruction_start = function->code()->instruction_start(); #ifdef DEBUG Address prev_call_address = NULL; #endif DeoptimizationInputData* deopt_data = DeoptimizationInputData::cast(code->deoptimization_data()); for (int i = 0; i < deopt_data->DeoptCount(); i++) { if (deopt_data->Pc(i)->value() == -1) continue; // Position where Call will be patched in. Address call_address = instruction_start + deopt_data->Pc(i)->value(); // There is room enough to write a long call instruction because we pad // LLazyBailout instructions with nops if necessary. CodePatcher patcher(call_address, Assembler::kCallInstructionLength); patcher.masm()->Call(GetDeoptimizationEntry(isolate, i, LAZY), RelocInfo::NONE64); ASSERT(prev_call_address == NULL || call_address >= prev_call_address + patch_size()); ASSERT(call_address + patch_size() <= code->instruction_end()); #ifdef DEBUG prev_call_address = call_address; #endif } // Add the deoptimizing code to the list. DeoptimizingCodeListNode* node = new DeoptimizingCodeListNode(code); DeoptimizerData* data = isolate->deoptimizer_data(); node->set_next(data->deoptimizing_code_list_); data->deoptimizing_code_list_ = node; // We might be in the middle of incremental marking with compaction. // Tell collector to treat this code object in a special way and // ignore all slots that might have been recorded on it. isolate->heap()->mark_compact_collector()->InvalidateCode(code); ReplaceCodeForRelatedFunctions(function, code); if (FLAG_trace_deopt) { PrintF("[forced deoptimization: "); function->PrintName(); PrintF(" / %" V8PRIxPTR "]\n", reinterpret_cast<intptr_t>(function)); } } static const byte kJnsInstruction = 0x79; static const byte kJnsOffset = 0x1d; static const byte kCallInstruction = 0xe8; static const byte kNopByteOne = 0x66; static const byte kNopByteTwo = 0x90; // The back edge bookkeeping code matches the pattern: // // add <profiling_counter>, <-delta> // jns ok // call <stack guard> // ok: // // We will patch away the branch so the code is: // // add <profiling_counter>, <-delta> ;; Not changed // nop // nop // call <on-stack replacment> // ok: void Deoptimizer::PatchInterruptCodeAt(Code* unoptimized_code, Address pc_after, Code* interrupt_code, Code* replacement_code) { ASSERT(!InterruptCodeIsPatched(unoptimized_code, pc_after, interrupt_code, replacement_code)); // Turn the jump into nops. Address call_target_address = pc_after - kIntSize; *(call_target_address - 3) = kNopByteOne; *(call_target_address - 2) = kNopByteTwo; // Replace the call address. Assembler::set_target_address_at(call_target_address, replacement_code->entry()); unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch( unoptimized_code, call_target_address, replacement_code); } void Deoptimizer::RevertInterruptCodeAt(Code* unoptimized_code, Address pc_after, Code* interrupt_code, Code* replacement_code) { ASSERT(InterruptCodeIsPatched(unoptimized_code, pc_after, interrupt_code, replacement_code)); // Restore the original jump. Address call_target_address = pc_after - kIntSize; *(call_target_address - 3) = kJnsInstruction; *(call_target_address - 2) = kJnsOffset; // Restore the original call address. Assembler::set_target_address_at(call_target_address, interrupt_code->entry()); interrupt_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch( unoptimized_code, call_target_address, interrupt_code); } #ifdef DEBUG bool Deoptimizer::InterruptCodeIsPatched(Code* unoptimized_code, Address pc_after, Code* interrupt_code, Code* replacement_code) { Address call_target_address = pc_after - kIntSize; ASSERT_EQ(kCallInstruction, *(call_target_address - 1)); if (*(call_target_address - 3) == kNopByteOne) { ASSERT(replacement_code->entry() == Assembler::target_address_at(call_target_address)); ASSERT_EQ(kNopByteTwo, *(call_target_address - 2)); return true; } else { ASSERT_EQ(interrupt_code->entry(), Assembler::target_address_at(call_target_address)); ASSERT_EQ(kJnsInstruction, *(call_target_address - 3)); ASSERT_EQ(kJnsOffset, *(call_target_address - 2)); return false; } } #endif // DEBUG static int LookupBailoutId(DeoptimizationInputData* data, BailoutId ast_id) { ByteArray* translations = data->TranslationByteArray(); int length = data->DeoptCount(); for (int i = 0; i < length; i++) { if (data->AstId(i) == ast_id) { TranslationIterator it(translations, data->TranslationIndex(i)->value()); int value = it.Next(); ASSERT(Translation::BEGIN == static_cast<Translation::Opcode>(value)); // Read the number of frames. value = it.Next(); if (value == 1) return i; } } UNREACHABLE(); return -1; } void Deoptimizer::DoComputeOsrOutputFrame() { DeoptimizationInputData* data = DeoptimizationInputData::cast( compiled_code_->deoptimization_data()); unsigned ast_id = data->OsrAstId()->value(); // TODO(kasperl): This should not be the bailout_id_. It should be // the ast id. Confusing. ASSERT(bailout_id_ == ast_id); int bailout_id = LookupBailoutId(data, BailoutId(ast_id)); unsigned translation_index = data->TranslationIndex(bailout_id)->value(); ByteArray* translations = data->TranslationByteArray(); TranslationIterator iterator(translations, translation_index); Translation::Opcode opcode = static_cast<Translation::Opcode>(iterator.Next()); ASSERT(Translation::BEGIN == opcode); USE(opcode); int count = iterator.Next(); iterator.Skip(1); // Drop JS frame count. ASSERT(count == 1); USE(count); opcode = static_cast<Translation::Opcode>(iterator.Next()); USE(opcode); ASSERT(Translation::JS_FRAME == opcode); unsigned node_id = iterator.Next(); USE(node_id); ASSERT(node_id == ast_id); int closure_id = iterator.Next(); USE(closure_id); ASSERT_EQ(Translation::kSelfLiteralId, closure_id); unsigned height = iterator.Next(); unsigned height_in_bytes = height * kPointerSize; USE(height_in_bytes); unsigned fixed_size = ComputeFixedSize(function_); unsigned input_frame_size = input_->GetFrameSize(); ASSERT(fixed_size + height_in_bytes == input_frame_size); unsigned stack_slot_size = compiled_code_->stack_slots() * kPointerSize; unsigned outgoing_height = data->ArgumentsStackHeight(bailout_id)->value(); unsigned outgoing_size = outgoing_height * kPointerSize; unsigned output_frame_size = fixed_size + stack_slot_size + outgoing_size; ASSERT(outgoing_size == 0); // OSR does not happen in the middle of a call. if (FLAG_trace_osr) { PrintF("[on-stack replacement: begin 0x%08" V8PRIxPTR " ", reinterpret_cast<intptr_t>(function_)); PrintFunctionName(); PrintF(" => node=%u, frame=%d->%d]\n", ast_id, input_frame_size, output_frame_size); } // There's only one output frame in the OSR case. output_count_ = 1; output_ = new FrameDescription*[1]; output_[0] = new(output_frame_size) FrameDescription( output_frame_size, function_); output_[0]->SetFrameType(StackFrame::JAVA_SCRIPT); // Clear the incoming parameters in the optimized frame to avoid // confusing the garbage collector. unsigned output_offset = output_frame_size - kPointerSize; int parameter_count = function_->shared()->formal_parameter_count() + 1; for (int i = 0; i < parameter_count; ++i) { output_[0]->SetFrameSlot(output_offset, 0); output_offset -= kPointerSize; } // Translate the incoming parameters. This may overwrite some of the // incoming argument slots we've just cleared. int input_offset = input_frame_size - kPointerSize; bool ok = true; int limit = input_offset - (parameter_count * kPointerSize); while (ok && input_offset > limit) { ok = DoOsrTranslateCommand(&iterator, &input_offset); } // There are no translation commands for the caller's pc and fp, the // context, and the function. Set them up explicitly. for (int i = StandardFrameConstants::kCallerPCOffset; ok && i >= StandardFrameConstants::kMarkerOffset; i -= kPointerSize) { intptr_t input_value = input_->GetFrameSlot(input_offset); if (FLAG_trace_osr) { const char* name = "UNKNOWN"; switch (i) { case StandardFrameConstants::kCallerPCOffset: name = "caller's pc"; break; case StandardFrameConstants::kCallerFPOffset: name = "fp"; break; case StandardFrameConstants::kContextOffset: name = "context"; break; case StandardFrameConstants::kMarkerOffset: name = "function"; break; } PrintF(" [rsp + %d] <- 0x%08" V8PRIxPTR " ; [rsp + %d] " "(fixed part - %s)\n", output_offset, input_value, input_offset, name); } output_[0]->SetFrameSlot(output_offset, input_->GetFrameSlot(input_offset)); input_offset -= kPointerSize; output_offset -= kPointerSize; } // Translate the rest of the frame. while (ok && input_offset >= 0) { ok = DoOsrTranslateCommand(&iterator, &input_offset); } // If translation of any command failed, continue using the input frame. if (!ok) { delete output_[0]; output_[0] = input_; output_[0]->SetPc(reinterpret_cast<intptr_t>(from_)); } else { // Set up the frame pointer and the context pointer. output_[0]->SetRegister(rbp.code(), input_->GetRegister(rbp.code())); output_[0]->SetRegister(rsi.code(), input_->GetRegister(rsi.code())); unsigned pc_offset = data->OsrPcOffset()->value(); intptr_t pc = reinterpret_cast<intptr_t>( compiled_code_->entry() + pc_offset); output_[0]->SetPc(pc); } Code* continuation = function_->GetIsolate()->builtins()->builtin(Builtins::kNotifyOSR); output_[0]->SetContinuation( reinterpret_cast<intptr_t>(continuation->entry())); if (FLAG_trace_osr) { PrintF("[on-stack replacement translation %s: 0x%08" V8PRIxPTR " ", ok ? "finished" : "aborted", reinterpret_cast<intptr_t>(function_)); PrintFunctionName(); PrintF(" => pc=0x%0" V8PRIxPTR "]\n", output_[0]->GetPc()); } } void Deoptimizer::FillInputFrame(Address tos, JavaScriptFrame* frame) { // Set the register values. The values are not important as there are no // callee saved registers in JavaScript frames, so all registers are // spilled. Registers rbp and rsp are set to the correct values though. for (int i = 0; i < Register::kNumRegisters; i++) { input_->SetRegister(i, i * 4); } input_->SetRegister(rsp.code(), reinterpret_cast<intptr_t>(frame->sp())); input_->SetRegister(rbp.code(), reinterpret_cast<intptr_t>(frame->fp())); for (int i = 0; i < DoubleRegister::NumAllocatableRegisters(); i++) { input_->SetDoubleRegister(i, 0.0); } // Fill the frame content from the actual data on the frame. for (unsigned i = 0; i < input_->GetFrameSize(); i += kPointerSize) { input_->SetFrameSlot(i, Memory::uint64_at(tos + i)); } } void Deoptimizer::SetPlatformCompiledStubRegisters( FrameDescription* output_frame, CodeStubInterfaceDescriptor* descriptor) { intptr_t handler = reinterpret_cast<intptr_t>(descriptor->deoptimization_handler_); int params = descriptor->register_param_count_; if (descriptor->stack_parameter_count_ != NULL) { params++; } output_frame->SetRegister(rax.code(), params); output_frame->SetRegister(rbx.code(), handler); } void Deoptimizer::CopyDoubleRegisters(FrameDescription* output_frame) { for (int i = 0; i < XMMRegister::NumAllocatableRegisters(); ++i) { double double_value = input_->GetDoubleRegister(i); output_frame->SetDoubleRegister(i, double_value); } } bool Deoptimizer::HasAlignmentPadding(JSFunction* function) { // There is no dynamic alignment padding on x64 in the input frame. return false; } #define __ masm()-> void Deoptimizer::EntryGenerator::Generate() { GeneratePrologue(); // Save all general purpose registers before messing with them. const int kNumberOfRegisters = Register::kNumRegisters; const int kDoubleRegsSize = kDoubleSize * XMMRegister::NumAllocatableRegisters(); __ subq(rsp, Immediate(kDoubleRegsSize)); for (int i = 0; i < XMMRegister::NumAllocatableRegisters(); ++i) { XMMRegister xmm_reg = XMMRegister::FromAllocationIndex(i); int offset = i * kDoubleSize; __ movsd(Operand(rsp, offset), xmm_reg); } // We push all registers onto the stack, even though we do not need // to restore all later. for (int i = 0; i < kNumberOfRegisters; i++) { Register r = Register::from_code(i); __ push(r); } const int kSavedRegistersAreaSize = kNumberOfRegisters * kPointerSize + kDoubleRegsSize; // We use this to keep the value of the fifth argument temporarily. // Unfortunately we can't store it directly in r8 (used for passing // this on linux), since it is another parameter passing register on windows. Register arg5 = r11; // Get the bailout id from the stack. __ movq(arg_reg_3, Operand(rsp, kSavedRegistersAreaSize)); // Get the address of the location in the code object // and compute the fp-to-sp delta in register arg5. __ movq(arg_reg_4, Operand(rsp, kSavedRegistersAreaSize + 1 * kPointerSize)); __ lea(arg5, Operand(rsp, kSavedRegistersAreaSize + 2 * kPointerSize)); __ subq(arg5, rbp); __ neg(arg5); // Allocate a new deoptimizer object. __ PrepareCallCFunction(6); __ movq(rax, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); __ movq(arg_reg_1, rax); __ Set(arg_reg_2, type()); // Args 3 and 4 are already in the right registers. // On windows put the arguments on the stack (PrepareCallCFunction // has created space for this). On linux pass the arguments in r8 and r9. #ifdef _WIN64 __ movq(Operand(rsp, 4 * kPointerSize), arg5); __ LoadAddress(arg5, ExternalReference::isolate_address(isolate())); __ movq(Operand(rsp, 5 * kPointerSize), arg5); #else __ movq(r8, arg5); __ LoadAddress(r9, ExternalReference::isolate_address(isolate())); #endif { AllowExternalCallThatCantCauseGC scope(masm()); __ CallCFunction(ExternalReference::new_deoptimizer_function(isolate()), 6); } // Preserve deoptimizer object in register rax and get the input // frame descriptor pointer. __ movq(rbx, Operand(rax, Deoptimizer::input_offset())); // Fill in the input registers. for (int i = kNumberOfRegisters -1; i >= 0; i--) { int offset = (i * kPointerSize) + FrameDescription::registers_offset(); __ pop(Operand(rbx, offset)); } // Fill in the double input registers. int double_regs_offset = FrameDescription::double_registers_offset(); for (int i = 0; i < XMMRegister::NumAllocatableRegisters(); i++) { int dst_offset = i * kDoubleSize + double_regs_offset; __ pop(Operand(rbx, dst_offset)); } // Remove the bailout id and return address from the stack. __ addq(rsp, Immediate(2 * kPointerSize)); // Compute a pointer to the unwinding limit in register rcx; that is // the first stack slot not part of the input frame. __ movq(rcx, Operand(rbx, FrameDescription::frame_size_offset())); __ addq(rcx, rsp); // Unwind the stack down to - but not including - the unwinding // limit and copy the contents of the activation frame to the input // frame description. __ lea(rdx, Operand(rbx, FrameDescription::frame_content_offset())); Label pop_loop_header; __ jmp(&pop_loop_header); Label pop_loop; __ bind(&pop_loop); __ pop(Operand(rdx, 0)); __ addq(rdx, Immediate(sizeof(intptr_t))); __ bind(&pop_loop_header); __ cmpq(rcx, rsp); __ j(not_equal, &pop_loop); // Compute the output frame in the deoptimizer. __ push(rax); __ PrepareCallCFunction(2); __ movq(arg_reg_1, rax); __ LoadAddress(arg_reg_2, ExternalReference::isolate_address(isolate())); { AllowExternalCallThatCantCauseGC scope(masm()); __ CallCFunction( ExternalReference::compute_output_frames_function(isolate()), 2); } __ pop(rax); // Replace the current frame with the output frames. Label outer_push_loop, inner_push_loop, outer_loop_header, inner_loop_header; // Outer loop state: rax = current FrameDescription**, rdx = one past the // last FrameDescription**. __ movl(rdx, Operand(rax, Deoptimizer::output_count_offset())); __ movq(rax, Operand(rax, Deoptimizer::output_offset())); __ lea(rdx, Operand(rax, rdx, times_pointer_size, 0)); __ jmp(&outer_loop_header); __ bind(&outer_push_loop); // Inner loop state: rbx = current FrameDescription*, rcx = loop index. __ movq(rbx, Operand(rax, 0)); __ movq(rcx, Operand(rbx, FrameDescription::frame_size_offset())); __ jmp(&inner_loop_header); __ bind(&inner_push_loop); __ subq(rcx, Immediate(sizeof(intptr_t))); __ push(Operand(rbx, rcx, times_1, FrameDescription::frame_content_offset())); __ bind(&inner_loop_header); __ testq(rcx, rcx); __ j(not_zero, &inner_push_loop); __ addq(rax, Immediate(kPointerSize)); __ bind(&outer_loop_header); __ cmpq(rax, rdx); __ j(below, &outer_push_loop); for (int i = 0; i < XMMRegister::NumAllocatableRegisters(); ++i) { XMMRegister xmm_reg = XMMRegister::FromAllocationIndex(i); int src_offset = i * kDoubleSize + double_regs_offset; __ movsd(xmm_reg, Operand(rbx, src_offset)); } // Push state, pc, and continuation from the last output frame. if (type() != OSR) { __ push(Operand(rbx, FrameDescription::state_offset())); } __ push(Operand(rbx, FrameDescription::pc_offset())); __ push(Operand(rbx, FrameDescription::continuation_offset())); // Push the registers from the last output frame. for (int i = 0; i < kNumberOfRegisters; i++) { int offset = (i * kPointerSize) + FrameDescription::registers_offset(); __ push(Operand(rbx, offset)); } // Restore the registers from the stack. for (int i = kNumberOfRegisters - 1; i >= 0 ; i--) { Register r = Register::from_code(i); // Do not restore rsp, simply pop the value into the next register // and overwrite this afterwards. if (r.is(rsp)) { ASSERT(i > 0); r = Register::from_code(i - 1); } __ pop(r); } // Set up the roots register. __ InitializeRootRegister(); __ InitializeSmiConstantRegister(); // Return to the continuation point. __ ret(0); } void Deoptimizer::TableEntryGenerator::GeneratePrologue() { // Create a sequence of deoptimization entries. Label done; for (int i = 0; i < count(); i++) { int start = masm()->pc_offset(); USE(start); __ push_imm32(i); __ jmp(&done); ASSERT(masm()->pc_offset() - start == table_entry_size_); } __ bind(&done); } #undef __ } } // namespace v8::internal #endif // V8_TARGET_ARCH_X64
36.520194
80
0.685791
[ "object" ]
92e937a0eb6ef2dfa8a37d721a6a86a182271a45
2,905
cc
C++
src/ufo/filters/MetOfficeBuddyCollector.cc
rnt20/ufo
68dab85486f5d79991956076ac6b962bc1a0c5bd
[ "Apache-2.0" ]
4
2020-12-04T08:26:06.000Z
2021-11-20T01:18:47.000Z
src/ufo/filters/MetOfficeBuddyCollector.cc
rnt20/ufo
68dab85486f5d79991956076ac6b962bc1a0c5bd
[ "Apache-2.0" ]
21
2020-10-30T08:57:16.000Z
2021-05-17T15:11:20.000Z
src/ufo/filters/MetOfficeBuddyCollector.cc
rnt20/ufo
68dab85486f5d79991956076ac6b962bc1a0c5bd
[ "Apache-2.0" ]
31
2021-06-24T18:07:53.000Z
2021-10-08T15:40:39.000Z
/* * (C) Copyright 2020 Met Office UK * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ #include "ufo/filters/MetOfficeBuddyCollector.h" #include <algorithm> #include <cmath> #include "oops/util/sqr.h" #include "ufo/filters/MetOfficeBuddyPair.h" #include "ufo/utils/Constants.h" namespace ufo { MetOfficeBuddyCollector::MetOfficeBuddyCollector(const MetOfficeBuddyCheckParameters &options, const std::vector<float> &latitudes, const std::vector<float> &longitudes, const std::vector<int> &stationIds) : options_(options), latitudes_(latitudes), longitudes_(longitudes), stationIds_(stationIds) { // eqn 3.1 maxLatDifferenceBetweenBuddiesInDeg_ = Constants::rad2deg * options.searchRadius / Constants::mean_earth_rad; } void MetOfficeBuddyCollector::calcDeltaLatLonAndDistanceTo(int obsIdB, double &deltaLatInRad, double &deltaLonInRad, double &distanceInKm) const { deltaLatInRad = (latitudes_[obsIdB] - latitudes_[obsIdA_]) * Constants::deg2rad; deltaLonInRad = (longitudes_[obsIdB] - longitudes_[obsIdA_]) * Constants::deg2rad; if (deltaLonInRad > M_PI) deltaLonInRad -= 2 * M_PI; else if (deltaLonInRad < -M_PI) deltaLonInRad += 2 * M_PI; distanceInKm = Constants::mean_earth_rad * std::sqrt(util::sqr(deltaLatInRad) + 4.0 * util::sqr(std::sin(0.5 * deltaLonInRad)) * std::cos(latitudes_[obsIdA_] * Constants::deg2rad) * std::cos(latitudes_[obsIdB] * Constants::deg2rad)); // eqn 3.3 } MetOfficeBuddyPair MetOfficeBuddyCollector::createBuddyPair(int obsIdB, double deltaLatInRad, double deltaLonInRad, double distanceInKm) const { double rotA, rotB; if (distanceInKm < 10.0) { rotA = 0.0; // the transformation is undefined rotB = 0.0; // for distanceInKm = 0.0, use u,v components } else { // eqn 3.5 double alpha = 0.5 * std::sin(latitudes_[obsIdA_] * Constants::deg2rad) * deltaLonInRad; // eqn 3.6 double sinBeta = Constants::mean_earth_rad * deltaLatInRad * std::cos(alpha) / distanceInKm; sinBeta = std::min(1.0, std::max(-1.0, sinBeta)); double beta = std::asin(sinBeta); rotA = alpha + beta; // eqn 3.7 rotB = beta - alpha; // eqn 3.8 } return MetOfficeBuddyPair(obsIdA_, obsIdB, distanceInKm, rotA, rotB); } } // namespace ufo
40.347222
96
0.581411
[ "vector" ]
92f1acf3caeaf7bc52be3ca9e57dfc3ea779299a
1,891
cpp
C++
examples/objects/C++/book.cpp
davidli3100/ICS4U
b12f3ee88b475b5da1866bef179da4e9ff7bd2d2
[ "MIT" ]
21
2015-04-26T03:03:46.000Z
2019-08-24T20:10:36.000Z
ICS4U/ICS4U-2020-2021/Code/examples/objects/C++/book.cpp
mrseidel-classes/archives
b3e04fd4338e3b3796ad2c681a10fbca69e1dae2
[ "MIT" ]
19
2016-09-14T12:34:22.000Z
2019-09-02T15:51:21.000Z
ICS4U/ICS4U-2020-2021/Code/examples/objects/C++/book.cpp
mrseidel-classes/archives
b3e04fd4338e3b3796ad2c681a10fbca69e1dae2
[ "MIT" ]
24
2015-05-27T04:17:30.000Z
2019-02-23T23:03:46.000Z
/** * A Object holding the price, author, and title of a book * * @author Mr. Seidel * @since 23-Sep-2018 * @version 1.0 * * Updated 13-Apr-20: * - "printX" methods * + "getX" methods * + updated main() function */ class Book { private: string author, title; double price; public: Book(string, string); Book(string, string, double); ~Book(); string getAuthor(void); string getTitle(void); double getPrice(void); bool increasePrice(double); }; // <--- note the semi-colon here /** * This is the constructor function for new books * * @param author - This is the initial author * @param title - This is the initial title of the book * */ Book::Book (string _author, string _title){ price = 0.00; author = _author; title = _title; } /** * This is the constructor function for new books * * @param _author - This is the initial author * @param _title - This is the initial title of the book * @param _price - This is the initial price of the book * */ Book::Book (string _author, string _title, double _price){ price = _price; author = _author; title = _title; } /** * Returns the author of the book * * @return the author of the book */ string Book::getAuthor() { return author; } /** * Returns the title of the book * * @return the title of the book */ string Book::getTitle() { return title; } /** * Returns the price of the book as a double * * @return the price of the book */ double Book::getPrice() { return price; } /** * Attempts to increase the price of the book * * @param increase This is the amount to increase the price of the book * @return true if it is successful in modifying the price, false otherwise. */ bool Book::increasePrice(double increase) { if (increase < 0) { // this is a decrease, not an increase return false; } price = price + increase; return true; }
19.905263
75
0.656795
[ "object" ]
92f3590102b57ba99cd396a502802bd6a170aad0
10,165
cpp
C++
3rdParty/openal/core/uhjfilter.cpp
mewbak/devilutionX
c8ba49e2bf9bcf5bb6fd47b1b7ce3d0370d1524c
[ "Unlicense" ]
417
2020-06-01T15:55:15.000Z
2022-03-31T12:50:51.000Z
Engine/lib/openal-soft/core/uhjfilter.cpp
Ashry00/Torque3D
33e3e41c8b7eb41c743a589558bc21302207ef97
[ "MIT" ]
186
2020-06-02T19:12:39.000Z
2022-02-15T02:22:27.000Z
Engine/lib/openal-soft/core/uhjfilter.cpp
Ashry00/Torque3D
33e3e41c8b7eb41c743a589558bc21302207ef97
[ "MIT" ]
84
2020-06-01T15:54:44.000Z
2022-03-24T13:52:59.000Z
#include "config.h" #include "uhjfilter.h" #ifdef HAVE_SSE_INTRINSICS #include <xmmintrin.h> #elif defined(HAVE_NEON) #include <arm_neon.h> #endif #include <algorithm> #include <iterator> #include "alcomplex.h" #include "alnumeric.h" #include "opthelpers.h" namespace { using complex_d = std::complex<double>; struct PhaseShifterT { alignas(16) std::array<float,Uhj2Encoder::sFilterSize> Coeffs; /* Some notes on this filter construction. * * A wide-band phase-shift filter needs a delay to maintain linearity. A * dirac impulse in the center of a time-domain buffer represents a filter * passing all frequencies through as-is with a pure delay. Converting that * to the frequency domain, adjusting the phase of each frequency bin by * +90 degrees, then converting back to the time domain, results in a FIR * filter that applies a +90 degree wide-band phase-shift. * * A particularly notable aspect of the time-domain filter response is that * every other coefficient is 0. This allows doubling the effective size of * the filter, by storing only the non-0 coefficients and double-stepping * over the input to apply it. * * Additionally, the resulting filter is independent of the sample rate. * The same filter can be applied regardless of the device's sample rate * and achieve the same effect. */ PhaseShifterT() { constexpr size_t fft_size{Uhj2Encoder::sFilterSize * 2}; constexpr size_t half_size{fft_size / 2}; /* Generate a frequency domain impulse with a +90 degree phase offset. * Reconstruct the mirrored frequencies to convert to the time domain. */ auto fftBuffer = std::make_unique<complex_d[]>(fft_size); std::fill_n(fftBuffer.get(), fft_size, complex_d{}); fftBuffer[half_size] = 1.0; forward_fft({fftBuffer.get(), fft_size}); for(size_t i{0};i < half_size+1;++i) fftBuffer[i] = complex_d{-fftBuffer[i].imag(), fftBuffer[i].real()}; for(size_t i{half_size+1};i < fft_size;++i) fftBuffer[i] = std::conj(fftBuffer[fft_size - i]); inverse_fft({fftBuffer.get(), fft_size}); /* Reverse the filter for simpler processing, and store only the non-0 * coefficients. */ auto fftiter = fftBuffer.get() + half_size + (Uhj2Encoder::sFilterSize-1); for(float &coeff : Coeffs) { coeff = static_cast<float>(fftiter->real() / double{fft_size}); fftiter -= 2; } } }; const PhaseShifterT PShift{}; void allpass_process(al::span<float> dst, const float *RESTRICT src) { #ifdef HAVE_SSE_INTRINSICS size_t pos{0}; if(size_t todo{dst.size()>>1}) { do { __m128 r04{_mm_setzero_ps()}; __m128 r14{_mm_setzero_ps()}; for(size_t j{0};j < PShift.Coeffs.size();j+=4) { const __m128 coeffs{_mm_load_ps(&PShift.Coeffs[j])}; const __m128 s0{_mm_loadu_ps(&src[j*2])}; const __m128 s1{_mm_loadu_ps(&src[j*2 + 4])}; __m128 s{_mm_shuffle_ps(s0, s1, _MM_SHUFFLE(2, 0, 2, 0))}; r04 = _mm_add_ps(r04, _mm_mul_ps(s, coeffs)); s = _mm_shuffle_ps(s0, s1, _MM_SHUFFLE(3, 1, 3, 1)); r14 = _mm_add_ps(r14, _mm_mul_ps(s, coeffs)); } r04 = _mm_add_ps(r04, _mm_shuffle_ps(r04, r04, _MM_SHUFFLE(0, 1, 2, 3))); r04 = _mm_add_ps(r04, _mm_movehl_ps(r04, r04)); dst[pos++] += _mm_cvtss_f32(r04); r14 = _mm_add_ps(r14, _mm_shuffle_ps(r14, r14, _MM_SHUFFLE(0, 1, 2, 3))); r14 = _mm_add_ps(r14, _mm_movehl_ps(r14, r14)); dst[pos++] += _mm_cvtss_f32(r14); src += 2; } while(--todo); } if((dst.size()&1)) { __m128 r4{_mm_setzero_ps()}; for(size_t j{0};j < PShift.Coeffs.size();j+=4) { const __m128 coeffs{_mm_load_ps(&PShift.Coeffs[j])}; /* NOTE: This could alternatively be done with two unaligned loads * and a shuffle. Which would be better? */ const __m128 s{_mm_setr_ps(src[j*2], src[j*2 + 2], src[j*2 + 4], src[j*2 + 6])}; r4 = _mm_add_ps(r4, _mm_mul_ps(s, coeffs)); } r4 = _mm_add_ps(r4, _mm_shuffle_ps(r4, r4, _MM_SHUFFLE(0, 1, 2, 3))); r4 = _mm_add_ps(r4, _mm_movehl_ps(r4, r4)); dst[pos] += _mm_cvtss_f32(r4); } #elif defined(HAVE_NEON) size_t pos{0}; if(size_t todo{dst.size()>>1}) { /* There doesn't seem to be NEON intrinsics to do this kind of stipple * shuffling, so there's two custom methods for it. */ auto shuffle_2020 = [](float32x4_t a, float32x4_t b) { float32x4_t ret{vmovq_n_f32(vgetq_lane_f32(a, 0))}; ret = vsetq_lane_f32(vgetq_lane_f32(a, 2), ret, 1); ret = vsetq_lane_f32(vgetq_lane_f32(b, 0), ret, 2); ret = vsetq_lane_f32(vgetq_lane_f32(b, 2), ret, 3); return ret; }; auto shuffle_3131 = [](float32x4_t a, float32x4_t b) { float32x4_t ret{vmovq_n_f32(vgetq_lane_f32(a, 1))}; ret = vsetq_lane_f32(vgetq_lane_f32(a, 3), ret, 1); ret = vsetq_lane_f32(vgetq_lane_f32(b, 1), ret, 2); ret = vsetq_lane_f32(vgetq_lane_f32(b, 3), ret, 3); return ret; }; do { float32x4_t r04{vdupq_n_f32(0.0f)}; float32x4_t r14{vdupq_n_f32(0.0f)}; for(size_t j{0};j < PShift.Coeffs.size();j+=4) { const float32x4_t coeffs{vld1q_f32(&PShift.Coeffs[j])}; const float32x4_t s0{vld1q_f32(&src[j*2])}; const float32x4_t s1{vld1q_f32(&src[j*2 + 4])}; r04 = vmlaq_f32(r04, shuffle_2020(s0, s1), coeffs); r14 = vmlaq_f32(r14, shuffle_3131(s0, s1), coeffs); } r04 = vaddq_f32(r04, vrev64q_f32(r04)); dst[pos++] = vget_lane_f32(vadd_f32(vget_low_f32(r04), vget_high_f32(r04)), 0); r14 = vaddq_f32(r14, vrev64q_f32(r14)); dst[pos++] = vget_lane_f32(vadd_f32(vget_low_f32(r14), vget_high_f32(r14)), 0); src += 2; } while(--todo); } if((dst.size()&1)) { auto load4 = [](float32_t a, float32_t b, float32_t c, float32_t d) { float32x4_t ret{vmovq_n_f32(a)}; ret = vsetq_lane_f32(b, ret, 1); ret = vsetq_lane_f32(c, ret, 2); ret = vsetq_lane_f32(d, ret, 3); return ret; }; float32x4_t r4{vdupq_n_f32(0.0f)}; for(size_t j{0};j < PShift.Coeffs.size();j+=4) { const float32x4_t coeffs{vld1q_f32(&PShift.Coeffs[j])}; const float32x4_t s{load4(src[j*2], src[j*2 + 2], src[j*2 + 4], src[j*2 + 6])}; r4 = vmlaq_f32(r4, s, coeffs); } r4 = vaddq_f32(r4, vrev64q_f32(r4)); dst[pos] = vget_lane_f32(vadd_f32(vget_low_f32(r4), vget_high_f32(r4)), 0); } #else for(float &output : dst) { float ret{0.0f}; for(size_t j{0};j < PShift.Coeffs.size();++j) ret += src[j*2] * PShift.Coeffs[j]; output += ret; ++src; } #endif } } // namespace /* Encoding 2-channel UHJ from B-Format is done as: * * S = 0.9396926*W + 0.1855740*X * D = j(-0.3420201*W + 0.5098604*X) + 0.6554516*Y * * Left = (S + D)/2.0 * Right = (S - D)/2.0 * * where j is a wide-band +90 degree phase shift. * * The phase shift is done using a FIR filter derived from an FFT'd impulse * with the desired shift. */ void Uhj2Encoder::encode(FloatBufferLine &LeftOut, FloatBufferLine &RightOut, const FloatBufferLine *InSamples, const size_t SamplesToDo) { ASSUME(SamplesToDo > 0); float *RESTRICT left{al::assume_aligned<16>(LeftOut.data())}; float *RESTRICT right{al::assume_aligned<16>(RightOut.data())}; const float *RESTRICT winput{al::assume_aligned<16>(InSamples[0].data())}; const float *RESTRICT xinput{al::assume_aligned<16>(InSamples[1].data())}; const float *RESTRICT yinput{al::assume_aligned<16>(InSamples[2].data())}; /* Combine the previously delayed mid/side signal with the input. */ /* S = 0.9396926*W + 0.1855740*X */ auto miditer = std::copy(mMidDelay.cbegin(), mMidDelay.cend(), mMid.begin()); std::transform(winput, winput+SamplesToDo, xinput, miditer, [](const float w, const float x) noexcept -> float { return 0.9396926f*w + 0.1855740f*x; }); /* D = 0.6554516*Y */ auto sideiter = std::copy(mSideDelay.cbegin(), mSideDelay.cend(), mSide.begin()); std::transform(yinput, yinput+SamplesToDo, sideiter, [](const float y) noexcept -> float { return 0.6554516f*y; }); /* Include any existing direct signal in the mid/side buffers. */ for(size_t i{0};i < SamplesToDo;++i,++miditer) *miditer += left[i] + right[i]; for(size_t i{0};i < SamplesToDo;++i,++sideiter) *sideiter += left[i] - right[i]; /* Copy the future samples back to the delay buffers for next time. */ std::copy_n(mMid.cbegin()+SamplesToDo, mMidDelay.size(), mMidDelay.begin()); std::copy_n(mSide.cbegin()+SamplesToDo, mSideDelay.size(), mSideDelay.begin()); /* Now add the all-passed signal into the side signal. */ /* D += j(-0.3420201*W + 0.5098604*X) */ auto tmpiter = std::copy(mSideHistory.cbegin(), mSideHistory.cend(), mTemp.begin()); std::transform(winput, winput+SamplesToDo, xinput, tmpiter, [](const float w, const float x) noexcept -> float { return -0.3420201f*w + 0.5098604f*x; }); std::copy_n(mTemp.cbegin()+SamplesToDo, mSideHistory.size(), mSideHistory.begin()); allpass_process({mSide.data(), SamplesToDo}, mTemp.data()); /* Left = (S + D)/2.0 */ for(size_t i{0};i < SamplesToDo;i++) left[i] = (mMid[i] + mSide[i]) * 0.5f; /* Right = (S - D)/2.0 */ for(size_t i{0};i < SamplesToDo;i++) right[i] = (mMid[i] - mSide[i]) * 0.5f; }
36.82971
92
0.593015
[ "transform" ]
92f889a3f615e56d46b29c304acc409213c62db7
454
hpp
C++
contributors/kirill_tolstobrov/graph_path.hpp
AxoyTO/TheGraph
4ced7206847f5bb22bd25a48ff09247c5b1218ef
[ "MIT" ]
1
2022-02-07T15:52:51.000Z
2022-02-07T15:52:51.000Z
contributors/kirill_tolstobrov/graph_path.hpp
AxoyTO/TheGraph
4ced7206847f5bb22bd25a48ff09247c5b1218ef
[ "MIT" ]
null
null
null
contributors/kirill_tolstobrov/graph_path.hpp
AxoyTO/TheGraph
4ced7206847f5bb22bd25a48ff09247c5b1218ef
[ "MIT" ]
2
2022-02-07T15:53:00.000Z
2022-02-12T13:31:36.000Z
#pragma once #include <vector> #include "graph.hpp" namespace uni_cpp_practice { struct GraphPath { using Distance = int; explicit GraphPath(const std::vector<VertexId>& init_vertex_ids) : vertex_ids(init_vertex_ids) {} Distance distance() const { return vertex_ids.size() - 1; }; std::vector<VertexId> get_vertex_ids() const { return vertex_ids; } private: std::vector<VertexId> vertex_ids; }; } // namespace uni_cpp_practice
18.916667
69
0.718062
[ "vector" ]
92fbff146d4e32362a4c2701dc74d20084ced4f5
1,653
cpp
C++
aws-cpp-sdk-wafv2/source/model/GeoMatchStatement.cpp
neil-b/aws-sdk-cpp
1602b75abbca880b770c12788f6d2bac0c87176a
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-wafv2/source/model/GeoMatchStatement.cpp
neil-b/aws-sdk-cpp
1602b75abbca880b770c12788f6d2bac0c87176a
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-wafv2/source/model/GeoMatchStatement.cpp
neil-b/aws-sdk-cpp
1602b75abbca880b770c12788f6d2bac0c87176a
[ "Apache-2.0" ]
null
null
null
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/wafv2/model/GeoMatchStatement.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace WAFV2 { namespace Model { GeoMatchStatement::GeoMatchStatement() : m_countryCodesHasBeenSet(false) { } GeoMatchStatement::GeoMatchStatement(JsonView jsonValue) : m_countryCodesHasBeenSet(false) { *this = jsonValue; } GeoMatchStatement& GeoMatchStatement::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("CountryCodes")) { Array<JsonView> countryCodesJsonList = jsonValue.GetArray("CountryCodes"); for(unsigned countryCodesIndex = 0; countryCodesIndex < countryCodesJsonList.GetLength(); ++countryCodesIndex) { m_countryCodes.push_back(CountryCodeMapper::GetCountryCodeForName(countryCodesJsonList[countryCodesIndex].AsString())); } m_countryCodesHasBeenSet = true; } return *this; } JsonValue GeoMatchStatement::Jsonize() const { JsonValue payload; if(m_countryCodesHasBeenSet) { Array<JsonValue> countryCodesJsonList(m_countryCodes.size()); for(unsigned countryCodesIndex = 0; countryCodesIndex < countryCodesJsonList.GetLength(); ++countryCodesIndex) { countryCodesJsonList[countryCodesIndex].AsString(CountryCodeMapper::GetNameForCountryCode(m_countryCodes[countryCodesIndex])); } payload.WithArray("CountryCodes", std::move(countryCodesJsonList)); } return payload; } } // namespace Model } // namespace WAFV2 } // namespace Aws
24.308824
131
0.758016
[ "model" ]
92feb57fde6e268c26ca50a49913afda718fd8cb
2,862
cpp
C++
mparse/src/error_handling.cpp
nmraz/mparse
77dbdd349746eb33265c0d1254c5402c65c59a6a
[ "MIT" ]
null
null
null
mparse/src/error_handling.cpp
nmraz/mparse
77dbdd349746eb33265c0d1254c5402c65c59a6a
[ "MIT" ]
null
null
null
mparse/src/error_handling.cpp
nmraz/mparse
77dbdd349746eb33265c0d1254c5402c65c59a6a
[ "MIT" ]
null
null
null
#include "error_handling.h" #include "diagnostics.h" #include "mparse/ast.h" #include <iostream> #include <sstream> using namespace std::literals; namespace { void print_math_error(std::string_view msg) { print_error("Math", msg); } void print_syntax_error(std::string_view msg) { print_error("Syntax", msg); } void append_msg(std::ostream& msg, const std::exception& nested) { msg << ": " << nested.what(); } void handle_bad_func_call(const ast_ops::eval_error& err, const mparse::source_map& smap, std::string_view input) { auto* node = static_cast<const mparse::func_node*>(err.node()); std::vector locs = { smap.find_locs(node)[1], // function name }; std::ostringstream msg; msg << err.what(); try { std::rethrow_if_nested(err); } catch (const ast_ops::arity_error& arity_err) { append_msg(msg, arity_err); auto expected = arity_err.expected(); auto provided = arity_err.provided(); if (expected < provided) { for (const auto& arg : util::span{node->args()}.last(provided - expected)) { locs.push_back(smap.find_primary_loc(arg.get())); } } } catch (const ast_ops::func_arg_error& arg_err) { append_msg(msg, arg_err); for (auto index : arg_err.indices()) { locs.push_back(smap.find_primary_loc(node->args()[index].get())); } } catch (const std::exception& inner) { append_msg(msg, inner); } catch (...) { } print_math_error(msg.str()); print_locs(input, locs); } } // namespace void handle_syntax_error(const mparse::syntax_error& err, std::string_view input) { print_syntax_error(err.what()); print_locs(input, err.where()); if (!err.fixit_hint().empty()) { print_fixit(err.fixit_hint(), err.fixit_col()); } } void handle_math_error(const ast_ops::eval_error& err, const mparse::source_map& smap, std::string_view input) { auto* node = static_cast<const mparse::binary_op_node*>(err.node()); switch (err.code()) { case ast_ops::eval_errc::div_by_zero: print_math_error(err.what()); print_loc(input, smap.find_primary_loc(node->rhs())); break; case ast_ops::eval_errc::bad_pow: print_math_error(err.what()); print_locs(input, {smap.find_primary_loc(node->lhs()), smap.find_primary_loc(node->rhs())}); break; case ast_ops::eval_errc::unbound_var: print_math_error(err.what()); print_loc(input, smap.find_primary_loc(err.node())); break; case ast_ops::eval_errc::bad_func_call: handle_bad_func_call(err, smap, input); break; case ast_ops::eval_errc::out_of_range: print_math_error(err.what()); print_locs(input, {smap.find_primary_loc(err.node())}); break; default: print_math_error(err.what()); break; } }
26.5
80
0.646401
[ "vector" ]
1300d322001008b9568816b9b9d99a0e8ce2fe1b
7,426
hpp
C++
external/mapnik/include/mapnik/feature.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
external/mapnik/include/mapnik/feature.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
external/mapnik/include/mapnik/feature.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 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_FEATURE_HPP #define MAPNIK_FEATURE_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/value_types.hpp> #include <mapnik/value.hpp> #include <mapnik/box2d.hpp> #include <mapnik/geometry.hpp> #include <mapnik/geometry_envelope.hpp> // #include <mapnik/feature_kv_iterator.hpp> #include <mapnik/util/noncopyable.hpp> // stl #include <memory> #include <vector> #include <map> #include <ostream> // for basic_ostream, operator<<, etc #include <sstream> // for basic_stringstream #include <stdexcept> // for out_of_range #include <iostream> namespace mapnik { class raster; class feature_impl; using raster_ptr = std::shared_ptr<raster>; template <typename T> class context : private util::noncopyable { friend class feature_impl; public: using map_type = T; using value_type = typename map_type::value_type; using key_type = typename map_type::key_type; using size_type = typename map_type::size_type; using difference_type = typename map_type::difference_type; using iterator = typename map_type::iterator; using const_iterator = typename map_type::const_iterator; context() : mapping_() {} inline size_type push(key_type const& name) { size_type index = mapping_.size(); mapping_.emplace(name, index); return index; } inline void add(key_type const& name, size_type index) { mapping_.emplace(name, index); } inline size_type size() const { return mapping_.size(); } inline const_iterator begin() const { return mapping_.begin();} inline const_iterator end() const { return mapping_.end();} private: map_type mapping_; }; using context_type = context<std::map<std::string,std::size_t> >; using context_ptr = std::shared_ptr<context_type>; static const value default_feature_value{}; class MAPNIK_DECL feature_impl : private util::noncopyable { friend class feature_kv_iterator; public: using value_type = mapnik::value; using cont_type = std::vector<value_type>; using iterator = feature_kv_iterator; feature_impl(context_ptr const& ctx, mapnik::value_integer _id) : id_(_id), ctx_(ctx), data_(ctx_->mapping_.size()), geom_(geometry::geometry_empty()), raster_() {} inline mapnik::value_integer id() const { return id_;} inline void set_id(mapnik::value_integer _id) { id_ = _id;} template <typename T> inline void put(context_type::key_type const& key, T const& val) { put(key, value(val)); } template <typename T> inline void put_new(context_type::key_type const& key, T const& val) { put_new(key, value(val)); } inline void put(context_type::key_type const& key, value && val) { context_type::map_type::const_iterator itr = ctx_->mapping_.find(key); if (itr != ctx_->mapping_.end() && itr->second < data_.size()) { data_[itr->second] = std::move(val); } else { throw std::out_of_range(std::string("Key does not exist: '") + key + "'"); } } inline void put_new(context_type::key_type const& key, value && val) { context_type::map_type::const_iterator itr = ctx_->mapping_.find(key); if (itr != ctx_->mapping_.end() && itr->second < data_.size()) { data_[itr->second] = std::move(val); } else { cont_type::size_type index = ctx_->push(key); if (index == data_.size()) data_.push_back(std::move(val)); } } inline bool has_key(context_type::key_type const& key) const { return (ctx_->mapping_.count(key) == 1); } inline value_type const& get(context_type::key_type const& key) const { context_type::map_type::const_iterator itr = ctx_->mapping_.find(key); if (itr != ctx_->mapping_.end()) return get(itr->second); else return default_feature_value; } inline value_type const& get(std::size_t index) const { if (index < data_.size()) return data_[index]; return default_feature_value; } inline std::size_t size() const { return data_.size(); } inline cont_type const& get_data() const { return data_; } inline void set_data(cont_type const& data) { data_ = data; } inline context_ptr context() const { return ctx_; } inline void set_geometry(geometry::geometry<double> && geom) { geom_ = std::move(geom); } inline void set_geometry_copy(geometry::geometry<double> const& geom) { geom_ = geom; } inline geometry::geometry<double> const& get_geometry() const { return geom_; } inline box2d<double> envelope() const { return mapnik::geometry::envelope(geom_); } inline raster_ptr const& get_raster() const { return raster_; } inline void set_raster(raster_ptr const& raster) { raster_ = raster; } inline feature_kv_iterator begin() const { return feature_kv_iterator(*this,true); } inline feature_kv_iterator end() const { return feature_kv_iterator(*this); } std::string to_string() const { std::stringstream ss; ss << "Feature ( id=" << id_ << std::endl; for (auto const& kv : ctx_->mapping_) { std::size_t index = kv.second; if (index < data_.size()) { if (data_[kv.second] == mapnik::value_null()) { ss << " " << kv.first << ":null" << std::endl; } else { ss << " " << kv.first << ":" << data_[kv.second] << std::endl; } } } ss << ")" << std::endl; return ss.str(); } private: mapnik::value_integer id_; context_ptr ctx_; cont_type data_; geometry::geometry<double> geom_; raster_ptr raster_; }; inline std::ostream& operator<< (std::ostream & out,feature_impl const& f) { out << f.to_string(); return out; } using feature_ptr = std::shared_ptr<feature_impl>; } #endif // MAPNIK_FEATURE_HPP
26.616487
86
0.599111
[ "geometry", "vector" ]
130467090ce089d1b4063d44a67748b12e8d427b
5,572
cpp
C++
objs__gun_port.cpp
poikilos/golgotha
d3184dea6b061f853423e0666dba23218042e5ba
[ "CC0-1.0" ]
5
2015-12-09T20:37:49.000Z
2021-08-10T08:06:29.000Z
objs__gun_port.cpp
poikilos/golgotha
d3184dea6b061f853423e0666dba23218042e5ba
[ "CC0-1.0" ]
13
2021-09-20T16:25:30.000Z
2022-03-17T04:59:40.000Z
objs__gun_port.cpp
poikilos/golgotha
d3184dea6b061f853423e0666dba23218042e5ba
[ "CC0-1.0" ]
5
2016-01-04T22:54:22.000Z
2021-09-20T16:09:03.000Z
#include "pch.h" /********************************************************************** Golgotha Forever - A portable, free 3D strategy and FPS game. Copyright (C) 1999 Golgotha Forever Developers Sources contained in this distribution were derived from Crack Dot Com's public release of Golgotha which can be found here: http://www.crack.com All changes and new works are licensed under the GPL: 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 For the full license, see COPYING. ***********************************************************************/ #include "objs/def_object.h" #include "lisp/li_init.h" #include "lisp/li_class.h" #include "li_objref.h" #include "map_man.h" #include "map.h" #include "math/pi.h" #include "objs/map_piece.h" #include "object_definer.h" static li_int_class_member explode_health("explode_health"), fire_delay("fire_delay"), total_burst("total_burst"), burst_delay("burst_delay"); static li_symbol_class_member fire_type("fire_type"); static g1_model_ref barrel_ref("gunport_barrel"); void g1_gunport_init() { }; class g1_gunport_class : public g1_map_piece_class { protected: g1_mini_object * barrel; public: enum { DATA_VERSION=1 }; g1_gunport_class(g1_object_type id, g1_loader_class * fp); virtual void think(); virtual void save(g1_saver_class * fp); }; g1_object_definer<g1_gunport_class> g1_gunport_def("gunport", g1_object_definition_class::EDITOR_SELECTABLE| g1_object_definition_class::TO_MAP_PIECE, g1_gunport_init); g1_gunport_class::g1_gunport_class(g1_object_type id, g1_loader_class * fp) : g1_map_piece_class(id,fp) { defaults=g1_gunport_def.defaults; draw_params.setup("gunport_base"); allocate_mini_objects(1,"gunport mini objects"); barrel=&mini_objects[0]; barrel->x=0; barrel->y=0; barrel->h=0.1f; barrel->rotation.y=i4_pi(); barrel->defmodeltype = barrel_ref.id(); radar_type=G1_RADAR_BUILDING; set_flag(SELECTABLE| TARGETABLE| DANGEROUS| GROUND| HIT_GROUND| BLOCKING| HIT_UNDERWATER| HIT_AERIAL,1); w16 ver, data_size; if (fp) { fp->get_version(ver,data_size); //actally, we don't exspect any data for us fp->seek(fp->tell() + data_size); fp->end_version(I4_LF); } else { ver=0; } } //li_object *g1_gunport_damage(li_object *o, li_environment *env) //{ // g1_dynamic_object_class *me=g1_dynamic_object_class::get(li_car(o,env),env); // int hp=li_int::get(li_car(li_cdr(li_cdr(o,env),env),env),env)->value(); // health()-=hp; // me->request_think(); // return 0; //} //li_object *g1_gunport_enter_range(li_object *o, li_environment *env) //{ // return 0; //} void g1_gunport_class::save(g1_saver_class * fp) { g1_map_piece_class::save(fp); fp->start_version(DATA_VERSION); fp->end_version(); } void g1_gunport_class::think() { if (health < 0) { if (health < explode_health()) { unoccupy_location(); request_remove(); } else { set_flag(g1_object_class::DANGEROUS,0); health--; request_think(); } return; } theta+=defaults->turn_speed; } //static li_float_class_member turn_speed("turn_speed"), speed("speed"), // max_speed("max_speed"), hill_scale("hill_scale"), damage_speedup("damage_speedup"); /* li_object *g1_speed_damage(li_object *o, li_environment *env) { g1_dynamic_object_class *me=g1_dynamic_object_class::get(li_car(o)); int hp=li_int::get(li_car(li_cdr(li_cdr(o))))->value(); speed()+=hp * damage_speedup(); me->request_think(); return 0; } */ /*li_object *g1_circle_think(li_object *o, li_environment *env) { g1_dynamic_object_class *me=g1_dynamic_object_class::get(li_car(o,env),env); me->grab_old(); me->unoccupy_location(); float s=me->defaults->speed; me->x += cos(me->theta)*s; me->y += sin(me->theta)*s; float h=g1_get_map()->terrain_height(me->x, me->y); if (h<me->h) // going down hill speed up { s += (me->h-h) * hill_scale(); if (s>max_speed()) s=max_speed(); speed()=s; me->h=h; } else if (h>me->h) // going up hill, slow down { s += (me->h-h) * hill_scale(); if (s<0) { me->theta+=i4_pi(); // turn around s=0.001; } speed()=s; me->h=h; } me->theta += turn_speed(); if (me->occupy_location()) me->request_think(); return 0; } */ //li_automatic_add_function(g1_speed_damage, "speed_damage"); //li_automatic_add_function(g1_circle_think, "circle_think"); //li_automatic_add_function(g1_gunport_damage, "gunport_damage"); //li_automatic_add_function(g1_gunport_think, "gunport_think"); //li_automatic_add_function(g1_gunport_enter_range, "gunport_enter_range");
25.677419
88
0.653984
[ "3d" ]
13079fed1fd529e6ce522858564dfe6855d8979f
1,982
cpp
C++
test/fibonaccisearch.cpp
nowtechnologies/cpp-qspi-flash-driver
4520b8ad15cfe67d525529c3142d6963107b3efb
[ "MIT" ]
1
2021-03-12T01:59:41.000Z
2021-03-12T01:59:41.000Z
test/fibonaccisearch.cpp
nowtechnologies/cpp-qspi-flash-driver
4520b8ad15cfe67d525529c3142d6963107b3efb
[ "MIT" ]
null
null
null
test/fibonaccisearch.cpp
nowtechnologies/cpp-qspi-flash-driver
4520b8ad15cfe67d525529c3142d6963107b3efb
[ "MIT" ]
1
2020-05-22T18:29:36.000Z
2020-05-22T18:29:36.000Z
#include<algorithm> #include<iostream> #include<numeric> #include<iomanip> #include<vector> #include<string> #include<limits> #include<cmath> int main(int argc, char **argv) { int ret; if(argc > 1) { std::string arg(argv[1]); int length = std::stoi(arg); int displacement = -1; int maxSoFar = std::numeric_limits<int>::max(); for(int d = length / 4; d <= 3 * length / 4; ++d) { if(std::gcd(d ,length) == 1) { int m = length % d; int n = std::min(m, d - m); int value = std::abs(d * (d - 3 * n) + n * n); if(value < maxSoFar) { maxSoFar = value; displacement = d; } else { // nothing to do } } else { // nothing to do } } if(displacement > 0) { std::cout << "displacement: " << displacement << " ratio: " << static_cast<double>(displacement) / length << " maxSoFar: " << maxSoFar << '\n'; int where = 0; std::vector<bool> was(length, false); for(int i = 0; i < length; ++i) { was[where] = true; where = (where + displacement) % length; int maxFree = 0; std::vector<bool>::iterator found0; std::vector<bool>::iterator found1 = was.begin(); do { found0 = std::find(found1, was.end(), false); found1 = std::find(found0, was.end(), true); maxFree = std::max(static_cast<int>(found1 - found0), maxFree); } while(found0 != was.end()); std::cout << std::setw(4) << i << ' ' << std::setw(4) << (length + i) / (i + 1) << std::setw(4) << maxFree << " - "; for(int j = 0; j < length; ++j) { std::cout << (was[j] ? static_cast<char>(('0' + j % 10)) : ' '); } std::cout << '\n'; } ret = 0; } else { std::cerr << "No suitable displacement found.\n"; ret = 1; } } else { std::cerr << "Usage: " << argv[0] << " [length of partition]\n"; ret = 1; } return ret; }
30.030303
149
0.493946
[ "vector" ]
130ac089d44cbc4b42a743118c7c948850a4c398
8,500
cpp
C++
example_manager/src/example_manager.cpp
ctu-mrs/example_ros_pluginlib
b566f9b9cef82f1f69508fd45b59e63c8a27b817
[ "BSD-3-Clause" ]
null
null
null
example_manager/src/example_manager.cpp
ctu-mrs/example_ros_pluginlib
b566f9b9cef82f1f69508fd45b59e63c8a27b817
[ "BSD-3-Clause" ]
null
null
null
example_manager/src/example_manager.cpp
ctu-mrs/example_ros_pluginlib
b566f9b9cef82f1f69508fd45b59e63c8a27b817
[ "BSD-3-Clause" ]
null
null
null
#include <ros/ros.h> #include <nodelet/nodelet.h> #include <example_manager/plugin_interface.h> #include <mrs_lib/param_loader.h> #include <mrs_lib/mutex.h> #include <pluginlib/class_loader.h> namespace example_manager { /* //{ class ExampleManager */ /* class PluginParams() //{ */ class PluginParams { public: PluginParams(const std::string& address, const std::string& name_space, const double& some_property); public: std::string address; std::string name_space; double some_property; }; PluginParams::PluginParams(const std::string& address, const std::string& name_space, const double& some_property) { this->address = address; this->name_space = name_space; this->some_property = some_property; } //} class ExampleManager : public nodelet::Nodelet { public: virtual void onInit(); private: ros::NodeHandle nh_; bool is_initialized_ = false; // | ---------------------- update timer ---------------------- | ros::Timer timer_update_; double _rate_timer_update_; // | -------- an object we want to share to our plugins ------- | std::string example_of_a_shared_object_; // | --------------------- common handlers -------------------- | std::shared_ptr<example_manager::CommonHandlers_t> common_handlers_; // | --------------- dynamic loading of plugins --------------- | std::unique_ptr<pluginlib::ClassLoader<example_manager::Plugin>> plugin_loader_; // pluginlib loader std::vector<std::string> _plugin_names_; std::map<std::string, PluginParams> plugins_; // map between plugin names and plugin params std::vector<boost::shared_ptr<example_manager::Plugin>> plugin_list_; // list of plugins, routines are callable from this std::mutex mutex_plugins_; std::string _initial_plugin_name_; int _initial_plugin_idx_ = 0; int active_plugin_idx_ = 0; // | ------------------------ routines ------------------------ | double vectorNorm(const Eigen::Vector3d& input); // | ------------------------- timers ------------------------- | void timerUpdate(const ros::TimerEvent& event); }; //} /* onInit() //{ */ void ExampleManager::onInit() { ros::NodeHandle nh_ = nodelet::Nodelet::getMTPrivateNodeHandle(); ros::Time::waitForValid(); ROS_INFO("[ExampleManager]: initializing"); // -------------------------------------------------------------- // | params | // -------------------------------------------------------------- mrs_lib::ParamLoader param_loader(nh_, "ExampleManager"); param_loader.loadParam("update_timer_rate", _rate_timer_update_); param_loader.loadParam("initial_plugin", _initial_plugin_name_); // | --------------- example of a shared object --------------- | example_of_a_shared_object_ = "Hello, this is a shared object"; // -------------------------------------------------------------- // | common handlers | // -------------------------------------------------------------- common_handlers_ = std::make_shared<example_manager::CommonHandlers_t>(); common_handlers_->some_shared_object = std::make_shared<std::string>(example_of_a_shared_object_); common_handlers_->vector_calculator.vectorNorm = boost::bind(&ExampleManager::vectorNorm, this, _1); common_handlers_->vector_calculator.enabled = true; // -------------------------------------------------------------- // | load the plugins | // -------------------------------------------------------------- param_loader.loadParam("plugins", _plugin_names_); plugin_loader_ = std::make_unique<pluginlib::ClassLoader<example_manager::Plugin>>("example_manager", "example_manager::Plugin"); // for each plugin in the list for (int i = 0; i < int(_plugin_names_.size()); i++) { std::string plugin_name = _plugin_names_[i]; // load the plugin parameters std::string address; std::string name_space; double some_property; param_loader.loadParam(plugin_name + "/address", address); param_loader.loadParam(plugin_name + "/name_space", name_space); param_loader.loadParam(plugin_name + "/some_property", some_property); PluginParams new_plugin(address, name_space, some_property); plugins_.insert(std::pair<std::string, PluginParams>(plugin_name, new_plugin)); try { ROS_INFO("[ExampleManager]: loading the plugin '%s'", new_plugin.address.c_str()); plugin_list_.push_back(plugin_loader_->createInstance(new_plugin.address.c_str())); } catch (pluginlib::CreateClassException& ex1) { ROS_ERROR("[ExampleManager]: CreateClassException for the plugin '%s'", new_plugin.address.c_str()); ROS_ERROR("[ExampleManager]: Error: %s", ex1.what()); ros::shutdown(); } catch (pluginlib::PluginlibException& ex) { ROS_ERROR("[ExampleManager]: PluginlibException for the plugin '%s'", new_plugin.address.c_str()); ROS_ERROR("[ExampleManager]: Error: %s", ex.what()); ros::shutdown(); } } ROS_INFO("[ExampleManager]: plugins were loaded"); for (int i = 0; i < int(plugin_list_.size()); i++) { try { std::map<std::string, PluginParams>::iterator it; it = plugins_.find(_plugin_names_[i]); ROS_INFO("[ExampleManager]: initializing the plugin '%s'", it->second.address.c_str()); plugin_list_[i]->initialize(nh_, _plugin_names_[i], it->second.name_space, common_handlers_); } catch (std::runtime_error& ex) { ROS_ERROR("[ExampleManager]: exception caught during plugin initialization: '%s'", ex.what()); } } ROS_INFO("[ExampleManager]: plugins were initialized"); // -------------------------------------------------------------- // | check for existance of the initial plugin | // -------------------------------------------------------------- { bool check = false; for (int i = 0; i < int(_plugin_names_.size()); i++) { std::string plugin_name = _plugin_names_[i]; if (plugin_name == _initial_plugin_name_) { check = true; _initial_plugin_idx_ = i; break; } } if (!check) { ROS_ERROR("[ExampleManager]: the initial plugin (%s) is not within the loaded plugins", _initial_plugin_name_.c_str()); ros::shutdown(); } } // | ---------- activate the first plugin on the list --------- | ROS_INFO("[ExampleManager]: activating plugin with idx %d on the list (named: %s)", _initial_plugin_idx_, _plugin_names_[_initial_plugin_idx_].c_str()); int some_activation_input_to_plugin = 1234; plugin_list_[_initial_plugin_idx_]->activate(some_activation_input_to_plugin); active_plugin_idx_ = _initial_plugin_idx_; // | ------------------------- timers ------------------------- | timer_update_ = nh_.createTimer(ros::Rate(_rate_timer_update_), &ExampleManager::timerUpdate, this); // | ----------------------- finish init ---------------------- | if (!param_loader.loadedSuccessfully()) { ROS_ERROR("[ExampleManager]: could not load all parameters!"); ros::shutdown(); } is_initialized_ = true; ROS_INFO("[ExampleManager]: initialized"); } //} // | ------------------------- timers ------------------------- | /* timerUpdate() //{ */ void ExampleManager::timerUpdate([[maybe_unused]] const ros::TimerEvent& event) { if (!is_initialized_) return; auto active_plugin_idx = mrs_lib::get_mutexed(mutex_plugins_, active_plugin_idx_); // plugin input Eigen::Vector3d input; input << 0, 1, 2; // call the plugin's update routine auto result = plugin_list_[active_plugin_idx]->update(input); if (result) { // print the result ROS_INFO("[ExampleManager]: plugin update() returned: %.2f", result.value()); } else { ROS_ERROR("[ExampleManager]: plugin update failed!"); } } //} // | ------------------------ routines ------------------------ | /* vectorNorm() //{ */ double ExampleManager::vectorNorm(const Eigen::Vector3d& input) { ROS_INFO("[ExampleManager]: somebody called my vectorNorm() function, probably some plugin"); return input.norm(); } //} } // namespace example_manager #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(example_manager::ExampleManager, nodelet::Nodelet)
31.135531
154
0.587647
[ "object", "vector" ]
130dfa28d7f1e987cf1914b0505514a3d1811dd5
912
cpp
C++
30 Days of Code/Day 21 Generics.cpp
ersincebi/hackerrank
9475c8e88e9071544c10a939fe7307c8e62fe3a0
[ "MIT" ]
null
null
null
30 Days of Code/Day 21 Generics.cpp
ersincebi/hackerrank
9475c8e88e9071544c10a939fe7307c8e62fe3a0
[ "MIT" ]
null
null
null
30 Days of Code/Day 21 Generics.cpp
ersincebi/hackerrank
9475c8e88e9071544c10a939fe7307c8e62fe3a0
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> using namespace std; /** * Name: printArray * Print each element of the generic vector on a new line. Do not return anything. * @param A generic vector **/ // Write your code here template <class T> void printArray(vector<T> int_vector){ for(int i=0; i<int_vector.size(); i++) cout<<int_vector[i]<<endl; } int main() { int n; // cin >> n; vector<int> int_vector(3); int_vector[0] = 1; int_vector[1] = 2; int_vector[2] = 3; // for (int i = 0; i < n; i++) { // int value; // cin >> value; // int_vector[i] = value; // } // cin >> n; vector<string> string_vector(2); string_vector[0] = "Hello"; string_vector[1] = "World"; // for (int i = 0; i < n; i++) { // string value; // cin >> value; // string_vector[i] = value; // } printArray<int>(int_vector); printArray<string>(string_vector); return 0; }
19
84
0.601974
[ "vector" ]
13115f940f276500a7b12d2a8b0bd1e8a1104316
107,573
cc
C++
third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "platform/scheduler/base/task_queue_manager.h" #include <stddef.h> #include <utility> #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted_memory.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/test/simple_test_tick_clock.h" #include "base/test/trace_event_analyzer.h" #include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/blame_context.h" #include "base/trace_event/trace_buffer.h" #include "cc/test/ordered_simple_task_runner.h" #include "platform/scheduler/base/real_time_domain.h" #include "platform/scheduler/base/task_queue_impl.h" #include "platform/scheduler/base/task_queue_manager_delegate_for_test.h" #include "platform/scheduler/base/task_queue_selector.h" #include "platform/scheduler/base/test_count_uses_time_source.h" #include "platform/scheduler/base/test_task_time_observer.h" #include "platform/scheduler/base/test_time_source.h" #include "platform/scheduler/base/virtual_time_domain.h" #include "platform/scheduler/base/work_queue.h" #include "platform/scheduler/base/work_queue_sets.h" #include "platform/scheduler/test/test_task_queue.h" #include "testing/gmock/include/gmock/gmock.h" using ::testing::AnyNumber; using ::testing::Contains; using ::testing::ElementsAre; using ::testing::ElementsAreArray; using ::testing::Mock; using ::testing::Not; using ::testing::_; using blink::scheduler::internal::EnqueueOrder; namespace blink { namespace scheduler { class TaskQueueManagerForTest : public TaskQueueManager { public: explicit TaskQueueManagerForTest( scoped_refptr<TaskQueueManagerDelegate> delegate) : TaskQueueManager(delegate) {} using TaskQueueManager::NextTaskDelay; }; class MessageLoopTaskRunner : public TaskQueueManagerDelegateForTest { public: static scoped_refptr<MessageLoopTaskRunner> Create( std::unique_ptr<base::TickClock> tick_clock) { return make_scoped_refptr(new MessageLoopTaskRunner(std::move(tick_clock))); } // TaskQueueManagerDelegateForTest: bool IsNested() const override { DCHECK(RunsTasksInCurrentSequence()); return base::RunLoop::IsNestedOnCurrentThread(); } void AddNestingObserver(base::RunLoop::NestingObserver* observer) override { base::RunLoop::AddNestingObserverOnCurrentThread(observer); } void RemoveNestingObserver( base::RunLoop::NestingObserver* observer) override { base::RunLoop::RemoveNestingObserverOnCurrentThread(observer); } private: explicit MessageLoopTaskRunner(std::unique_ptr<base::TickClock> tick_clock) : TaskQueueManagerDelegateForTest(base::ThreadTaskRunnerHandle::Get(), std::move(tick_clock)) {} ~MessageLoopTaskRunner() override {} }; class TaskQueueManagerTest : public ::testing::Test { public: TaskQueueManagerTest() {} void DeleteTaskQueueManager() { manager_.reset(); } protected: scoped_refptr<TestTaskQueue> CreateTaskQueueWithSpec(TaskQueue::Spec spec) { return manager_->CreateTaskQueue<TestTaskQueue>(spec); } scoped_refptr<TestTaskQueue> CreateTaskQueue() { return CreateTaskQueueWithSpec(TaskQueue::Spec("test")); } scoped_refptr<TestTaskQueue> CreateTaskQueueWithMonitoredQuiescence() { return CreateTaskQueueWithSpec( TaskQueue::Spec("test").SetShouldMonitorQuiescence(true)); } void InitializeWithClock(size_t num_queues, std::unique_ptr<base::TickClock> test_time_source) { test_task_runner_ = make_scoped_refptr( new cc::OrderedSimpleTaskRunner(now_src_.get(), false)); main_task_runner_ = TaskQueueManagerDelegateForTest::Create( test_task_runner_.get(), base::MakeUnique<TestTimeSource>(now_src_.get())); manager_ = base::MakeUnique<TaskQueueManagerForTest>(main_task_runner_); for (size_t i = 0; i < num_queues; i++) runners_.push_back(CreateTaskQueue()); } void Initialize(size_t num_queues) { now_src_.reset(new base::SimpleTestTickClock()); now_src_->Advance(base::TimeDelta::FromMicroseconds(1000)); InitializeWithClock(num_queues, base::MakeUnique<TestTimeSource>(now_src_.get())); } void InitializeWithRealMessageLoop(size_t num_queues) { now_src_.reset(new base::SimpleTestTickClock()); message_loop_.reset(new base::MessageLoop()); // A null clock triggers some assertions. now_src_->Advance(base::TimeDelta::FromMicroseconds(1000)); manager_ = base::MakeUnique<TaskQueueManagerForTest>(MessageLoopTaskRunner::Create( base::WrapUnique(new TestTimeSource(now_src_.get())))); for (size_t i = 0; i < num_queues; i++) runners_.push_back(CreateTaskQueue()); } void WakeUpReadyDelayedQueues(LazyNow lazy_now) { manager_->WakeUpReadyDelayedQueues(&lazy_now); } using NextTaskDelay = TaskQueueManagerForTest::NextTaskDelay; base::Optional<NextTaskDelay> ComputeDelayTillNextTask(LazyNow* lazy_now) { base::AutoLock lock(manager_->any_thread_lock_); return manager_->ComputeDelayTillNextTaskLocked(lazy_now); } void PostDoWorkContinuation(base::Optional<NextTaskDelay> next_delay, LazyNow* lazy_now) { MoveableAutoLock lock(manager_->any_thread_lock_); return manager_->PostDoWorkContinuationLocked(next_delay, lazy_now, std::move(lock)); } int immediate_do_work_posted_count() const { base::AutoLock lock(manager_->any_thread_lock_); return manager_->any_thread().immediate_do_work_posted_count; } base::TimeTicks next_delayed_do_work_time() const { return manager_->next_delayed_do_work_.run_time(); } EnqueueOrder GetNextSequenceNumber() const { return manager_->GetNextSequenceNumber(); } void MaybeScheduleImmediateWorkLocked( const tracked_objects::Location& from_here) { MoveableAutoLock lock(manager_->any_thread_lock_); manager_->MaybeScheduleImmediateWorkLocked(from_here, std::move(lock)); } // Runs all immediate tasks until there is no more work to do and advances // time if there is a pending delayed task. |per_run_time_callback| is called // when the clock advances. void RunUntilIdle(base::Closure per_run_time_callback) { for (;;) { // Advance time if we've run out of immediate work to do. if (manager_->selector_.EnabledWorkQueuesEmpty()) { base::TimeTicks run_time; if (manager_->real_time_domain()->NextScheduledRunTime(&run_time)) { now_src_->SetNowTicks(run_time); per_run_time_callback.Run(); } else { break; } } test_task_runner_->RunPendingTasks(); } } std::unique_ptr<base::MessageLoop> message_loop_; std::unique_ptr<base::SimpleTestTickClock> now_src_; scoped_refptr<TaskQueueManagerDelegateForTest> main_task_runner_; scoped_refptr<cc::OrderedSimpleTaskRunner> test_task_runner_; std::unique_ptr<TaskQueueManagerForTest> manager_; std::vector<scoped_refptr<TestTaskQueue>> runners_; TestTaskTimeObserver test_task_time_observer_; }; void PostFromNestedRunloop(base::MessageLoop* message_loop, base::SingleThreadTaskRunner* runner, std::vector<std::pair<base::Closure, bool>>* tasks) { base::MessageLoop::ScopedNestableTaskAllower allow(message_loop); for (std::pair<base::Closure, bool>& pair : *tasks) { if (pair.second) { runner->PostTask(FROM_HERE, pair.first); } else { runner->PostNonNestableTask(FROM_HERE, pair.first); } } base::RunLoop().RunUntilIdle(); } void NopTask() {} TEST_F(TaskQueueManagerTest, NowCalledMinimumNumberOfTimesToComputeTaskDurations) { message_loop_.reset(new base::MessageLoop()); // This memory is managed by the TaskQueueManager, but we need to hold a // pointer to this object to read out how many times Now was called. TestCountUsesTimeSource* test_count_uses_time_source = new TestCountUsesTimeSource(); manager_ = base::MakeUnique<TaskQueueManagerForTest>(MessageLoopTaskRunner::Create( base::WrapUnique(test_count_uses_time_source))); manager_->SetWorkBatchSize(6); manager_->AddTaskTimeObserver(&test_task_time_observer_); for (size_t i = 0; i < 3; i++) runners_.push_back(CreateTaskQueue()); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); runners_[1]->PostTask(FROM_HERE, base::Bind(&NopTask)); runners_[1]->PostTask(FROM_HERE, base::Bind(&NopTask)); runners_[2]->PostTask(FROM_HERE, base::Bind(&NopTask)); runners_[2]->PostTask(FROM_HERE, base::Bind(&NopTask)); base::RunLoop().RunUntilIdle(); // We need to call Now for the beginning of the first task, and then the end // of every task after. We reuse the end time of one task for the start time // of the next task. In this case, there were 6 tasks, so we expect 7 calls to // Now. EXPECT_EQ(7, test_count_uses_time_source->now_calls_count()); } TEST_F(TaskQueueManagerTest, NowNotCalledForNestedTasks) { message_loop_.reset(new base::MessageLoop()); // This memory is managed by the TaskQueueManager, but we need to hold a // pointer to this object to read out how many times Now was called. TestCountUsesTimeSource* test_count_uses_time_source = new TestCountUsesTimeSource(); manager_ = base::MakeUnique<TaskQueueManagerForTest>(MessageLoopTaskRunner::Create( base::WrapUnique(test_count_uses_time_source))); manager_->AddTaskTimeObserver(&test_task_time_observer_); runners_.push_back(CreateTaskQueue()); std::vector<std::pair<base::Closure, bool>> tasks_to_post_from_nested_loop; for (int i = 0; i <= 6; ++i) { tasks_to_post_from_nested_loop.push_back( std::make_pair(base::Bind(&NopTask), true)); } runners_[0]->PostTask( FROM_HERE, base::Bind(&PostFromNestedRunloop, message_loop_.get(), base::RetainedRef(runners_[0]), base::Unretained(&tasks_to_post_from_nested_loop))); base::RunLoop().RunUntilIdle(); // We need to call Now twice, to measure the start and end of the outermost // task. We shouldn't call it for any of the nested tasks. EXPECT_EQ(2, test_count_uses_time_source->now_calls_count()); } void NullTask() {} void TestTask(EnqueueOrder value, std::vector<EnqueueOrder>* out_result) { out_result->push_back(value); } TEST_F(TaskQueueManagerTest, SingleQueuePosting) { Initialize(1u); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order)); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1, 2, 3)); } TEST_F(TaskQueueManagerTest, MultiQueuePosting) { Initialize(3u); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); runners_[1]->PostTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order)); runners_[1]->PostTask(FROM_HERE, base::Bind(&TestTask, 4, &run_order)); runners_[2]->PostTask(FROM_HERE, base::Bind(&TestTask, 5, &run_order)); runners_[2]->PostTask(FROM_HERE, base::Bind(&TestTask, 6, &run_order)); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1, 2, 3, 4, 5, 6)); } TEST_F(TaskQueueManagerTest, NonNestableTaskPosting) { InitializeWithRealMessageLoop(1u); std::vector<EnqueueOrder> run_order; runners_[0]->PostNonNestableTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); base::RunLoop().RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1)); } TEST_F(TaskQueueManagerTest, NonNestableTaskExecutesInExpectedOrder) { InitializeWithRealMessageLoop(1u); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 4, &run_order)); runners_[0]->PostNonNestableTask(FROM_HERE, base::Bind(&TestTask, 5, &run_order)); base::RunLoop().RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1, 2, 3, 4, 5)); } TEST_F(TaskQueueManagerTest, NonNestableTaskDoesntExecuteInNestedLoop) { InitializeWithRealMessageLoop(1u); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); std::vector<std::pair<base::Closure, bool>> tasks_to_post_from_nested_loop; tasks_to_post_from_nested_loop.push_back( std::make_pair(base::Bind(&TestTask, 3, &run_order), false)); tasks_to_post_from_nested_loop.push_back( std::make_pair(base::Bind(&TestTask, 4, &run_order), true)); tasks_to_post_from_nested_loop.push_back( std::make_pair(base::Bind(&TestTask, 5, &run_order), true)); runners_[0]->PostTask( FROM_HERE, base::Bind(&PostFromNestedRunloop, message_loop_.get(), base::RetainedRef(runners_[0]), base::Unretained(&tasks_to_post_from_nested_loop))); base::RunLoop().RunUntilIdle(); // Note we expect task 3 to run last because it's non-nestable. EXPECT_THAT(run_order, ElementsAre(1, 2, 4, 5, 3)); } TEST_F(TaskQueueManagerTest, HasPendingImmediateWork_ImmediateTask) { Initialize(1u); std::vector<EnqueueOrder> run_order; EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately()); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately()); // Move the task into the |immediate_work_queue|. EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->immediate_work_queue()->Empty()); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = runners_[0]->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); test_task_runner_->RunUntilIdle(); EXPECT_FALSE( runners_[0]->GetTaskQueueImpl()->immediate_work_queue()->Empty()); EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately()); // Run the task, making the queue empty. voter->SetQueueEnabled(true); test_task_runner_->RunUntilIdle(); EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately()); } TEST_F(TaskQueueManagerTest, HasPendingImmediateWork_DelayedTask) { Initialize(1u); std::vector<EnqueueOrder> run_order; base::TimeDelta delay(base::TimeDelta::FromMilliseconds(10)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), delay); EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately()); now_src_->Advance(delay); EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately()); // Move the task into the |delayed_work_queue|. WakeUpReadyDelayedQueues(LazyNow(now_src_.get())); EXPECT_FALSE(runners_[0]->GetTaskQueueImpl()->delayed_work_queue()->Empty()); EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately()); // Run the task, making the queue empty. test_task_runner_->RunUntilIdle(); EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately()); } TEST_F(TaskQueueManagerTest, DelayedTaskPosting) { Initialize(1u); std::vector<EnqueueOrder> run_order; base::TimeDelta delay(base::TimeDelta::FromMilliseconds(10)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), delay); EXPECT_EQ(delay, test_task_runner_->DelayToNextTaskTime()); EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately()); EXPECT_TRUE(run_order.empty()); // The task doesn't run before the delay has completed. test_task_runner_->RunForPeriod(base::TimeDelta::FromMilliseconds(9)); EXPECT_TRUE(run_order.empty()); // After the delay has completed, the task runs normally. test_task_runner_->RunForPeriod(base::TimeDelta::FromMilliseconds(1)); EXPECT_THAT(run_order, ElementsAre(1)); EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately()); } bool MessageLoopTaskCounter(size_t* count) { *count = *count + 1; return true; } TEST_F(TaskQueueManagerTest, DelayedTaskExecutedInOneMessageLoopTask) { Initialize(1u); base::TimeDelta delay(base::TimeDelta::FromMilliseconds(10)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay); size_t task_count = 0; test_task_runner_->RunTasksWhile( base::Bind(&MessageLoopTaskCounter, &task_count)); EXPECT_EQ(1u, task_count); } TEST_F(TaskQueueManagerTest, DelayedTaskPosting_MultipleTasks_DecendingOrder) { Initialize(1u); std::vector<EnqueueOrder> run_order; runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), base::TimeDelta::FromMilliseconds(10)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order), base::TimeDelta::FromMilliseconds(8)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order), base::TimeDelta::FromMilliseconds(5)); EXPECT_EQ(base::TimeDelta::FromMilliseconds(5), test_task_runner_->DelayToNextTaskTime()); test_task_runner_->RunForPeriod(base::TimeDelta::FromMilliseconds(5)); EXPECT_THAT(run_order, ElementsAre(3)); EXPECT_EQ(base::TimeDelta::FromMilliseconds(3), test_task_runner_->DelayToNextTaskTime()); test_task_runner_->RunForPeriod(base::TimeDelta::FromMilliseconds(3)); EXPECT_THAT(run_order, ElementsAre(3, 2)); EXPECT_EQ(base::TimeDelta::FromMilliseconds(2), test_task_runner_->DelayToNextTaskTime()); test_task_runner_->RunForPeriod(base::TimeDelta::FromMilliseconds(2)); EXPECT_THAT(run_order, ElementsAre(3, 2, 1)); } TEST_F(TaskQueueManagerTest, DelayedTaskPosting_MultipleTasks_AscendingOrder) { Initialize(1u); std::vector<EnqueueOrder> run_order; runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), base::TimeDelta::FromMilliseconds(1)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order), base::TimeDelta::FromMilliseconds(5)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order), base::TimeDelta::FromMilliseconds(10)); EXPECT_EQ(base::TimeDelta::FromMilliseconds(1), test_task_runner_->DelayToNextTaskTime()); test_task_runner_->RunForPeriod(base::TimeDelta::FromMilliseconds(1)); EXPECT_THAT(run_order, ElementsAre(1)); EXPECT_EQ(base::TimeDelta::FromMilliseconds(4), test_task_runner_->DelayToNextTaskTime()); test_task_runner_->RunForPeriod(base::TimeDelta::FromMilliseconds(4)); EXPECT_THAT(run_order, ElementsAre(1, 2)); EXPECT_EQ(base::TimeDelta::FromMilliseconds(5), test_task_runner_->DelayToNextTaskTime()); test_task_runner_->RunForPeriod(base::TimeDelta::FromMilliseconds(5)); EXPECT_THAT(run_order, ElementsAre(1, 2, 3)); } TEST_F(TaskQueueManagerTest, PostDelayedTask_SharesUnderlyingDelayedTasks) { Initialize(1u); std::vector<EnqueueOrder> run_order; base::TimeDelta delay(base::TimeDelta::FromMilliseconds(10)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), delay); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order), delay); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order), delay); EXPECT_EQ(1u, test_task_runner_->NumPendingTasks()); } class TestObject { public: ~TestObject() { destructor_count__++; } void Run() { FAIL() << "TestObject::Run should not be called"; } static int destructor_count__; }; int TestObject::destructor_count__ = 0; TEST_F(TaskQueueManagerTest, PendingDelayedTasksRemovedOnShutdown) { Initialize(1u); TestObject::destructor_count__ = 0; base::TimeDelta delay(base::TimeDelta::FromMilliseconds(10)); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&TestObject::Run, base::Owned(new TestObject())), delay); runners_[0]->PostTask( FROM_HERE, base::Bind(&TestObject::Run, base::Owned(new TestObject()))); manager_.reset(); EXPECT_EQ(2, TestObject::destructor_count__); } TEST_F(TaskQueueManagerTest, InsertAndRemoveFence) { Initialize(1u); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); std::vector<EnqueueOrder> run_order; // Posting a task when pumping is disabled doesn't result in work getting // posted. runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); EXPECT_FALSE(test_task_runner_->HasPendingTasks()); // However polling still works. EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately()); // After removing the fence the task runs normally. runners_[0]->RemoveFence(); EXPECT_TRUE(test_task_runner_->HasPendingTasks()); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1)); } TEST_F(TaskQueueManagerTest, RemovingFenceForDisabledQueueDoesNotPostDoWork) { Initialize(1u); std::vector<EnqueueOrder> run_order; std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = runners_[0]->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[0]->RemoveFence(); EXPECT_FALSE(test_task_runner_->HasPendingTasks()); } TEST_F(TaskQueueManagerTest, EnablingFencedQueueDoesNotPostDoWork) { Initialize(1u); std::vector<EnqueueOrder> run_order; std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = runners_[0]->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); voter->SetQueueEnabled(true); EXPECT_FALSE(test_task_runner_->HasPendingTasks()); } TEST_F(TaskQueueManagerTest, DenyRunning_BeforePosting) { Initialize(1u); std::vector<EnqueueOrder> run_order; std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = runners_[0]->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); EXPECT_FALSE(test_task_runner_->HasPendingTasks()); test_task_runner_->RunUntilIdle(); EXPECT_TRUE(run_order.empty()); voter->SetQueueEnabled(true); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1)); } TEST_F(TaskQueueManagerTest, DenyRunning_AfterPosting) { Initialize(1u); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = runners_[0]->CreateQueueEnabledVoter(); EXPECT_TRUE(test_task_runner_->HasPendingTasks()); voter->SetQueueEnabled(false); test_task_runner_->RunUntilIdle(); EXPECT_TRUE(run_order.empty()); voter->SetQueueEnabled(true); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1)); } TEST_F(TaskQueueManagerTest, DenyRunning_AfterRemovingFence) { Initialize(1u); std::vector<EnqueueOrder> run_order; runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = runners_[0]->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); test_task_runner_->RunUntilIdle(); EXPECT_TRUE(run_order.empty()); runners_[0]->RemoveFence(); voter->SetQueueEnabled(true); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1)); } TEST_F(TaskQueueManagerTest, RemovingFenceWithDelayedTask) { Initialize(1u); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); std::vector<EnqueueOrder> run_order; // Posting a delayed task when fenced will apply the delay, but won't cause // work to executed afterwards. base::TimeDelta delay(base::TimeDelta::FromMilliseconds(10)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), delay); // The task does not run even though it's delay is up. test_task_runner_->RunForPeriod(base::TimeDelta::FromMilliseconds(10)); EXPECT_TRUE(run_order.empty()); // Removing the fence causes the task to run. runners_[0]->RemoveFence(); EXPECT_TRUE(test_task_runner_->HasPendingTasks()); test_task_runner_->RunPendingTasks(); EXPECT_THAT(run_order, ElementsAre(1)); } TEST_F(TaskQueueManagerTest, RemovingFenceWithMultipleDelayedTasks) { Initialize(1u); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); std::vector<EnqueueOrder> run_order; // Posting a delayed task when fenced will apply the delay, but won't cause // work to executed afterwards. base::TimeDelta delay1(base::TimeDelta::FromMilliseconds(1)); base::TimeDelta delay2(base::TimeDelta::FromMilliseconds(10)); base::TimeDelta delay3(base::TimeDelta::FromMilliseconds(20)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), delay1); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order), delay2); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order), delay3); now_src_->Advance(base::TimeDelta::FromMilliseconds(15)); test_task_runner_->RunUntilIdle(); EXPECT_TRUE(run_order.empty()); // Removing the fence causes the ready tasks to run. runners_[0]->RemoveFence(); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1, 2)); } TEST_F(TaskQueueManagerTest, InsertFencePreventsDelayedTasksFromRunning) { Initialize(1u); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); std::vector<EnqueueOrder> run_order; base::TimeDelta delay(base::TimeDelta::FromMilliseconds(10)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), delay); test_task_runner_->RunForPeriod(base::TimeDelta::FromMilliseconds(10)); EXPECT_TRUE(run_order.empty()); } TEST_F(TaskQueueManagerTest, MultipleFences) { Initialize(1u); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order)); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1, 2)); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); // Subsequent tasks should be blocked. runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 4, &run_order)); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1, 2, 3)); } TEST_F(TaskQueueManagerTest, InsertFenceThenImmediatlyRemoveDoesNotBlock) { Initialize(1u); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); runners_[0]->RemoveFence(); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1, 2)); } TEST_F(TaskQueueManagerTest, InsertFencePostThenRemoveDoesNotBlock) { Initialize(1u); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); runners_[0]->RemoveFence(); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1, 2)); } TEST_F(TaskQueueManagerTest, MultipleFencesWithInitiallyEmptyQueue) { Initialize(1u); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1)); } TEST_F(TaskQueueManagerTest, BlockedByFence) { Initialize(1u); EXPECT_FALSE(runners_[0]->BlockedByFence()); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); EXPECT_TRUE(runners_[0]->BlockedByFence()); runners_[0]->RemoveFence(); EXPECT_FALSE(runners_[0]->BlockedByFence()); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); EXPECT_FALSE(runners_[0]->BlockedByFence()); test_task_runner_->RunUntilIdle(); EXPECT_TRUE(runners_[0]->BlockedByFence()); runners_[0]->RemoveFence(); EXPECT_FALSE(runners_[0]->BlockedByFence()); } TEST_F(TaskQueueManagerTest, BlockedByFence_BothTypesOfFence) { Initialize(1u); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); EXPECT_FALSE(runners_[0]->BlockedByFence()); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::BEGINNING_OF_TIME); EXPECT_TRUE(runners_[0]->BlockedByFence()); } void ReentrantTestTask(scoped_refptr<base::SingleThreadTaskRunner> runner, int countdown, std::vector<EnqueueOrder>* out_result) { out_result->push_back(countdown); if (--countdown) { runner->PostTask(FROM_HERE, Bind(&ReentrantTestTask, runner, countdown, out_result)); } } TEST_F(TaskQueueManagerTest, ReentrantPosting) { Initialize(1u); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, Bind(&ReentrantTestTask, runners_[0], 3, &run_order)); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(3, 2, 1)); } TEST_F(TaskQueueManagerTest, NoTasksAfterShutdown) { Initialize(1u); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); manager_.reset(); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); test_task_runner_->RunUntilIdle(); EXPECT_TRUE(run_order.empty()); } void PostTaskToRunner(scoped_refptr<base::SingleThreadTaskRunner> runner, std::vector<EnqueueOrder>* run_order) { runner->PostTask(FROM_HERE, base::Bind(&TestTask, 1, run_order)); } TEST_F(TaskQueueManagerTest, PostFromThread) { InitializeWithRealMessageLoop(1u); std::vector<EnqueueOrder> run_order; base::Thread thread("TestThread"); thread.Start(); thread.task_runner()->PostTask( FROM_HERE, base::Bind(&PostTaskToRunner, runners_[0], &run_order)); thread.Stop(); base::RunLoop().RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1)); } void RePostingTestTask(scoped_refptr<base::SingleThreadTaskRunner> runner, int* run_count) { (*run_count)++; runner->PostTask(FROM_HERE, Bind(&RePostingTestTask, base::Unretained(runner.get()), run_count)); } TEST_F(TaskQueueManagerTest, DoWorkCantPostItselfMultipleTimes) { Initialize(1u); int run_count = 0; runners_[0]->PostTask( FROM_HERE, base::Bind(&RePostingTestTask, runners_[0], &run_count)); test_task_runner_->RunPendingTasks(); // NOTE without the executing_task_ check in MaybeScheduleDoWork there // will be two tasks here. EXPECT_EQ(1u, test_task_runner_->NumPendingTasks()); EXPECT_EQ(1, run_count); } TEST_F(TaskQueueManagerTest, PostFromNestedRunloop) { InitializeWithRealMessageLoop(1u); std::vector<EnqueueOrder> run_order; std::vector<std::pair<base::Closure, bool>> tasks_to_post_from_nested_loop; tasks_to_post_from_nested_loop.push_back( std::make_pair(base::Bind(&TestTask, 1, &run_order), true)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 0, &run_order)); runners_[0]->PostTask( FROM_HERE, base::Bind(&PostFromNestedRunloop, message_loop_.get(), base::RetainedRef(runners_[0]), base::Unretained(&tasks_to_post_from_nested_loop))); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); base::RunLoop().RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(0, 2, 1)); } TEST_F(TaskQueueManagerTest, WorkBatching) { Initialize(1u); manager_->SetWorkBatchSize(2); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 4, &run_order)); // Running one task in the host message loop should cause two posted tasks to // get executed. EXPECT_EQ(test_task_runner_->NumPendingTasks(), 1u); test_task_runner_->RunPendingTasks(); EXPECT_THAT(run_order, ElementsAre(1, 2)); // The second task runs the remaining two posted tasks. EXPECT_EQ(test_task_runner_->NumPendingTasks(), 1u); test_task_runner_->RunPendingTasks(); EXPECT_THAT(run_order, ElementsAre(1, 2, 3, 4)); } class MockTaskObserver : public base::MessageLoop::TaskObserver { public: MOCK_METHOD1(DidProcessTask, void(const base::PendingTask& task)); MOCK_METHOD1(WillProcessTask, void(const base::PendingTask& task)); }; TEST_F(TaskQueueManagerTest, TaskObserverAdding) { InitializeWithRealMessageLoop(1u); MockTaskObserver observer; manager_->SetWorkBatchSize(2); manager_->AddTaskObserver(&observer); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); EXPECT_CALL(observer, WillProcessTask(_)).Times(2); EXPECT_CALL(observer, DidProcessTask(_)).Times(2); base::RunLoop().RunUntilIdle(); } TEST_F(TaskQueueManagerTest, TaskObserverRemoving) { InitializeWithRealMessageLoop(1u); MockTaskObserver observer; manager_->SetWorkBatchSize(2); manager_->AddTaskObserver(&observer); manager_->RemoveTaskObserver(&observer); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); EXPECT_CALL(observer, WillProcessTask(_)).Times(0); EXPECT_CALL(observer, DidProcessTask(_)).Times(0); base::RunLoop().RunUntilIdle(); } void RemoveObserverTask(TaskQueueManager* manager, base::MessageLoop::TaskObserver* observer) { manager->RemoveTaskObserver(observer); } TEST_F(TaskQueueManagerTest, TaskObserverRemovingInsideTask) { InitializeWithRealMessageLoop(1u); MockTaskObserver observer; manager_->SetWorkBatchSize(3); manager_->AddTaskObserver(&observer); runners_[0]->PostTask( FROM_HERE, base::Bind(&RemoveObserverTask, manager_.get(), &observer)); EXPECT_CALL(observer, WillProcessTask(_)).Times(1); EXPECT_CALL(observer, DidProcessTask(_)).Times(0); base::RunLoop().RunUntilIdle(); } TEST_F(TaskQueueManagerTest, QueueTaskObserverAdding) { InitializeWithRealMessageLoop(2u); MockTaskObserver observer; manager_->SetWorkBatchSize(2); runners_[0]->AddTaskObserver(&observer); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[1]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); EXPECT_CALL(observer, WillProcessTask(_)).Times(1); EXPECT_CALL(observer, DidProcessTask(_)).Times(1); base::RunLoop().RunUntilIdle(); } TEST_F(TaskQueueManagerTest, QueueTaskObserverRemoving) { InitializeWithRealMessageLoop(1u); MockTaskObserver observer; manager_->SetWorkBatchSize(2); runners_[0]->AddTaskObserver(&observer); runners_[0]->RemoveTaskObserver(&observer); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); EXPECT_CALL(observer, WillProcessTask(_)).Times(0); EXPECT_CALL(observer, DidProcessTask(_)).Times(0); base::RunLoop().RunUntilIdle(); } void RemoveQueueObserverTask(scoped_refptr<TaskQueue> queue, base::MessageLoop::TaskObserver* observer) { queue->RemoveTaskObserver(observer); } TEST_F(TaskQueueManagerTest, QueueTaskObserverRemovingInsideTask) { InitializeWithRealMessageLoop(1u); MockTaskObserver observer; runners_[0]->AddTaskObserver(&observer); runners_[0]->PostTask( FROM_HERE, base::Bind(&RemoveQueueObserverTask, runners_[0], &observer)); EXPECT_CALL(observer, WillProcessTask(_)).Times(1); EXPECT_CALL(observer, DidProcessTask(_)).Times(0); base::RunLoop().RunUntilIdle(); } TEST_F(TaskQueueManagerTest, ThreadCheckAfterTermination) { Initialize(1u); EXPECT_TRUE(runners_[0]->RunsTasksInCurrentSequence()); manager_.reset(); EXPECT_TRUE(runners_[0]->RunsTasksInCurrentSequence()); } TEST_F(TaskQueueManagerTest, TimeDomain_NextScheduledRunTime) { Initialize(2u); now_src_->Advance(base::TimeDelta::FromMicroseconds(10000)); // With no delayed tasks. base::TimeTicks run_time; EXPECT_FALSE(manager_->real_time_domain()->NextScheduledRunTime(&run_time)); // With a non-delayed task. runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); EXPECT_FALSE(manager_->real_time_domain()->NextScheduledRunTime(&run_time)); // With a delayed task. base::TimeDelta expected_delay = base::TimeDelta::FromMilliseconds(50); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), expected_delay); EXPECT_TRUE(manager_->real_time_domain()->NextScheduledRunTime(&run_time)); EXPECT_EQ(now_src_->NowTicks() + expected_delay, run_time); // With another delayed task in the same queue with a longer delay. runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromMilliseconds(100)); EXPECT_TRUE(manager_->real_time_domain()->NextScheduledRunTime(&run_time)); EXPECT_EQ(now_src_->NowTicks() + expected_delay, run_time); // With another delayed task in the same queue with a shorter delay. expected_delay = base::TimeDelta::FromMilliseconds(20); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), expected_delay); EXPECT_TRUE(manager_->real_time_domain()->NextScheduledRunTime(&run_time)); EXPECT_EQ(now_src_->NowTicks() + expected_delay, run_time); // With another delayed task in a different queue with a shorter delay. expected_delay = base::TimeDelta::FromMilliseconds(10); runners_[1]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), expected_delay); EXPECT_TRUE(manager_->real_time_domain()->NextScheduledRunTime(&run_time)); EXPECT_EQ(now_src_->NowTicks() + expected_delay, run_time); // Test it updates as time progresses now_src_->Advance(expected_delay); EXPECT_TRUE(manager_->real_time_domain()->NextScheduledRunTime(&run_time)); EXPECT_EQ(now_src_->NowTicks(), run_time); } TEST_F(TaskQueueManagerTest, TimeDomain_NextScheduledRunTime_MultipleQueues) { Initialize(3u); base::TimeDelta delay1 = base::TimeDelta::FromMilliseconds(50); base::TimeDelta delay2 = base::TimeDelta::FromMilliseconds(5); base::TimeDelta delay3 = base::TimeDelta::FromMilliseconds(10); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay1); runners_[1]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay2); runners_[2]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay3); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); base::TimeTicks run_time; EXPECT_TRUE(manager_->real_time_domain()->NextScheduledRunTime(&run_time)); EXPECT_EQ(now_src_->NowTicks() + delay2, run_time); } TEST_F(TaskQueueManagerTest, DeleteTaskQueueManagerInsideATask) { Initialize(1u); runners_[0]->PostTask( FROM_HERE, base::Bind(&TaskQueueManagerTest::DeleteTaskQueueManager, base::Unretained(this))); // This should not crash, assuming DoWork detects the TaskQueueManager has // been deleted. test_task_runner_->RunUntilIdle(); } TEST_F(TaskQueueManagerTest, GetAndClearSystemIsQuiescentBit) { Initialize(3u); scoped_refptr<TaskQueue> queue0 = CreateTaskQueueWithMonitoredQuiescence(); scoped_refptr<TaskQueue> queue1 = CreateTaskQueueWithMonitoredQuiescence(); scoped_refptr<TaskQueue> queue2 = CreateTaskQueue(); EXPECT_TRUE(manager_->GetAndClearSystemIsQuiescentBit()); queue0->PostTask(FROM_HERE, base::Bind(&NopTask)); test_task_runner_->RunUntilIdle(); EXPECT_FALSE(manager_->GetAndClearSystemIsQuiescentBit()); EXPECT_TRUE(manager_->GetAndClearSystemIsQuiescentBit()); queue1->PostTask(FROM_HERE, base::Bind(&NopTask)); test_task_runner_->RunUntilIdle(); EXPECT_FALSE(manager_->GetAndClearSystemIsQuiescentBit()); EXPECT_TRUE(manager_->GetAndClearSystemIsQuiescentBit()); queue2->PostTask(FROM_HERE, base::Bind(&NopTask)); test_task_runner_->RunUntilIdle(); EXPECT_TRUE(manager_->GetAndClearSystemIsQuiescentBit()); queue0->PostTask(FROM_HERE, base::Bind(&NopTask)); queue1->PostTask(FROM_HERE, base::Bind(&NopTask)); test_task_runner_->RunUntilIdle(); EXPECT_FALSE(manager_->GetAndClearSystemIsQuiescentBit()); EXPECT_TRUE(manager_->GetAndClearSystemIsQuiescentBit()); } TEST_F(TaskQueueManagerTest, HasPendingImmediateWork) { Initialize(1u); EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately()); runners_[0]->PostTask(FROM_HERE, base::Bind(NullTask)); EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately()); test_task_runner_->RunUntilIdle(); EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately()); } TEST_F(TaskQueueManagerTest, HasPendingImmediateWork_DelayedTasks) { Initialize(1u); EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately()); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(NullTask), base::TimeDelta::FromMilliseconds(12)); EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately()); // Move time forwards until just before the delayed task should run. now_src_->Advance(base::TimeDelta::FromMilliseconds(10)); WakeUpReadyDelayedQueues(LazyNow(now_src_.get())); EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately()); // Force the delayed task onto the work queue. now_src_->Advance(base::TimeDelta::FromMilliseconds(2)); WakeUpReadyDelayedQueues(LazyNow(now_src_.get())); EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately()); test_task_runner_->RunUntilIdle(); EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately()); } void ExpensiveTestTask(int value, base::SimpleTestTickClock* clock, std::vector<EnqueueOrder>* out_result) { out_result->push_back(value); clock->Advance(base::TimeDelta::FromMilliseconds(1)); } TEST_F(TaskQueueManagerTest, ImmediateAndDelayedTaskInterleaving) { Initialize(1u); std::vector<EnqueueOrder> run_order; base::TimeDelta delay = base::TimeDelta::FromMilliseconds(10); for (int i = 10; i < 19; i++) { runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&ExpensiveTestTask, i, now_src_.get(), &run_order), delay); } test_task_runner_->RunForPeriod(delay); for (int i = 0; i < 9; i++) { runners_[0]->PostTask(FROM_HERE, base::Bind(&ExpensiveTestTask, i, now_src_.get(), &run_order)); } test_task_runner_->SetAutoAdvanceNowToPendingTasks(true); test_task_runner_->RunUntilIdle(); // Delayed tasks are not allowed to starve out immediate work which is why // some of the immediate tasks run out of order. int expected_run_order[] = {10, 11, 12, 13, 0, 14, 15, 16, 1, 17, 18, 2, 3, 4, 5, 6, 7, 8}; EXPECT_THAT(run_order, ElementsAreArray(expected_run_order)); } TEST_F(TaskQueueManagerTest, DelayedTaskDoesNotSkipAHeadOfNonDelayedTask_SameQueue) { Initialize(1u); std::vector<EnqueueOrder> run_order; base::TimeDelta delay = base::TimeDelta::FromMilliseconds(10); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), delay); now_src_->Advance(delay * 2); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(2, 3, 1)); } TEST_F(TaskQueueManagerTest, DelayedTaskDoesNotSkipAHeadOfNonDelayedTask_DifferentQueues) { Initialize(2u); std::vector<EnqueueOrder> run_order; base::TimeDelta delay = base::TimeDelta::FromMilliseconds(10); runners_[1]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); runners_[1]->PostTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), delay); now_src_->Advance(delay * 2); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(2, 3, 1)); } TEST_F(TaskQueueManagerTest, DelayedTaskDoesNotSkipAHeadOfShorterDelayedTask) { Initialize(2u); std::vector<EnqueueOrder> run_order; base::TimeDelta delay1 = base::TimeDelta::FromMilliseconds(10); base::TimeDelta delay2 = base::TimeDelta::FromMilliseconds(5); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), delay1); runners_[1]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order), delay2); now_src_->Advance(delay1 * 2); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(2, 1)); } void CheckIsNested(bool* is_nested) { *is_nested = base::RunLoop::IsNestedOnCurrentThread(); } void PostAndQuitFromNestedRunloop(base::RunLoop* run_loop, base::SingleThreadTaskRunner* runner, bool* was_nested) { base::MessageLoop::ScopedNestableTaskAllower allow( base::MessageLoop::current()); runner->PostTask(FROM_HERE, run_loop->QuitClosure()); runner->PostTask(FROM_HERE, base::Bind(&CheckIsNested, was_nested)); run_loop->Run(); } TEST_F(TaskQueueManagerTest, QuitWhileNested) { // This test makes sure we don't continue running a work batch after a nested // run loop has been exited in the middle of the batch. InitializeWithRealMessageLoop(1u); manager_->SetWorkBatchSize(2); bool was_nested = true; base::RunLoop run_loop; runners_[0]->PostTask(FROM_HERE, base::Bind(&PostAndQuitFromNestedRunloop, base::Unretained(&run_loop), base::RetainedRef(runners_[0]), base::Unretained(&was_nested))); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(was_nested); } class SequenceNumberCapturingTaskObserver : public base::MessageLoop::TaskObserver { public: // MessageLoop::TaskObserver overrides. void WillProcessTask(const base::PendingTask& pending_task) override {} void DidProcessTask(const base::PendingTask& pending_task) override { sequence_numbers_.push_back(pending_task.sequence_num); } const std::vector<EnqueueOrder>& sequence_numbers() const { return sequence_numbers_; } private: std::vector<EnqueueOrder> sequence_numbers_; }; TEST_F(TaskQueueManagerTest, SequenceNumSetWhenTaskIsPosted) { Initialize(1u); SequenceNumberCapturingTaskObserver observer; manager_->AddTaskObserver(&observer); // Register four tasks that will run in reverse order. std::vector<EnqueueOrder> run_order; runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), base::TimeDelta::FromMilliseconds(30)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order), base::TimeDelta::FromMilliseconds(20)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order), base::TimeDelta::FromMilliseconds(10)); runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 4, &run_order)); test_task_runner_->RunForPeriod(base::TimeDelta::FromMilliseconds(40)); ASSERT_THAT(run_order, ElementsAre(4, 3, 2, 1)); // The sequence numbers are a one-based monotonically incrememting counter // which should be set when the task is posted rather than when it's enqueued // onto the Incoming queue. This counter starts with 2. EXPECT_THAT(observer.sequence_numbers(), ElementsAre(5, 4, 3, 2)); manager_->RemoveTaskObserver(&observer); } TEST_F(TaskQueueManagerTest, NewTaskQueues) { Initialize(1u); scoped_refptr<TaskQueue> queue1 = CreateTaskQueue(); scoped_refptr<TaskQueue> queue2 = CreateTaskQueue(); scoped_refptr<TaskQueue> queue3 = CreateTaskQueue(); ASSERT_NE(queue1, queue2); ASSERT_NE(queue1, queue3); ASSERT_NE(queue2, queue3); std::vector<EnqueueOrder> run_order; queue1->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); queue2->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); queue3->PostTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order)); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1, 2, 3)); } TEST_F(TaskQueueManagerTest, UnregisterTaskQueue) { Initialize(1u); scoped_refptr<TaskQueue> queue1 = CreateTaskQueue(); scoped_refptr<TaskQueue> queue2 = CreateTaskQueue(); scoped_refptr<TaskQueue> queue3 = CreateTaskQueue(); ASSERT_NE(queue1, queue2); ASSERT_NE(queue1, queue3); ASSERT_NE(queue2, queue3); std::vector<EnqueueOrder> run_order; queue1->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); queue2->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); queue3->PostTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order)); queue2->UnregisterTaskQueue(); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1, 3)); } TEST_F(TaskQueueManagerTest, UnregisterTaskQueue_WithDelayedTasks) { Initialize(2u); // Register three delayed tasks std::vector<EnqueueOrder> run_order; runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), base::TimeDelta::FromMilliseconds(10)); runners_[1]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order), base::TimeDelta::FromMilliseconds(20)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order), base::TimeDelta::FromMilliseconds(30)); runners_[1]->UnregisterTaskQueue(); test_task_runner_->RunUntilIdle(); test_task_runner_->RunForPeriod(base::TimeDelta::FromMilliseconds(40)); ASSERT_THAT(run_order, ElementsAre(1, 3)); } namespace { void UnregisterQueue(scoped_refptr<TaskQueue> queue) { queue->UnregisterTaskQueue(); } } TEST_F(TaskQueueManagerTest, UnregisterTaskQueue_InTasks) { Initialize(3u); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[0]->PostTask(FROM_HERE, base::Bind(&UnregisterQueue, runners_[1])); runners_[0]->PostTask(FROM_HERE, base::Bind(&UnregisterQueue, runners_[2])); runners_[1]->PostTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order)); runners_[2]->PostTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order)); test_task_runner_->RunUntilIdle(); ASSERT_THAT(run_order, ElementsAre(1)); } namespace { class MockObserver : public TaskQueueManager::Observer { public: MOCK_METHOD0(OnTriedToExecuteBlockedTask, void()); }; } // namespace TEST_F(TaskQueueManagerTest, OnTriedToExecuteBlockedTask) { Initialize(0u); MockObserver observer; manager_->SetObserver(&observer); scoped_refptr<TaskQueue> task_queue = CreateTaskQueueWithSpec( TaskQueue::Spec("test").SetShouldReportWhenExecutionBlocked(true)); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = task_queue->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); task_queue->PostTask(FROM_HERE, base::Bind(&NopTask)); // Trick |task_queue| into posting a DoWork. By default PostTask with a // disabled queue won't post a DoWork until we enable the queue. voter->SetQueueEnabled(true); voter->SetQueueEnabled(false); EXPECT_CALL(observer, OnTriedToExecuteBlockedTask()).Times(1); test_task_runner_->RunPendingTasks(); manager_->SetObserver(nullptr); } TEST_F(TaskQueueManagerTest, ExecutedNonBlockedTask) { Initialize(0u); MockObserver observer; manager_->SetObserver(&observer); scoped_refptr<TaskQueue> task_queue = CreateTaskQueueWithSpec( TaskQueue::Spec("test").SetShouldReportWhenExecutionBlocked(true)); task_queue->PostTask(FROM_HERE, base::Bind(&NopTask)); EXPECT_CALL(observer, OnTriedToExecuteBlockedTask()).Times(0); test_task_runner_->RunPendingTasks(); manager_->SetObserver(nullptr); } TEST_F(TaskQueueManagerTest, UnregisterTaskQueueInNestedLoop) { InitializeWithRealMessageLoop(1u); // We retain a reference to the task queue even when the manager has deleted // its reference. scoped_refptr<TaskQueue> task_queue = CreateTaskQueue(); std::vector<bool> log; std::vector<std::pair<base::Closure, bool>> tasks_to_post_from_nested_loop; // Inside a nested run loop, call task_queue->UnregisterTaskQueue, bookended // by calls to HasOneRefTask to make sure the manager doesn't release its // reference until the nested run loop exits. // NB: This first HasOneRefTask is a sanity check. tasks_to_post_from_nested_loop.push_back( std::make_pair(base::Bind(&NopTask), true)); tasks_to_post_from_nested_loop.push_back( std::make_pair(base::Bind(&TaskQueue::UnregisterTaskQueue, base::Unretained(task_queue.get())), true)); tasks_to_post_from_nested_loop.push_back( std::make_pair(base::Bind(&NopTask), true)); runners_[0]->PostTask( FROM_HERE, base::Bind(&PostFromNestedRunloop, message_loop_.get(), base::RetainedRef(runners_[0]), base::Unretained(&tasks_to_post_from_nested_loop))); base::RunLoop().RunUntilIdle(); // Just make sure that we don't crash. } TEST_F(TaskQueueManagerTest, TimeDomainsAreIndependant) { Initialize(2u); base::TimeTicks start_time = manager_->Delegate()->NowTicks(); std::unique_ptr<VirtualTimeDomain> domain_a( new VirtualTimeDomain(start_time)); std::unique_ptr<VirtualTimeDomain> domain_b( new VirtualTimeDomain(start_time)); manager_->RegisterTimeDomain(domain_a.get()); manager_->RegisterTimeDomain(domain_b.get()); runners_[0]->SetTimeDomain(domain_a.get()); runners_[1]->SetTimeDomain(domain_b.get()); std::vector<EnqueueOrder> run_order; runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), base::TimeDelta::FromMilliseconds(10)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order), base::TimeDelta::FromMilliseconds(20)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order), base::TimeDelta::FromMilliseconds(30)); runners_[1]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 4, &run_order), base::TimeDelta::FromMilliseconds(10)); runners_[1]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 5, &run_order), base::TimeDelta::FromMilliseconds(20)); runners_[1]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 6, &run_order), base::TimeDelta::FromMilliseconds(30)); domain_b->AdvanceTo(start_time + base::TimeDelta::FromMilliseconds(50)); manager_->MaybeScheduleImmediateWork(FROM_HERE); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(4, 5, 6)); domain_a->AdvanceTo(start_time + base::TimeDelta::FromMilliseconds(50)); manager_->MaybeScheduleImmediateWork(FROM_HERE); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(4, 5, 6, 1, 2, 3)); runners_[0]->UnregisterTaskQueue(); runners_[1]->UnregisterTaskQueue(); manager_->UnregisterTimeDomain(domain_a.get()); manager_->UnregisterTimeDomain(domain_b.get()); } TEST_F(TaskQueueManagerTest, TimeDomainMigration) { Initialize(1u); base::TimeTicks start_time = manager_->Delegate()->NowTicks(); std::unique_ptr<VirtualTimeDomain> domain_a( new VirtualTimeDomain(start_time)); manager_->RegisterTimeDomain(domain_a.get()); runners_[0]->SetTimeDomain(domain_a.get()); std::vector<EnqueueOrder> run_order; runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), base::TimeDelta::FromMilliseconds(10)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order), base::TimeDelta::FromMilliseconds(20)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order), base::TimeDelta::FromMilliseconds(30)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 4, &run_order), base::TimeDelta::FromMilliseconds(40)); domain_a->AdvanceTo(start_time + base::TimeDelta::FromMilliseconds(20)); manager_->MaybeScheduleImmediateWork(FROM_HERE); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1, 2)); std::unique_ptr<VirtualTimeDomain> domain_b( new VirtualTimeDomain(start_time)); manager_->RegisterTimeDomain(domain_b.get()); runners_[0]->SetTimeDomain(domain_b.get()); domain_b->AdvanceTo(start_time + base::TimeDelta::FromMilliseconds(50)); manager_->MaybeScheduleImmediateWork(FROM_HERE); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1, 2, 3, 4)); runners_[0]->UnregisterTaskQueue(); manager_->UnregisterTimeDomain(domain_a.get()); manager_->UnregisterTimeDomain(domain_b.get()); } TEST_F(TaskQueueManagerTest, TimeDomainMigrationWithIncomingImmediateTasks) { Initialize(1u); base::TimeTicks start_time = manager_->Delegate()->NowTicks(); std::unique_ptr<VirtualTimeDomain> domain_a( new VirtualTimeDomain(start_time)); std::unique_ptr<VirtualTimeDomain> domain_b( new VirtualTimeDomain(start_time)); manager_->RegisterTimeDomain(domain_a.get()); manager_->RegisterTimeDomain(domain_b.get()); runners_[0]->SetTimeDomain(domain_a.get()); std::vector<EnqueueOrder> run_order; runners_[0]->PostTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order)); runners_[0]->SetTimeDomain(domain_b.get()); test_task_runner_->RunUntilIdle(); EXPECT_THAT(run_order, ElementsAre(1)); runners_[0]->UnregisterTaskQueue(); manager_->UnregisterTimeDomain(domain_a.get()); manager_->UnregisterTimeDomain(domain_b.get()); } TEST_F(TaskQueueManagerTest, PostDelayedTasksReverseOrderAlternatingTimeDomains) { Initialize(1u); std::vector<EnqueueOrder> run_order; std::unique_ptr<RealTimeDomain> domain_a(new RealTimeDomain()); std::unique_ptr<RealTimeDomain> domain_b(new RealTimeDomain()); manager_->RegisterTimeDomain(domain_a.get()); manager_->RegisterTimeDomain(domain_b.get()); runners_[0]->SetTimeDomain(domain_a.get()); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 1, &run_order), base::TimeDelta::FromMilliseconds(40)); runners_[0]->SetTimeDomain(domain_b.get()); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 2, &run_order), base::TimeDelta::FromMilliseconds(30)); runners_[0]->SetTimeDomain(domain_a.get()); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 3, &run_order), base::TimeDelta::FromMilliseconds(20)); runners_[0]->SetTimeDomain(domain_b.get()); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&TestTask, 4, &run_order), base::TimeDelta::FromMilliseconds(10)); test_task_runner_->RunForPeriod(base::TimeDelta::FromMilliseconds(40)); EXPECT_THAT(run_order, ElementsAre(4, 3, 2, 1)); runners_[0]->UnregisterTaskQueue(); manager_->UnregisterTimeDomain(domain_a.get()); manager_->UnregisterTimeDomain(domain_b.get()); } namespace { class MockTaskQueueObserver : public TaskQueue::Observer { public: ~MockTaskQueueObserver() override {} MOCK_METHOD2(OnQueueNextWakeUpChanged, void(TaskQueue*, base::TimeTicks)); }; } // namespace TEST_F(TaskQueueManagerTest, TaskQueueObserver_ImmediateTask) { Initialize(1u); MockTaskQueueObserver observer; runners_[0]->SetObserver(&observer); // We should get a notification when a task is posted on an empty queue. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), base::TimeTicks())); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); Mock::VerifyAndClearExpectations(&observer); // But not subsequently. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); Mock::VerifyAndClearExpectations(&observer); // Unless the immediate work queue is emptied. runners_[0]->GetTaskQueueImpl()->ReloadImmediateWorkQueueIfEmpty(); EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), base::TimeTicks())); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); // Tidy up. runners_[0]->UnregisterTaskQueue(); } TEST_F(TaskQueueManagerTest, TaskQueueObserver_DelayedTask) { Initialize(1u); base::TimeTicks start_time = manager_->Delegate()->NowTicks(); base::TimeDelta delay10s(base::TimeDelta::FromSeconds(10)); base::TimeDelta delay100s(base::TimeDelta::FromSeconds(100)); base::TimeDelta delay1s(base::TimeDelta::FromSeconds(1)); MockTaskQueueObserver observer; runners_[0]->SetObserver(&observer); // We should get a notification when a delayed task is posted on an empty // queue. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), start_time + delay10s)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay10s); Mock::VerifyAndClearExpectations(&observer); // We should not get a notification for a longer delay. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay100s); Mock::VerifyAndClearExpectations(&observer); // We should get a notification for a shorter delay. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), start_time + delay1s)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay1s); Mock::VerifyAndClearExpectations(&observer); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = runners_[0]->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); Mock::VerifyAndClearExpectations(&observer); // When a queue has been enabled, we may get a notification if the // TimeDomain's next scheduled wake-up has changed. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), start_time + delay1s)); voter->SetQueueEnabled(true); Mock::VerifyAndClearExpectations(&observer); // Tidy up. runners_[0]->UnregisterTaskQueue(); } TEST_F(TaskQueueManagerTest, TaskQueueObserver_DelayedTaskMultipleQueues) { Initialize(2u); MockTaskQueueObserver observer; runners_[0]->SetObserver(&observer); runners_[1]->SetObserver(&observer); base::TimeTicks start_time = manager_->Delegate()->NowTicks(); base::TimeDelta delay1s(base::TimeDelta::FromSeconds(1)); base::TimeDelta delay10s(base::TimeDelta::FromSeconds(10)); EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), start_time + delay1s)) .Times(1); EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[1].get(), start_time + delay10s)) .Times(1); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay1s); runners_[1]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay10s); ::testing::Mock::VerifyAndClearExpectations(&observer); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter0 = runners_[0]->CreateQueueEnabledVoter(); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter1 = runners_[1]->CreateQueueEnabledVoter(); // Disabling a queue should not trigger a notification. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0); voter0->SetQueueEnabled(false); Mock::VerifyAndClearExpectations(&observer); // Re-enabling it should should also trigger a notification. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), start_time + delay1s)); voter0->SetQueueEnabled(true); Mock::VerifyAndClearExpectations(&observer); // Disabling a queue should not trigger a notification. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0); voter1->SetQueueEnabled(false); Mock::VerifyAndClearExpectations(&observer); // Re-enabling it should should trigger a notification. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[1].get(), start_time + delay10s)); voter1->SetQueueEnabled(true); Mock::VerifyAndClearExpectations(&observer); // Tidy up. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(AnyNumber()); runners_[0]->UnregisterTaskQueue(); runners_[1]->UnregisterTaskQueue(); } TEST_F(TaskQueueManagerTest, TaskQueueObserver_DelayedWorkWhichCanRunNow) { // This test checks that when delayed work becomes available // the notification still fires. This usually happens when time advances // and task becomes available in the middle of the scheduling code. // For this test we rely on the fact that notification dispatching code // is the same in all conditions and just change a time domain to // trigger notification. Initialize(1u); base::TimeDelta delay1s(base::TimeDelta::FromSeconds(1)); base::TimeDelta delay10s(base::TimeDelta::FromSeconds(10)); MockTaskQueueObserver observer; runners_[0]->SetObserver(&observer); // We should get a notification when a delayed task is posted on an empty // queue. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay1s); Mock::VerifyAndClearExpectations(&observer); std::unique_ptr<TimeDomain> mock_time_domain = base::MakeUnique<RealTimeDomain>(); manager_->RegisterTimeDomain(mock_time_domain.get()); now_src_->Advance(delay10s); EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)); runners_[0]->SetTimeDomain(mock_time_domain.get()); Mock::VerifyAndClearExpectations(&observer); // Tidy up. runners_[0]->UnregisterTaskQueue(); } class CancelableTask { public: explicit CancelableTask(base::TickClock* clock) : clock_(clock), weak_factory_(this) {} void RecordTimeTask(std::vector<base::TimeTicks>* run_times) { run_times->push_back(clock_->NowTicks()); } base::TickClock* clock_; base::WeakPtrFactory<CancelableTask> weak_factory_; }; TEST_F(TaskQueueManagerTest, TaskQueueObserver_SweepCanceledDelayedTasks) { Initialize(1u); MockTaskQueueObserver observer; runners_[0]->SetObserver(&observer); base::TimeTicks start_time = manager_->Delegate()->NowTicks(); base::TimeDelta delay1(base::TimeDelta::FromSeconds(5)); base::TimeDelta delay2(base::TimeDelta::FromSeconds(10)); EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), start_time + delay1)) .Times(1); CancelableTask task1(now_src_.get()); CancelableTask task2(now_src_.get()); std::vector<base::TimeTicks> run_times; runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task1.weak_factory_.GetWeakPtr(), &run_times), delay1); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task2.weak_factory_.GetWeakPtr(), &run_times), delay2); task1.weak_factory_.InvalidateWeakPtrs(); // Sweeping away canceled delayed tasks should trigger a notification. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), start_time + delay2)) .Times(1); manager_->SweepCanceledDelayedTasks(); } namespace { void ChromiumRunloopInspectionTask( scoped_refptr<cc::OrderedSimpleTaskRunner> test_task_runner) { EXPECT_EQ(1u, test_task_runner->NumPendingTasks()); } } // namespace TEST_F(TaskQueueManagerTest, NumberOfPendingTasksOnChromiumRunLoop) { Initialize(1u); // NOTE because tasks posted to the chromiumrun loop are not cancellable, we // will end up with a lot more tasks posted if the delayed tasks were posted // in the reverse order. // TODO(alexclarke): Consider talking to the message pump directly. test_task_runner_->SetAutoAdvanceNowToPendingTasks(true); for (int i = 1; i < 100; i++) { runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&ChromiumRunloopInspectionTask, test_task_runner_), base::TimeDelta::FromMilliseconds(i)); } test_task_runner_->RunUntilIdle(); } namespace { class QuadraticTask { public: QuadraticTask(scoped_refptr<TaskQueue> task_queue, base::TimeDelta delay, base::SimpleTestTickClock* now_src) : count_(0), task_queue_(task_queue), delay_(delay), now_src_(now_src) {} void SetShouldExit(base::Callback<bool()> should_exit) { should_exit_ = should_exit; } void Run() { if (should_exit_.Run()) return; count_++; task_queue_->PostDelayedTask( FROM_HERE, base::Bind(&QuadraticTask::Run, base::Unretained(this)), delay_); task_queue_->PostDelayedTask( FROM_HERE, base::Bind(&QuadraticTask::Run, base::Unretained(this)), delay_); now_src_->Advance(base::TimeDelta::FromMilliseconds(5)); } int Count() const { return count_; } private: int count_; scoped_refptr<TaskQueue> task_queue_; base::TimeDelta delay_; base::Callback<bool()> should_exit_; base::SimpleTestTickClock* now_src_; }; class LinearTask { public: LinearTask(scoped_refptr<TaskQueue> task_queue, base::TimeDelta delay, base::SimpleTestTickClock* now_src) : count_(0), task_queue_(task_queue), delay_(delay), now_src_(now_src) {} void SetShouldExit(base::Callback<bool()> should_exit) { should_exit_ = should_exit; } void Run() { if (should_exit_.Run()) return; count_++; task_queue_->PostDelayedTask( FROM_HERE, base::Bind(&LinearTask::Run, base::Unretained(this)), delay_); now_src_->Advance(base::TimeDelta::FromMilliseconds(5)); } int Count() const { return count_; } private: int count_; scoped_refptr<TaskQueue> task_queue_; base::TimeDelta delay_; base::Callback<bool()> should_exit_; base::SimpleTestTickClock* now_src_; }; bool ShouldExit(QuadraticTask* quadratic_task, LinearTask* linear_task) { return quadratic_task->Count() == 1000 || linear_task->Count() == 1000; } } // namespace TEST_F(TaskQueueManagerTest, DelayedTasksDontBadlyStarveNonDelayedWork_SameQueue) { Initialize(1u); QuadraticTask quadratic_delayed_task( runners_[0], base::TimeDelta::FromMilliseconds(10), now_src_.get()); LinearTask linear_immediate_task(runners_[0], base::TimeDelta(), now_src_.get()); base::Callback<bool()> should_exit = base::Bind(ShouldExit, &quadratic_delayed_task, &linear_immediate_task); quadratic_delayed_task.SetShouldExit(should_exit); linear_immediate_task.SetShouldExit(should_exit); quadratic_delayed_task.Run(); linear_immediate_task.Run(); test_task_runner_->SetAutoAdvanceNowToPendingTasks(true); test_task_runner_->RunUntilIdle(); double ratio = static_cast<double>(linear_immediate_task.Count()) / static_cast<double>(quadratic_delayed_task.Count()); EXPECT_GT(ratio, 0.333); EXPECT_LT(ratio, 1.1); } TEST_F(TaskQueueManagerTest, ImmediateWorkCanStarveDelayedTasks_SameQueue) { Initialize(1u); QuadraticTask quadratic_immediate_task(runners_[0], base::TimeDelta(), now_src_.get()); LinearTask linear_delayed_task( runners_[0], base::TimeDelta::FromMilliseconds(10), now_src_.get()); base::Callback<bool()> should_exit = base::Bind(&ShouldExit, &quadratic_immediate_task, &linear_delayed_task); quadratic_immediate_task.SetShouldExit(should_exit); linear_delayed_task.SetShouldExit(should_exit); quadratic_immediate_task.Run(); linear_delayed_task.Run(); test_task_runner_->SetAutoAdvanceNowToPendingTasks(true); test_task_runner_->RunUntilIdle(); double ratio = static_cast<double>(linear_delayed_task.Count()) / static_cast<double>(quadratic_immediate_task.Count()); // This is by design, we want to enforce a strict ordering in task execution // where by delayed tasks can not skip ahead of non-delayed work. EXPECT_GT(ratio, 0.0); EXPECT_LT(ratio, 0.1); } TEST_F(TaskQueueManagerTest, DelayedTasksDontBadlyStarveNonDelayedWork_DifferentQueue) { Initialize(2u); QuadraticTask quadratic_delayed_task( runners_[0], base::TimeDelta::FromMilliseconds(10), now_src_.get()); LinearTask linear_immediate_task(runners_[1], base::TimeDelta(), now_src_.get()); base::Callback<bool()> should_exit = base::Bind(ShouldExit, &quadratic_delayed_task, &linear_immediate_task); quadratic_delayed_task.SetShouldExit(should_exit); linear_immediate_task.SetShouldExit(should_exit); quadratic_delayed_task.Run(); linear_immediate_task.Run(); test_task_runner_->SetAutoAdvanceNowToPendingTasks(true); test_task_runner_->RunUntilIdle(); double ratio = static_cast<double>(linear_immediate_task.Count()) / static_cast<double>(quadratic_delayed_task.Count()); EXPECT_GT(ratio, 0.333); EXPECT_LT(ratio, 1.1); } TEST_F(TaskQueueManagerTest, ImmediateWorkCanStarveDelayedTasks_DifferentQueue) { Initialize(2u); QuadraticTask quadratic_immediate_task(runners_[0], base::TimeDelta(), now_src_.get()); LinearTask linear_delayed_task( runners_[1], base::TimeDelta::FromMilliseconds(10), now_src_.get()); base::Callback<bool()> should_exit = base::Bind(&ShouldExit, &quadratic_immediate_task, &linear_delayed_task); quadratic_immediate_task.SetShouldExit(should_exit); linear_delayed_task.SetShouldExit(should_exit); quadratic_immediate_task.Run(); linear_delayed_task.Run(); test_task_runner_->SetAutoAdvanceNowToPendingTasks(true); test_task_runner_->RunUntilIdle(); double ratio = static_cast<double>(linear_delayed_task.Count()) / static_cast<double>(quadratic_immediate_task.Count()); // This is by design, we want to enforce a strict ordering in task execution // where by delayed tasks can not skip ahead of non-delayed work. EXPECT_GT(ratio, 0.0); EXPECT_LT(ratio, 0.1); } TEST_F(TaskQueueManagerTest, CurrentlyExecutingTaskQueue_NoTaskRunning) { Initialize(1u); EXPECT_EQ(nullptr, manager_->currently_executing_task_queue()); } namespace { void CurrentlyExecutingTaskQueueTestTask( TaskQueueManager* task_queue_manager, std::vector<internal::TaskQueueImpl*>* task_sources) { task_sources->push_back(task_queue_manager->currently_executing_task_queue()); } } TEST_F(TaskQueueManagerTest, CurrentlyExecutingTaskQueue_TaskRunning) { Initialize(2u); TestTaskQueue* queue0 = runners_[0].get(); TestTaskQueue* queue1 = runners_[1].get(); std::vector<internal::TaskQueueImpl*> task_sources; queue0->PostTask(FROM_HERE, base::Bind(&CurrentlyExecutingTaskQueueTestTask, manager_.get(), &task_sources)); queue1->PostTask(FROM_HERE, base::Bind(&CurrentlyExecutingTaskQueueTestTask, manager_.get(), &task_sources)); test_task_runner_->RunUntilIdle(); EXPECT_THAT(task_sources, ElementsAre(queue0->GetTaskQueueImpl(), queue1->GetTaskQueueImpl())); EXPECT_EQ(nullptr, manager_->currently_executing_task_queue()); } namespace { void RunloopCurrentlyExecutingTaskQueueTestTask( base::MessageLoop* message_loop, TaskQueueManager* task_queue_manager, std::vector<internal::TaskQueueImpl*>* task_sources, std::vector<std::pair<base::Closure, TestTaskQueue*>>* tasks) { base::MessageLoop::ScopedNestableTaskAllower allow(message_loop); task_sources->push_back(task_queue_manager->currently_executing_task_queue()); for (std::pair<base::Closure, TestTaskQueue*>& pair : *tasks) { pair.second->PostTask(FROM_HERE, pair.first); } base::RunLoop().RunUntilIdle(); task_sources->push_back(task_queue_manager->currently_executing_task_queue()); } } TEST_F(TaskQueueManagerTest, CurrentlyExecutingTaskQueue_NestedLoop) { InitializeWithRealMessageLoop(3u); TestTaskQueue* queue0 = runners_[0].get(); TestTaskQueue* queue1 = runners_[1].get(); TestTaskQueue* queue2 = runners_[2].get(); std::vector<internal::TaskQueueImpl*> task_sources; std::vector<std::pair<base::Closure, TestTaskQueue*>> tasks_to_post_from_nested_loop; tasks_to_post_from_nested_loop.push_back( std::make_pair(base::Bind(&CurrentlyExecutingTaskQueueTestTask, manager_.get(), &task_sources), queue1)); tasks_to_post_from_nested_loop.push_back( std::make_pair(base::Bind(&CurrentlyExecutingTaskQueueTestTask, manager_.get(), &task_sources), queue2)); queue0->PostTask( FROM_HERE, base::Bind(&RunloopCurrentlyExecutingTaskQueueTestTask, message_loop_.get(), manager_.get(), &task_sources, &tasks_to_post_from_nested_loop)); base::RunLoop().RunUntilIdle(); EXPECT_THAT( task_sources, ElementsAre(queue0->GetTaskQueueImpl(), queue1->GetTaskQueueImpl(), queue2->GetTaskQueueImpl(), queue0->GetTaskQueueImpl())); EXPECT_EQ(nullptr, manager_->currently_executing_task_queue()); } void OnTraceDataCollected(base::Closure quit_closure, base::trace_event::TraceResultBuffer* buffer, const scoped_refptr<base::RefCountedString>& json, bool has_more_events) { buffer->AddFragment(json->data()); if (!has_more_events) quit_closure.Run(); } class TaskQueueManagerTestWithTracing : public TaskQueueManagerTest { public: void StartTracing(); void StopTracing(); std::unique_ptr<trace_analyzer::TraceAnalyzer> CreateTraceAnalyzer(); }; void TaskQueueManagerTestWithTracing::StartTracing() { base::trace_event::TraceLog::GetInstance()->SetEnabled( base::trace_event::TraceConfig("*"), base::trace_event::TraceLog::RECORDING_MODE); } void TaskQueueManagerTestWithTracing::StopTracing() { base::trace_event::TraceLog::GetInstance()->SetDisabled(); } std::unique_ptr<trace_analyzer::TraceAnalyzer> TaskQueueManagerTestWithTracing::CreateTraceAnalyzer() { base::trace_event::TraceResultBuffer buffer; base::trace_event::TraceResultBuffer::SimpleOutput trace_output; buffer.SetOutputCallback(trace_output.GetCallback()); base::RunLoop run_loop; buffer.Start(); base::trace_event::TraceLog::GetInstance()->Flush( Bind(&OnTraceDataCollected, run_loop.QuitClosure(), base::Unretained(&buffer))); run_loop.Run(); buffer.Finish(); return base::WrapUnique( trace_analyzer::TraceAnalyzer::Create(trace_output.json_output)); } TEST_F(TaskQueueManagerTestWithTracing, BlameContextAttribution) { using trace_analyzer::Query; InitializeWithRealMessageLoop(1u); TestTaskQueue* queue = runners_[0].get(); StartTracing(); { base::trace_event::BlameContext blame_context("cat", "name", "type", "scope", 0, nullptr); blame_context.Initialize(); queue->SetBlameContext(&blame_context); queue->PostTask(FROM_HERE, base::Bind(&NopTask)); base::RunLoop().RunUntilIdle(); } StopTracing(); std::unique_ptr<trace_analyzer::TraceAnalyzer> analyzer = CreateTraceAnalyzer(); trace_analyzer::TraceEventVector events; Query q = Query::EventPhaseIs(TRACE_EVENT_PHASE_ENTER_CONTEXT) || Query::EventPhaseIs(TRACE_EVENT_PHASE_LEAVE_CONTEXT); analyzer->FindEvents(q, &events); EXPECT_EQ(2u, events.size()); } TEST_F(TaskQueueManagerTest, NoWakeUpsForCanceledDelayedTasks) { Initialize(1u); base::TimeTicks start_time = manager_->Delegate()->NowTicks(); CancelableTask task1(now_src_.get()); CancelableTask task2(now_src_.get()); CancelableTask task3(now_src_.get()); CancelableTask task4(now_src_.get()); base::TimeDelta delay1(base::TimeDelta::FromSeconds(5)); base::TimeDelta delay2(base::TimeDelta::FromSeconds(10)); base::TimeDelta delay3(base::TimeDelta::FromSeconds(15)); base::TimeDelta delay4(base::TimeDelta::FromSeconds(30)); std::vector<base::TimeTicks> run_times; runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task1.weak_factory_.GetWeakPtr(), &run_times), delay1); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task2.weak_factory_.GetWeakPtr(), &run_times), delay2); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task3.weak_factory_.GetWeakPtr(), &run_times), delay3); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task4.weak_factory_.GetWeakPtr(), &run_times), delay4); task2.weak_factory_.InvalidateWeakPtrs(); task3.weak_factory_.InvalidateWeakPtrs(); std::set<base::TimeTicks> wake_up_times; RunUntilIdle(base::Bind( [](std::set<base::TimeTicks>* wake_up_times, base::SimpleTestTickClock* clock) { wake_up_times->insert(clock->NowTicks()); }, &wake_up_times, now_src_.get())); EXPECT_THAT(wake_up_times, ElementsAre(start_time + delay1, start_time + delay4)); EXPECT_THAT(run_times, ElementsAre(start_time + delay1, start_time + delay4)); } TEST_F(TaskQueueManagerTest, NoWakeUpsForCanceledDelayedTasksReversePostOrder) { Initialize(1u); base::TimeTicks start_time = manager_->Delegate()->NowTicks(); CancelableTask task1(now_src_.get()); CancelableTask task2(now_src_.get()); CancelableTask task3(now_src_.get()); CancelableTask task4(now_src_.get()); base::TimeDelta delay1(base::TimeDelta::FromSeconds(5)); base::TimeDelta delay2(base::TimeDelta::FromSeconds(10)); base::TimeDelta delay3(base::TimeDelta::FromSeconds(15)); base::TimeDelta delay4(base::TimeDelta::FromSeconds(30)); std::vector<base::TimeTicks> run_times; runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task4.weak_factory_.GetWeakPtr(), &run_times), delay4); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task3.weak_factory_.GetWeakPtr(), &run_times), delay3); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task2.weak_factory_.GetWeakPtr(), &run_times), delay2); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task1.weak_factory_.GetWeakPtr(), &run_times), delay1); task2.weak_factory_.InvalidateWeakPtrs(); task3.weak_factory_.InvalidateWeakPtrs(); std::set<base::TimeTicks> wake_up_times; RunUntilIdle(base::Bind( [](std::set<base::TimeTicks>* wake_up_times, base::SimpleTestTickClock* clock) { wake_up_times->insert(clock->NowTicks()); }, &wake_up_times, now_src_.get())); EXPECT_THAT(wake_up_times, ElementsAre(start_time + delay1, start_time + delay4)); EXPECT_THAT(run_times, ElementsAre(start_time + delay1, start_time + delay4)); } TEST_F(TaskQueueManagerTest, TimeDomainWakeUpOnlyCancelledIfAllUsesCancelled) { Initialize(1u); base::TimeTicks start_time = manager_->Delegate()->NowTicks(); CancelableTask task1(now_src_.get()); CancelableTask task2(now_src_.get()); CancelableTask task3(now_src_.get()); CancelableTask task4(now_src_.get()); base::TimeDelta delay1(base::TimeDelta::FromSeconds(5)); base::TimeDelta delay2(base::TimeDelta::FromSeconds(10)); base::TimeDelta delay3(base::TimeDelta::FromSeconds(15)); base::TimeDelta delay4(base::TimeDelta::FromSeconds(30)); std::vector<base::TimeTicks> run_times; runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task1.weak_factory_.GetWeakPtr(), &run_times), delay1); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task2.weak_factory_.GetWeakPtr(), &run_times), delay2); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task3.weak_factory_.GetWeakPtr(), &run_times), delay3); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task4.weak_factory_.GetWeakPtr(), &run_times), delay4); // Post a non-canceled task with |delay3|. So we should still get a wake-up at // |delay3| even though we cancel |task3|. runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, base::Unretained(&task3), &run_times), delay3); task2.weak_factory_.InvalidateWeakPtrs(); task3.weak_factory_.InvalidateWeakPtrs(); task1.weak_factory_.InvalidateWeakPtrs(); std::set<base::TimeTicks> wake_up_times; RunUntilIdle(base::Bind( [](std::set<base::TimeTicks>* wake_up_times, base::SimpleTestTickClock* clock) { wake_up_times->insert(clock->NowTicks()); }, &wake_up_times, now_src_.get())); EXPECT_THAT(wake_up_times, ElementsAre(start_time + delay1, start_time + delay3, start_time + delay4)); EXPECT_THAT(run_times, ElementsAre(start_time + delay3, start_time + delay4)); } TEST_F(TaskQueueManagerTest, TaskQueueVoters) { Initialize(1u); // The task queue should be initially enabled. EXPECT_TRUE(runners_[0]->IsQueueEnabled()); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter1 = runners_[0]->CreateQueueEnabledVoter(); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter2 = runners_[0]->CreateQueueEnabledVoter(); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter3 = runners_[0]->CreateQueueEnabledVoter(); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter4 = runners_[0]->CreateQueueEnabledVoter(); // Voters should initially vote for the queue to be enabled. EXPECT_TRUE(runners_[0]->IsQueueEnabled()); // If any voter wants to disable, the queue is disabled. voter1->SetQueueEnabled(false); EXPECT_FALSE(runners_[0]->IsQueueEnabled()); // If the voter is deleted then the queue should be re-enabled. voter1.reset(); EXPECT_TRUE(runners_[0]->IsQueueEnabled()); // If any of the remaining voters wants to disable, the queue should be // disabled. voter2->SetQueueEnabled(false); EXPECT_FALSE(runners_[0]->IsQueueEnabled()); // If another queue votes to disable, nothing happens because it's already // disabled. voter3->SetQueueEnabled(false); EXPECT_FALSE(runners_[0]->IsQueueEnabled()); // There are two votes to disable, so one of them voting to enable does // nothing. voter2->SetQueueEnabled(true); EXPECT_FALSE(runners_[0]->IsQueueEnabled()); // IF all queues vote to enable then the queue is enabled. voter3->SetQueueEnabled(true); EXPECT_TRUE(runners_[0]->IsQueueEnabled()); } TEST_F(TaskQueueManagerTest, UnregisterQueueBeforeEnabledVoterDeleted) { Initialize(1u); scoped_refptr<TaskQueue> queue = CreateTaskQueue(); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = queue->CreateQueueEnabledVoter(); voter->SetQueueEnabled(true); // NOP queue->UnregisterTaskQueue(); // This should complete without DCHECKing. voter.reset(); } TEST_F(TaskQueueManagerTest, UnregisterQueueBeforeDisabledVoterDeleted) { Initialize(1u); scoped_refptr<TaskQueue> queue = CreateTaskQueue(); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = queue->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); queue->UnregisterTaskQueue(); // This should complete without DCHECKing. voter.reset(); } TEST_F(TaskQueueManagerTest, SweepCanceledDelayedTasks) { Initialize(1u); CancelableTask task1(now_src_.get()); CancelableTask task2(now_src_.get()); CancelableTask task3(now_src_.get()); CancelableTask task4(now_src_.get()); base::TimeDelta delay1(base::TimeDelta::FromSeconds(5)); base::TimeDelta delay2(base::TimeDelta::FromSeconds(10)); base::TimeDelta delay3(base::TimeDelta::FromSeconds(15)); base::TimeDelta delay4(base::TimeDelta::FromSeconds(30)); std::vector<base::TimeTicks> run_times; runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task1.weak_factory_.GetWeakPtr(), &run_times), delay1); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task2.weak_factory_.GetWeakPtr(), &run_times), delay2); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task3.weak_factory_.GetWeakPtr(), &run_times), delay3); runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&CancelableTask::RecordTimeTask, task4.weak_factory_.GetWeakPtr(), &run_times), delay4); EXPECT_EQ(4u, runners_[0]->GetNumberOfPendingTasks()); task2.weak_factory_.InvalidateWeakPtrs(); task3.weak_factory_.InvalidateWeakPtrs(); EXPECT_EQ(4u, runners_[0]->GetNumberOfPendingTasks()); manager_->SweepCanceledDelayedTasks(); EXPECT_EQ(2u, runners_[0]->GetNumberOfPendingTasks()); task1.weak_factory_.InvalidateWeakPtrs(); task4.weak_factory_.InvalidateWeakPtrs(); manager_->SweepCanceledDelayedTasks(); EXPECT_EQ(0u, runners_[0]->GetNumberOfPendingTasks()); } TEST_F(TaskQueueManagerTest, ComputeDelayTillNextTask) { Initialize(2u); LazyNow lazy_now(now_src_.get()); EXPECT_FALSE(static_cast<bool>(ComputeDelayTillNextTask(&lazy_now))); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromSeconds(10)); EXPECT_EQ(base::TimeDelta::FromSeconds(10), ComputeDelayTillNextTask(&lazy_now)->Delay()); runners_[1]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromSeconds(15)); EXPECT_EQ(base::TimeDelta::FromSeconds(10), ComputeDelayTillNextTask(&lazy_now)->Delay()); runners_[1]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromSeconds(5)); EXPECT_EQ(base::TimeDelta::FromSeconds(5), ComputeDelayTillNextTask(&lazy_now)->Delay()); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); EXPECT_EQ(base::TimeDelta(), ComputeDelayTillNextTask(&lazy_now)->Delay()); } TEST_F(TaskQueueManagerTest, ComputeDelayTillNextTask_Disabled) { Initialize(1u); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = runners_[0]->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); LazyNow lazy_now(now_src_.get()); EXPECT_FALSE(ComputeDelayTillNextTask(&lazy_now)); } TEST_F(TaskQueueManagerTest, ComputeDelayTillNextTask_Fence) { Initialize(1u); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); LazyNow lazy_now(now_src_.get()); EXPECT_FALSE(ComputeDelayTillNextTask(&lazy_now)); } TEST_F(TaskQueueManagerTest, ComputeDelayTillNextTask_FenceUnblocking) { Initialize(1u); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); LazyNow lazy_now(now_src_.get()); EXPECT_EQ(base::TimeDelta(), ComputeDelayTillNextTask(&lazy_now)->Delay()); } TEST_F(TaskQueueManagerTest, ComputeDelayTillNextTask_DelayedTaskReady) { Initialize(1u); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromSeconds(1)); now_src_->Advance(base::TimeDelta::FromSeconds(10)); LazyNow lazy_now(now_src_.get()); EXPECT_EQ(base::TimeDelta(), ComputeDelayTillNextTask(&lazy_now)->Delay()); } TEST_F(TaskQueueManagerTest, PostDoWorkContinuation_NoMoreWork) { Initialize(1u); LazyNow lazy_now(now_src_.get()); PostDoWorkContinuation(base::Optional<NextTaskDelay>(), &lazy_now); EXPECT_EQ(0u, test_task_runner_->NumPendingTasks()); EXPECT_EQ(0, immediate_do_work_posted_count()); EXPECT_TRUE(next_delayed_do_work_time().is_null()); } TEST_F(TaskQueueManagerTest, PostDoWorkContinuation_ImmediateWork) { Initialize(1u); LazyNow lazy_now(now_src_.get()); PostDoWorkContinuation(NextTaskDelay(), &lazy_now); EXPECT_EQ(1u, test_task_runner_->NumPendingTasks()); EXPECT_EQ(base::TimeDelta(), test_task_runner_->DelayToNextTaskTime()); EXPECT_EQ(1, immediate_do_work_posted_count()); EXPECT_TRUE(next_delayed_do_work_time().is_null()); } TEST_F(TaskQueueManagerTest, PostDoWorkContinuation_DelayedWorkInThePast) { Initialize(1u); LazyNow lazy_now(now_src_.get()); // Note this isn't supposed to happen in practice. PostDoWorkContinuation( NextTaskDelay(base::TimeDelta::FromSeconds(-1), runners_[0]->GetTimeDomain(), NextTaskDelay::AllowAnyDelayForTesting()), &lazy_now); EXPECT_EQ(1u, test_task_runner_->NumPendingTasks()); EXPECT_EQ(base::TimeDelta(), test_task_runner_->DelayToNextTaskTime()); EXPECT_EQ(1, immediate_do_work_posted_count()); EXPECT_TRUE(next_delayed_do_work_time().is_null()); } TEST_F(TaskQueueManagerTest, PostDoWorkContinuation_DelayedWork) { Initialize(1u); LazyNow lazy_now(now_src_.get()); PostDoWorkContinuation(NextTaskDelay(base::TimeDelta::FromSeconds(1), runners_[0]->GetTimeDomain()), &lazy_now); EXPECT_EQ(1u, test_task_runner_->NumPendingTasks()); EXPECT_EQ(base::TimeDelta::FromSeconds(1), test_task_runner_->DelayToNextTaskTime()); EXPECT_EQ(0, immediate_do_work_posted_count()); EXPECT_EQ(lazy_now.Now() + base::TimeDelta::FromSeconds(1), next_delayed_do_work_time()); } TEST_F(TaskQueueManagerTest, PostDoWorkContinuation_DelayedWorkButImmediateDoWorkAlreadyPosted) { Initialize(1u); MaybeScheduleImmediateWorkLocked(FROM_HERE); EXPECT_EQ(1u, test_task_runner_->NumPendingTasks()); EXPECT_EQ(base::TimeDelta(), test_task_runner_->DelayToNextTaskTime()); EXPECT_EQ(1, immediate_do_work_posted_count()); LazyNow lazy_now(now_src_.get()); PostDoWorkContinuation(NextTaskDelay(base::TimeDelta::FromSeconds(1), runners_[0]->GetTimeDomain()), &lazy_now); // Test that a delayed task didn't get posted. EXPECT_EQ(1u, test_task_runner_->NumPendingTasks()); EXPECT_EQ(base::TimeDelta(), test_task_runner_->DelayToNextTaskTime()); EXPECT_EQ(1, immediate_do_work_posted_count()); EXPECT_TRUE(next_delayed_do_work_time().is_null()); } TEST_F(TaskQueueManagerTest, PostDoWorkContinuation_DelayedWorkTimeChanges) { Initialize(1u); LazyNow lazy_now(now_src_.get()); PostDoWorkContinuation(NextTaskDelay(base::TimeDelta::FromSeconds(1), runners_[0]->GetTimeDomain()), &lazy_now); EXPECT_TRUE(test_task_runner_->HasPendingTasks()); EXPECT_EQ(0, immediate_do_work_posted_count()); EXPECT_EQ(base::TimeDelta::FromSeconds(1), test_task_runner_->DelayToNextTaskTime()); EXPECT_EQ(lazy_now.Now() + base::TimeDelta::FromSeconds(1), next_delayed_do_work_time()); PostDoWorkContinuation(NextTaskDelay(base::TimeDelta::FromSeconds(10), runners_[0]->GetTimeDomain()), &lazy_now); // This should have resulted in the previous task getting canceled and a new // one getting posted. EXPECT_EQ(2u, test_task_runner_->NumPendingTasks()); test_task_runner_->RemoveCancelledTasks(); EXPECT_EQ(1u, test_task_runner_->NumPendingTasks()); EXPECT_EQ(base::TimeDelta::FromSeconds(10), test_task_runner_->DelayToNextTaskTime()); EXPECT_EQ(0, immediate_do_work_posted_count()); EXPECT_EQ(lazy_now.Now() + base::TimeDelta::FromSeconds(10), next_delayed_do_work_time()); } TEST_F(TaskQueueManagerTest, PostDoWorkContinuation_ImmediateWorkButDelayedDoWorkPending) { Initialize(1u); LazyNow lazy_now(now_src_.get()); PostDoWorkContinuation(NextTaskDelay(base::TimeDelta::FromSeconds(1), runners_[0]->GetTimeDomain()), &lazy_now); now_src_->Advance(base::TimeDelta::FromSeconds(1)); lazy_now = LazyNow(now_src_.get()); PostDoWorkContinuation(NextTaskDelay(), &lazy_now); // Because the delayed DoWork was pending we don't expect an immediate DoWork // to get posted. EXPECT_EQ(1u, test_task_runner_->NumPendingTasks()); EXPECT_EQ(base::TimeDelta(), test_task_runner_->DelayToNextTaskTime()); EXPECT_EQ(0, immediate_do_work_posted_count()); EXPECT_EQ(lazy_now.Now(), next_delayed_do_work_time()); } namespace { void MessageLoopTaskWithDelayedQuit(base::MessageLoop* message_loop, base::SimpleTestTickClock* now_src, scoped_refptr<TaskQueue> task_queue) { base::MessageLoop::ScopedNestableTaskAllower allow(message_loop); base::RunLoop run_loop; task_queue->PostDelayedTask(FROM_HERE, run_loop.QuitClosure(), base::TimeDelta::FromMilliseconds(100)); now_src->Advance(base::TimeDelta::FromMilliseconds(200)); run_loop.Run(); } } // namespace TEST_F(TaskQueueManagerTest, DelayedTaskRunsInNestedMessageLoop) { InitializeWithRealMessageLoop(1u); base::RunLoop run_loop; runners_[0]->PostTask( FROM_HERE, base::Bind(&MessageLoopTaskWithDelayedQuit, message_loop_.get(), now_src_.get(), base::RetainedRef(runners_[0]))); run_loop.RunUntilIdle(); } namespace { void MessageLoopTaskWithImmediateQuit(base::MessageLoop* message_loop, base::Closure non_nested_quit_closure, scoped_refptr<TaskQueue> task_queue) { base::MessageLoop::ScopedNestableTaskAllower allow(message_loop); base::RunLoop run_loop; // Needed because entering the nested run loop causes a DoWork to get // posted. task_queue->PostTask(FROM_HERE, base::Bind(&NopTask)); task_queue->PostTask(FROM_HERE, run_loop.QuitClosure()); run_loop.Run(); non_nested_quit_closure.Run(); } } // namespace TEST_F(TaskQueueManagerTest, DelayedNestedMessageLoopDoesntPreventTasksRunning) { InitializeWithRealMessageLoop(1u); base::RunLoop run_loop; runners_[0]->PostDelayedTask( FROM_HERE, base::Bind(&MessageLoopTaskWithImmediateQuit, message_loop_.get(), run_loop.QuitClosure(), base::RetainedRef(runners_[0])), base::TimeDelta::FromMilliseconds(100)); now_src_->Advance(base::TimeDelta::FromMilliseconds(200)); run_loop.Run(); } TEST_F(TaskQueueManagerTest, CouldTaskRun_DisableAndReenable) { Initialize(1u); EnqueueOrder enqueue_order = GetNextSequenceNumber(); EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order)); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = runners_[0]->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); EXPECT_FALSE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order)); voter->SetQueueEnabled(true); EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order)); } TEST_F(TaskQueueManagerTest, CouldTaskRun_Fence) { Initialize(1u); EnqueueOrder enqueue_order = GetNextSequenceNumber(); EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order)); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order)); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::BEGINNING_OF_TIME); EXPECT_FALSE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order)); runners_[0]->RemoveFence(); EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order)); } TEST_F(TaskQueueManagerTest, CouldTaskRun_FenceBeforeThenAfter) { Initialize(1u); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); EnqueueOrder enqueue_order = GetNextSequenceNumber(); EXPECT_FALSE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order)); runners_[0]->InsertFence(TaskQueue::InsertFencePosition::NOW); EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order)); } TEST_F(TaskQueueManagerTest, DelayedDoWorkNotPostedForDisabledQueue) { Initialize(1u); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromMilliseconds(1)); ASSERT_TRUE(test_task_runner_->HasPendingTasks()); EXPECT_EQ(base::TimeDelta::FromMilliseconds(1), test_task_runner_->DelayToNextTaskTime()); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = runners_[0]->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); EXPECT_TRUE(test_task_runner_->HasPendingTasks()); test_task_runner_->RemoveCancelledTasks(); EXPECT_FALSE(test_task_runner_->HasPendingTasks()); voter->SetQueueEnabled(true); ASSERT_TRUE(test_task_runner_->HasPendingTasks()); EXPECT_EQ(base::TimeDelta::FromMilliseconds(1), test_task_runner_->DelayToNextTaskTime()); } TEST_F(TaskQueueManagerTest, DisablingQueuesChangesDelayTillNextDoWork) { Initialize(3u); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromMilliseconds(1)); runners_[1]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromMilliseconds(10)); runners_[2]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromMilliseconds(100)); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter0 = runners_[0]->CreateQueueEnabledVoter(); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter1 = runners_[1]->CreateQueueEnabledVoter(); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter2 = runners_[2]->CreateQueueEnabledVoter(); ASSERT_TRUE(test_task_runner_->HasPendingTasks()); EXPECT_EQ(base::TimeDelta::FromMilliseconds(1), test_task_runner_->DelayToNextTaskTime()); voter0->SetQueueEnabled(false); test_task_runner_->RemoveCancelledTasks(); ASSERT_TRUE(test_task_runner_->HasPendingTasks()); EXPECT_EQ(base::TimeDelta::FromMilliseconds(10), test_task_runner_->DelayToNextTaskTime()); voter1->SetQueueEnabled(false); test_task_runner_->RemoveCancelledTasks(); ASSERT_TRUE(test_task_runner_->HasPendingTasks()); EXPECT_EQ(base::TimeDelta::FromMilliseconds(100), test_task_runner_->DelayToNextTaskTime()); voter2->SetQueueEnabled(false); test_task_runner_->RemoveCancelledTasks(); EXPECT_FALSE(test_task_runner_->HasPendingTasks()); } TEST_F(TaskQueueManagerTest, GetNextScheduledWakeUp) { Initialize(1u); EXPECT_EQ(base::nullopt, runners_[0]->GetNextScheduledWakeUp()); base::TimeTicks start_time = manager_->Delegate()->NowTicks(); base::TimeDelta delay1 = base::TimeDelta::FromMilliseconds(10); base::TimeDelta delay2 = base::TimeDelta::FromMilliseconds(2); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay1); EXPECT_EQ(start_time + delay1, runners_[0]->GetNextScheduledWakeUp()); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay2); EXPECT_EQ(start_time + delay2, runners_[0]->GetNextScheduledWakeUp()); // We don't have wake-ups scheduled for disabled queues. std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = runners_[0]->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); EXPECT_EQ(base::nullopt, runners_[0]->GetNextScheduledWakeUp()); voter->SetQueueEnabled(true); EXPECT_EQ(start_time + delay2, runners_[0]->GetNextScheduledWakeUp()); // Immediate tasks shouldn't make any difference. runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); EXPECT_EQ(start_time + delay2, runners_[0]->GetNextScheduledWakeUp()); // Neither should fences. runners_[0]->InsertFence(TaskQueue::InsertFencePosition::BEGINNING_OF_TIME); EXPECT_EQ(start_time + delay2, runners_[0]->GetNextScheduledWakeUp()); } TEST_F(TaskQueueManagerTest, SetTimeDomainForDisabledQueue) { Initialize(1u); MockTaskQueueObserver observer; runners_[0]->SetObserver(&observer); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromMilliseconds(1)); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = runners_[0]->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); // We should not get a notification for a disabled queue. EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0); std::unique_ptr<VirtualTimeDomain> domain( new VirtualTimeDomain(manager_->Delegate()->NowTicks())); manager_->RegisterTimeDomain(domain.get()); runners_[0]->SetTimeDomain(domain.get()); // Tidy up. runners_[0]->UnregisterTaskQueue(); manager_->UnregisterTimeDomain(domain.get()); } } // namespace scheduler } // namespace blink
36.840068
80
0.717782
[ "object", "vector" ]
1311f1bb14292303abc42c307cb2ce9f27b0b591
861
hpp
C++
src/world.hpp
qkniep/Simetra
734292ff3d48afd83f811501d8da39f5bb0d3623
[ "MIT" ]
2
2021-01-07T15:30:36.000Z
2021-06-13T21:47:46.000Z
src/world.hpp
qkniep/Simetra
734292ff3d48afd83f811501d8da39f5bb0d3623
[ "MIT" ]
null
null
null
src/world.hpp
qkniep/Simetra
734292ff3d48afd83f811501d8da39f5bb0d3623
[ "MIT" ]
null
null
null
#ifndef WORLD_HPP #define WORLD_HPP #include <vector> #include <GL/glew.h> #include <glm/glm.hpp> #include "FastNoise/FastNoise.h" #include "chunk.hpp" struct vertex { GLfloat x, y, z; GLfloat r, g, b; GLfloat nx, ny, nz; }; class World { int seed; std::vector<Chunk*> allChunks; unsigned int deleteIndex; unsigned int currentRow; std::vector<std::array<float, 2>> samples; std::vector<vertex> vertices; std::vector<unsigned int> indices; GLuint vao, vbo, elementbuffer; public: World(int s); ~World(); void load(); void render(GLuint mvp_loc, glm::mat4 mvp); void setSeed(int s); void loadNextRow(); private: vertex generateVertex(const FastNoise& noise, float x, float z); void calculateNormals(unsigned int* v0); void generateDelaunayTerrain(int seed); void placeTrees(int seed); //void addWater(); }; #endif // WORLD_HPP
17.22
65
0.708479
[ "render", "vector" ]
1312747d03195e07dbfa3c67fc3574a18f4a8231
67,272
hpp
C++
sycl/include/sycl/ext/intel/experimental/esimd/memory.hpp
MikeDvorskiy/llvm
8213321ebb90110bf4f3d04fa0dc8e131a464a19
[ "Apache-2.0" ]
null
null
null
sycl/include/sycl/ext/intel/experimental/esimd/memory.hpp
MikeDvorskiy/llvm
8213321ebb90110bf4f3d04fa0dc8e131a464a19
[ "Apache-2.0" ]
null
null
null
sycl/include/sycl/ext/intel/experimental/esimd/memory.hpp
MikeDvorskiy/llvm
8213321ebb90110bf4f3d04fa0dc8e131a464a19
[ "Apache-2.0" ]
null
null
null
//==-------------- memory.hpp - DPC++ Explicit SIMD API --------------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // Implement Explicit SIMD memory-access APIs. //===----------------------------------------------------------------------===// #pragma once #include <CL/sycl/half_type.hpp> #include <sycl/ext/intel/experimental/esimd/common.hpp> #include <sycl/ext/intel/experimental/esimd/detail/memory_intrin.hpp> #include <sycl/ext/intel/experimental/esimd/detail/types.hpp> #include <sycl/ext/intel/experimental/esimd/detail/util.hpp> #include <sycl/ext/intel/experimental/esimd/simd.hpp> #include <cstdint> __SYCL_INLINE_NAMESPACE(cl) { namespace sycl { namespace ext { namespace intel { namespace experimental { namespace esimd { /// @addtogroup sycl_esimd_memory /// @{ /// @defgroup sycl_esimd_memory_atomics Atomic memory access. /// Memory access functions which perform per-lane atomic update using given /// operation. "Per-lane" means that the atomicity guarantees of a vector atomic /// operation are the same as of N independent scalar atomic operations per /// lane (N is number of lanes). /// @defgroup sycl_esimd_memory_slm Shared local memory access functions. /// @} sycl_esimd_memory /// @cond ESIMD_DETAIL namespace detail { // Type used in internal functions to designate SLM access by // providing dummy accessor of this type. Used to make it possible to delegate // implemenations of SLM memory accesses to general surface-based memory // accesses and thus reuse validity checks etc. struct LocalAccessorMarker {}; } // namespace detail /// @endcond ESIMD_DETAIL /// @addtogroup sycl_esimd_memory /// @{ /// Get surface index corresponding to a SYCL accessor. /// /// @param acc a SYCL buffer or image accessor. /// @return the index of the corresponding surface (aka "binding table index"). /// template <typename AccessorTy> __ESIMD_API SurfaceIndex get_surface_index(AccessorTy acc) { if constexpr (std::is_same_v<detail::LocalAccessorMarker, AccessorTy>) { return detail::SLM_BTI; } else { #ifdef __SYCL_DEVICE_ONLY__ const auto mem_obj = detail::AccessorPrivateProxy::getNativeImageObj(acc); return __esimd_get_surface_index(mem_obj); #else // __SYCL_DEVICE_ONLY__ return __esimd_get_surface_index(acc); #endif // __SYCL_DEVICE_ONLY__ } } #define __ESIMD_GET_SURF_HANDLE(acc) get_surface_index(acc) // TODO @Pennycook // {quote} // ...I'd like us to think more about what we can do to make these interfaces // more user - friendly. A user providing cache hints has to provide a lot more // template arguments than required.Could we make this nicer by providing the // hints as tag - type arguments ? // ... // // Without cache hints, type and length can be deduced from offsets // float* p; // simd<uint32_t, 16> offsets; // auto result = flat_load(p, offsets); // // // With cache hints as templates, verbosity increases significantly: // // - Providing any cache hint forces the user to specify the type and // length float* p; simd<uint32_t, 16> offsets; auto result = // flat_load<uint32_t, 16, 1, CacheHint::Foo, CacheHint::Bar>(p, offsets); // // // With cache hints as tag types, verbosity is reduced: // // - Providing a cache hint does not prevent deduction of type and length // float* p; // simd <uint32_t, 16> offsets; // auto result = flat_load(p, offsets, CacheHint::Foo{}); // // Note also that the templated form prevents a developer from specifying an L3 // hint without also explicitly specifying an L1 hint. If flat_load accepted a // list of hints, it might be possible to refactor the hints to specify them in // any order, and it may be more extensible to future cache hints: // {/quote} // // TODO @keryell // {quote} // An approach a la https ://github.com/chriskohlhoff/propria from // @chriskohlhoff would be to add a property to the pointer, such as // // auto result = flat_load(p, offsets); // auto result = flat_load(decorate<CacheHint::Foo, CacheHint::Bar>(p), // offsets); // The advantage is that you do not have to change all tour API and all the uses // of this decorated pointer will benefit from this. decorate is to be bikeshed // accordingly. // {/quote} // /// Loads ("gathers") elements from different memory locations and returns a /// vector of them. Each memory location is base address plus an offset - a /// value of the corresponding element in the input offset vector. Access to /// any element's memory location can be disabled via the input vector of /// predicates (mask). /// @tparam Tx Element type, must be of size 4 or less. /// @tparam N Number of elements to read; can be \c 8, \c 16 or \c 32. /// @param p The base address. /// @param offsets the vector of 32-bit offsets in bytes. For each lane \c i, /// ((byte*)p + offsets[i]) must be element size aligned. /// @param mask The access mask, defaults to all 1s. /// @return A vector of elements read. Elements in masked out lanes are /// undefined. /// template <typename Tx, int N, class T = detail::__raw_t<Tx>> __ESIMD_API std::enable_if_t<N == 8 || N == 16 || N == 32, simd<Tx, N>> gather(const Tx *p, simd<uint32_t, N> offsets, simd_mask<N> mask = 1) { simd<uint64_t, N> offsets_i = convert<uint64_t>(offsets); simd<uint64_t, N> addrs(reinterpret_cast<uint64_t>(p)); addrs = addrs + offsets_i; if constexpr (sizeof(T) == 1) { auto Ret = __esimd_svm_gather<T, N, detail::ElemsPerAddrEncoding<4>()>( addrs.data(), detail::ElemsPerAddrEncoding<1>(), mask.data()); return __esimd_rdregion<T, N * 4, N, /*VS*/ 0, N, 4>(Ret, 0); } else if constexpr (sizeof(T) == 2) { auto Ret = __esimd_svm_gather<T, N, detail::ElemsPerAddrEncoding<2>()>( addrs.data(), detail::ElemsPerAddrEncoding<2>(), mask.data()); return __esimd_rdregion<T, N * 2, N, /*VS*/ 0, N, 2>(Ret, 0); } else return __esimd_svm_gather<T, N, detail::ElemsPerAddrEncoding<1>()>( addrs.data(), detail::ElemsPerAddrEncoding<1>(), mask.data()); } /// Writes ("scatters") elements of the input vector to different memory /// locations. Each memory location is base address plus an offset - a /// value of the corresponding element in the input offset vector. Access to /// any element's memory location can be disabled via the input mask. /// @tparam Tx Element type, must be of size 4 or less. /// @tparam N Number of elements to write; can be \c 8, \c 16 or \c 32. /// @param p The base address. /// @param offsets A vector of 32-bit offsets in bytes. For each lane \c i, /// ((byte*)p + offsets[i]) must be element size aligned. /// @param vals The vector to scatter. /// @param mask The access mask, defaults to all 1s. /// template <typename Tx, int N, class T = detail::__raw_t<Tx>> __ESIMD_API std::enable_if_t<N == 8 || N == 16 || N == 32> scatter(Tx *p, simd<uint32_t, N> offsets, simd<Tx, N> vals, simd_mask<N> mask = 1) { simd<uint64_t, N> offsets_i = convert<uint64_t>(offsets); simd<uint64_t, N> addrs(reinterpret_cast<uint64_t>(p)); addrs = addrs + offsets_i; if constexpr (sizeof(T) == 1) { simd<T, N * 4> D; D = __esimd_wrregion<T, N * 4, N, /*VS*/ 0, N, 4>(D.data(), vals.data(), 0); __esimd_svm_scatter<T, N, detail::ElemsPerAddrEncoding<4>()>( addrs.data(), D.data(), detail::ElemsPerAddrEncoding<1>(), mask.data()); } else if constexpr (sizeof(T) == 2) { simd<T, N * 2> D; D = __esimd_wrregion<T, N * 2, N, /*VS*/ 0, N, 2>(D.data(), vals.data(), 0); __esimd_svm_scatter<T, N, detail::ElemsPerAddrEncoding<2>()>( addrs.data(), D.data(), detail::ElemsPerAddrEncoding<2>(), mask.data()); } else __esimd_svm_scatter<T, N, detail::ElemsPerAddrEncoding<1>()>( addrs.data(), vals.data(), detail::ElemsPerAddrEncoding<1>(), mask.data()); } /// Loads a contiguous block of memory from given memory address and returns /// the loaded data as a vector. Actual code generated depends on the /// alignment parameter. /// @tparam Tx Element type. /// @tparam N Number of elements to load, <code>N * sizeof(Tx)</code> must be /// 1, 2, 4 or 8 owords long. /// @tparam Flags The alignment specifier type tag. Auto-deduced from the /// \c Flags parameter. If it is less than \c 16, then slower unaligned /// access is generated, othewise the access is aligned. /// @param addr The address to load from. /// @param Flags Specifies the alignment. /// @return A vector of loaded elements. /// template <typename Tx, int N, typename Flags = vector_aligned_tag, class T = detail::__raw_t<Tx>, typename = std::enable_if_t<is_simd_flag_type_v<Flags>>> __ESIMD_API simd<Tx, N> block_load(const Tx *addr, Flags = {}) { constexpr unsigned Sz = sizeof(T) * N; static_assert(Sz >= detail::OperandSize::OWORD, "block size must be at least 1 oword"); static_assert(Sz % detail::OperandSize::OWORD == 0, "block size must be whole number of owords"); static_assert(detail::isPowerOf2(Sz / detail::OperandSize::OWORD), "block must be 1, 2, 4 or 8 owords long"); static_assert(Sz <= 8 * detail::OperandSize::OWORD, "block size must be at most 8 owords"); uintptr_t Addr = reinterpret_cast<uintptr_t>(addr); if constexpr (Flags::template alignment<simd<T, N>> >= detail::OperandSize::OWORD) { return __esimd_svm_block_ld<T, N>(Addr); } else { return __esimd_svm_block_ld_unaligned<T, N>(Addr); } } /// Loads a contiguous block of memory from given accessor and offset and /// returns the loaded data as a vector. Actual code generated depends on the /// alignment parameter. /// @tparam Tx Element type. /// @tparam N Number of elements to load, <code>N * sizeof(Tx)</code> must be /// 1, 2, 4 or 8 owords long. /// @tparam AccessorTy Accessor type (auto-deduced). /// @tparam Flags The alignment specifier type tag. Auto-deduced from the /// \c Flags parameter. If it is less than \c 16, then slower unaligned /// access is generated, othewise the access is aligned. /// @param acc The accessor. /// @param offset The offset to load from in bytes. /// @param Flags Specifies the alignment. /// @return A vector of loaded elements. /// template <typename Tx, int N, typename AccessorTy, typename Flags = vector_aligned_tag, typename = std::enable_if_t<is_simd_flag_type_v<Flags>>, class T = detail::__raw_t<Tx>> __ESIMD_API simd<Tx, N> block_load(AccessorTy acc, uint32_t offset, Flags = {}) { constexpr unsigned Sz = sizeof(T) * N; static_assert(Sz >= detail::OperandSize::OWORD, "block size must be at least 1 oword"); static_assert(Sz % detail::OperandSize::OWORD == 0, "block size must be whole number of owords"); static_assert(detail::isPowerOf2(Sz / detail::OperandSize::OWORD), "block must be 1, 2, 4 or 8 owords long"); static_assert(Sz <= 8 * detail::OperandSize::OWORD, "block size must be at most 8 owords"); #if defined(__SYCL_DEVICE_ONLY__) auto surf_ind = __esimd_get_surface_index( detail::AccessorPrivateProxy::getNativeImageObj(acc)); #else // __SYCL_DEVICE_ONLY__ auto surf_ind = __esimd_get_surface_index(acc); #endif // __SYCL_DEVICE_ONLY__ if constexpr (Flags::template alignment<simd<T, N>> >= detail::OperandSize::OWORD) { return __esimd_oword_ld<T, N>(surf_ind, offset >> 4); } else { return __esimd_oword_ld_unaligned<T, N>(surf_ind, offset); } } /// Stores elements of a vector to a contiguous block of memory at given /// address. The address must be at least \c 16 bytes-aligned. /// @tparam Tx Element type. /// @tparam N Number of elements to store, <code>N * sizeof(Tx)</code> must be /// 1, 2, 4 or 8 owords long. /// @param p The memory address to store at. /// @param vals The vector to store. /// template <typename Tx, int N, class T = detail::__raw_t<Tx>> __ESIMD_API void block_store(Tx *p, simd<Tx, N> vals) { constexpr unsigned Sz = sizeof(T) * N; static_assert(Sz >= detail::OperandSize::OWORD, "block size must be at least 1 oword"); static_assert(Sz % detail::OperandSize::OWORD == 0, "block size must be whole number of owords"); static_assert(detail::isPowerOf2(Sz / detail::OperandSize::OWORD), "block must be 1, 2, 4 or 8 owords long"); static_assert(Sz <= 8 * detail::OperandSize::OWORD, "block size must be at most 8 owords"); uintptr_t Addr = reinterpret_cast<uintptr_t>(p); __esimd_svm_block_st<T, N>(Addr, vals.data()); } /// Stores elements of a vector to a contiguous block of memory represented by /// an accessor and an offset within this accessor. /// @tparam Tx Element type. /// @tparam N Number of elements to store, <code>N * sizeof(Tx)</code> must be /// 1, 2, 4 or 8 owords long. /// @tparam AccessorTy Accessor type (auto-deduced). /// @param acc The accessor to store to. /// @param offset The offset to store at. It is in bytes and must be a multiple /// of \c 16. /// @param vals The vector to store. /// template <typename Tx, int N, typename AccessorTy, class T = detail::__raw_t<Tx>> __ESIMD_API void block_store(AccessorTy acc, uint32_t offset, simd<Tx, N> vals) { constexpr unsigned Sz = sizeof(T) * N; static_assert(Sz >= detail::OperandSize::OWORD, "block size must be at least 1 oword"); static_assert(Sz % detail::OperandSize::OWORD == 0, "block size must be whole number of owords"); static_assert(detail::isPowerOf2(Sz / detail::OperandSize::OWORD), "block must be 1, 2, 4 or 8 owords long"); static_assert(Sz <= 8 * detail::OperandSize::OWORD, "block size must be at most 8 owords"); #if defined(__SYCL_DEVICE_ONLY__) auto surf_ind = __esimd_get_surface_index( detail::AccessorPrivateProxy::getNativeImageObj(acc)); #else // auto surf_ind = __esimd_get_surface_index(acc); #endif __esimd_oword_st<T, N>(surf_ind, offset >> 4, vals.data()); } /// @} sycl_esimd_memory /// @cond ESIMD_DETAIL // Implementations of accessor-based gather and scatter functions namespace detail { template <typename T, int N, typename AccessorTy> ESIMD_INLINE ESIMD_NODEBUG std::enable_if_t<(sizeof(T) <= 4) && (N == 1 || N == 8 || N == 16 || N == 32) && !std::is_pointer<AccessorTy>::value> scatter_impl(AccessorTy acc, simd<T, N> vals, simd<uint32_t, N> offsets, uint32_t glob_offset, simd_mask<N> mask) { constexpr int TypeSizeLog2 = detail::ElemsPerAddrEncoding<sizeof(T)>(); // TODO (performance) use hardware-supported scale once BE supports it constexpr int16_t scale = 0; const auto si = __ESIMD_GET_SURF_HANDLE(acc); if constexpr (sizeof(T) < 4) { using Tint = std::conditional_t<std::is_integral_v<T>, T, detail::uint_type_t<sizeof(T)>>; using Treal = __raw_t<T>; simd<Tint, N> vals_int = bitcast<Tint, Treal, N>(std::move(vals).data()); using PromoT = typename sycl::detail::conditional_t<std::is_signed<Tint>::value, int32_t, uint32_t>; const simd<PromoT, N> promo_vals = convert<PromoT>(std::move(vals_int)); __esimd_scatter_scaled<PromoT, N, decltype(si), TypeSizeLog2, scale>( mask.data(), si, glob_offset, offsets.data(), promo_vals.data()); } else { __esimd_scatter_scaled<T, N, decltype(si), TypeSizeLog2, scale>( mask.data(), si, glob_offset, offsets.data(), vals.data()); } } template <typename T, int N, typename AccessorTy> ESIMD_INLINE ESIMD_NODEBUG std::enable_if_t< (sizeof(T) <= 4) && (N == 1 || N == 8 || N == 16 || N == 32) && !std::is_pointer<AccessorTy>::value, simd<T, N>> gather_impl(AccessorTy acc, simd<uint32_t, N> offsets, uint32_t glob_offset, simd_mask<N> mask) { constexpr int TypeSizeLog2 = detail::ElemsPerAddrEncoding<sizeof(T)>(); // TODO (performance) use hardware-supported scale once BE supports it constexpr uint32_t scale = 0; const auto si = get_surface_index(acc); if constexpr (sizeof(T) < 4) { using Tint = std::conditional_t<std::is_integral_v<T>, T, detail::uint_type_t<sizeof(T)>>; using Treal = __raw_t<T>; static_assert(std::is_integral<Tint>::value, "only integral 1- & 2-byte types are supported"); using PromoT = typename sycl::detail::conditional_t<std::is_signed<Tint>::value, int32_t, uint32_t>; const simd<PromoT, N> promo_vals = __esimd_gather_masked_scaled2<PromoT, N, decltype(si), TypeSizeLog2, scale>(si, glob_offset, offsets.data(), mask.data()); auto Res = convert<Tint>(promo_vals); if constexpr (!std::is_same_v<Tint, T>) { return detail::bitcast<Treal, Tint, N>(Res.data()); } else { return Res; } } else { return __esimd_gather_masked_scaled2<T, N, decltype(si), TypeSizeLog2, scale>(si, glob_offset, offsets.data(), mask.data()); } } } // namespace detail /// @endcond ESIMD_DETAIL /// @addtogroup sycl_esimd_memory /// @{ /// @anchor accessor_gather Accessor-based gather. /// /// Collects elements located at given offsets in an accessor and returns them /// as a single \ref simd object. An element can be 1, 2 or 4-byte value. /// /// @tparam T Element type; can only be a 1,2,4-byte integer, \c sycl::half or /// \c float. /// @tparam N The number of vector elements. Can be \c 1, \c 8, \c 16 or \c 32. /// @tparam AccessorTy The accessor type. /// @param acc The accessor to gather from. /// @param offsets Per-element offsets in bytes. /// @param glob_offset Offset in bytes added to each individual element's offset /// to compute actual memory access offset for that element. /// @param mask Memory access mask. Elements with zero corresponding mask's /// predicate are not accessed, their values in the resulting vector are /// undefined. /// template <typename T, int N, typename AccessorTy> __ESIMD_API std::enable_if_t<(sizeof(T) <= 4) && (N == 1 || N == 8 || N == 16 || N == 32) && !std::is_pointer<AccessorTy>::value, simd<T, N>> gather(AccessorTy acc, simd<uint32_t, N> offsets, uint32_t glob_offset = 0, simd_mask<N> mask = 1) { return detail::gather_impl<T, N, AccessorTy>(acc, offsets, glob_offset, mask); } /// @anchor accessor_scatter /// Accessor-based scatter. /// /// Writes elements of a \ref simd object into an accessor at given offsets. /// An element can be 1, 2 or 4-byte value. /// /// @tparam T Element type; can only be a 1,2,4-byte integer, \c sycl::half or /// \c float. /// @tparam N The number of vector elements. Can be \c 1, \c 8, \c 16 or \c 32. /// @tparam AccessorTy The accessor type. /// @param acc The accessor to scatter to. /// @param offsets Per-element offsets in bytes. /// @param vals Values to write. /// @param glob_offset Offset in bytes added to each individual element's offset /// to compute actual memory access offset for that element. /// @param mask Memory access mask. Elements with zero corresponding mask's /// predicate are not accessed. /// /// template <typename T, int N, typename AccessorTy> __ESIMD_API std::enable_if_t<(sizeof(T) <= 4) && (N == 1 || N == 8 || N == 16 || N == 32) && !std::is_pointer<AccessorTy>::value> scatter(AccessorTy acc, simd<uint32_t, N> offsets, simd<T, N> vals, uint32_t glob_offset = 0, simd_mask<N> mask = 1) { detail::scatter_impl<T, N, AccessorTy>(acc, vals, offsets, glob_offset, mask); } /// Load a scalar value from an accessor. /// @tparam T Type of the value. /// @tparam AccessorTy Type of the accessor. /// @param acc Accessor to load from. /// @param offset Offset in bytes. /// @return The loaded value. /// template <typename T, typename AccessorTy> __ESIMD_API T scalar_load(AccessorTy acc, uint32_t offset) { const simd<T, 1> Res = gather<T, 1, AccessorTy>(acc, simd<uint32_t, 1>(offset)); return Res[0]; } /// Store a scalar value into an accessor. /// @tparam T Type of the value. /// @tparam AccessorTy Type of the accessor. /// @param acc Accessor to store to. /// @param offset Offset in bytes. /// @param val The stored value. /// template <typename T, typename AccessorTy> __ESIMD_API void scalar_store(AccessorTy acc, uint32_t offset, T val) { scatter<T, 1, AccessorTy>(acc, simd<uint32_t, 1>(offset), simd<T, 1>(val)); } /// @anchor usm_gather_rgba /// Gather and transpose pixels from given memory locations defined by the base /// pointer \c p and \c offsets. Up to 4 32-bit data elements may be accessed at /// each address depending on the channel mask \c Mask template parameter. Each /// pixel's address must be 4 byte aligned. As an example, let's assume we want /// to read \c n pixels at address \c addr, skipping \c G and \c B channels. /// Each channel is a 32-bit float and the pixel data at given address in memory /// is: /// @code{.cpp} /// R1 G1 B1 A1 R2 G2 B2 A2 ... Rn Gn Bn An /// @endcode /// Then this can be achieved by using /// @code{.cpp} /// simd<uint32_t, n> byte_offsets(0, 4*4 /* byte size of a single pixel */); /// auto x = gather_rgba<float, n, rgba_channel_mask::AR>(addr, byte_offsets); /// @endcode /// Returned \c x will contain \c 2*n \c float elements: /// @code{.cpp} /// R1 R2 ... Rn A1 A2 ... An /// @endcode /// /// @tparam Tx Element type of the returned vector. Must be 4 bytes in size. /// @tparam N Number of pixels to access (matches the size of the \c offsets /// vector). Must be 8, 16 or 32. /// @tparam Mask A pixel's channel mask. /// @param p The USM base pointer representing memory address of the access. /// @param offsets Byte offsets of the pixels relative to the base pointer. /// @param mask Memory access mask. Pixels with zero corresponding mask's /// predicate are not accessed. Their values in the resulting vector are /// undefined. /// @return Read data - up to N*4 values of type \c Tx. /// template <typename Tx, int N, rgba_channel_mask Mask, class T = detail::__raw_t<Tx>> __ESIMD_API std::enable_if_t<(N == 8 || N == 16 || N == 32) && (sizeof(T) == 4), simd<Tx, N * get_num_channels_enabled(Mask)>> gather_rgba(const Tx *p, simd<uint32_t, N> offsets, simd_mask<N> mask = 1) { simd<uint64_t, N> offsets_i = convert<uint64_t>(offsets); simd<uint64_t, N> addrs(reinterpret_cast<uint64_t>(p)); addrs = addrs + offsets_i; return __esimd_svm_gather4_scaled<T, N, Mask>(addrs.data(), mask.data()); } /// @anchor usm_scatter_rgba /// Transpose and scatter pixels to given memory locations defined by the base /// pointer \c p and \c offsets. Up to 4 32-bit data elements may be accessed at /// each address depending on the channel mask \c Mask template parameter. Each /// pixel's address must be 4 byte aligned. This is basically an inverse /// operation for gather_rgba. /// /// @tparam Tx Element type of the returned vector. Must be 4 bytes in size. /// @tparam N Number of pixels to access (matches the size of the \c offsets /// vector). Must be 8, 16 or 32. /// @tparam Mask A pixel's channel mask. /// @param p The USM base pointer representing memory address of the access. /// @param vals values to be written. /// @param offsets Byte offsets of the pixels relative to the base pointer. /// @param mask Memory access mask. Pixels with zero corresponding mask's /// predicate are not accessed. Their values in the resulting vector are /// undefined. /// template <typename Tx, int N, rgba_channel_mask Mask, class T = detail::__raw_t<Tx>> __ESIMD_API std::enable_if_t<(N == 8 || N == 16 || N == 32) && (sizeof(T) == 4)> scatter_rgba(Tx *p, simd<uint32_t, N> offsets, simd<Tx, N * get_num_channels_enabled(Mask)> vals, simd_mask<N> mask = 1) { simd<uint64_t, N> offsets_i = convert<uint64_t>(offsets); simd<uint64_t, N> addrs(reinterpret_cast<uint64_t>(p)); addrs = addrs + offsets_i; __esimd_svm_scatter4_scaled<T, N, Mask>(addrs.data(), vals.data(), mask.data()); } /// @} sycl_esimd_memory /// @cond ESIMD_DETAIL namespace detail { /// Check the legality of an atomic call in terms of size and type. /// template <atomic_op Op, typename T, int N, unsigned NumSrc> constexpr bool check_atomic() { if constexpr (!detail::isPowerOf2(N, 32)) { static_assert((detail::isPowerOf2(N, 32)), "Execution size 1, 2, 4, 8, 16, 32 are supported"); return false; } // No source operands. if constexpr (Op == atomic_op::inc || Op == atomic_op::dec) { if constexpr (NumSrc != 0) { static_assert(NumSrc == 0, "No source operands are expected"); return false; } if constexpr (!is_type<T, uint16_t, uint32_t, uint64_t>()) { static_assert((is_type<T, uint16_t, uint32_t, uint64_t>()), "Type UW, UD or UQ is expected"); return false; } return true; } // One source integer operand. if constexpr (Op == atomic_op::add || Op == atomic_op::sub || Op == atomic_op::min || Op == atomic_op::max || Op == atomic_op::xchg || Op == atomic_op::bit_and || Op == atomic_op::bit_or || Op == atomic_op::bit_xor || Op == atomic_op::minsint || Op == atomic_op::maxsint) { if constexpr (NumSrc != 1) { static_assert(NumSrc == 1, "One source operand is expected"); return false; } if constexpr ((Op != atomic_op::minsint && Op != atomic_op::maxsint) && !is_type<T, uint16_t, uint32_t, uint64_t>()) { static_assert((is_type<T, uint16_t, uint32_t, uint64_t>()), "Type UW, UD or UQ is expected"); return false; } if constexpr ((Op == atomic_op::minsint || Op == atomic_op::maxsint) && !is_type<T, int16_t, int32_t, int64_t>()) { static_assert((is_type<T, int16_t, int32_t, int64_t>()), "Type W, D or Q is expected"); return false; } return true; } // One source float operand. if constexpr (Op == atomic_op::fmax || Op == atomic_op::fmin) { if constexpr (NumSrc != 1) { static_assert(NumSrc == 1, "One source operand is expected"); return false; } if constexpr (!is_type<T, float, sycl::half>()) { static_assert((is_type<T, float, sycl::half>()), "Type F or HF is expected"); return false; } return true; } // Two source operands. if constexpr (Op == atomic_op::cmpxchg || Op == atomic_op::fcmpwr) { if constexpr (NumSrc != 2) { static_assert(NumSrc == 2, "Two source operands are expected"); return false; } if constexpr (Op == atomic_op::cmpxchg && !is_type<T, uint16_t, uint32_t, uint64_t>()) { static_assert((is_type<T, uint16_t, uint32_t, uint64_t>()), "Type UW, UD or UQ is expected"); return false; } if constexpr (Op == atomic_op::fcmpwr && !is_type<T, float, sycl::half>()) { static_assert((is_type<T, float, sycl::half>()), "Type F or HF is expected"); return false; } return true; } // Unsupported svm atomic Op. return false; } } // namespace detail /// @endcond ESIMD_DETAIL /// @addtogroup sycl_esimd_memory_atomics /// @{ /// @anchor usm_atomic_update0 /// Atomically updates \c N memory locations represented by a USM pointer and /// a vector of offsets relative to the pointer, and returns a vector of old /// values found at the memory locations before update. The update operation /// has no arguments in addition to the value at the memory location. /// /// @tparam Op The atomic operation - can be \c atomic_op::inc or /// atomic_op::dec. /// @tparam Tx The vector element type. /// @tparam N The number of memory locations to update. /// @param p The USM pointer. /// @param offset The vector of 32-bit offsets in bytes. /// @param mask Operation mask, only locations with non-zero in the /// corresponding mask element are updated. /// @return A vector of the old values at the memory locations before the /// update. /// template <atomic_op Op, typename Tx, int N, class T = detail::__raw_t<Tx>> __ESIMD_API std::enable_if_t<detail::check_atomic<Op, Tx, N, 0>(), simd<Tx, N>> atomic_update(Tx *p, simd<unsigned, N> offset, simd_mask<N> mask) { simd<uintptr_t, N> vAddr(reinterpret_cast<uintptr_t>(p)); simd<uintptr_t, N> offset_i1 = convert<uintptr_t>(offset); vAddr += offset_i1; return __esimd_svm_atomic0<Op, T, N>(vAddr.data(), mask.data()); } /// @anchor usm_atomic_update1 /// Atomically updates \c N memory locations represented by a USM pointer and /// a vector of offsets relative to the pointer, and returns a vector of old /// values found at the memory locations before update. The update operation /// has 1 additional argument. /// /// @tparam Op The atomic operation - can be one of the following: /// \c atomic_op::add, \c atomic_op::sub, \c atomic_op::min, \c atomic_op::max, /// \c atomic_op::xchg, \c atomic_op::bit_and, \c atomic_op::bit_or, /// \c atomic_op::bit_xor, \c atomic_op::minsint, \c atomic_op::maxsint, /// \c atomic_op::fmax, \c atomic_op::fmin. /// @tparam Tx The vector element type. /// @tparam N The number of memory locations to update. /// @param p The USM pointer. /// @param offset The vector of 32-bit offsets in bytes. /// @param src0 The additional argument. /// @param mask Operation mask, only locations with non-zero in the /// corresponding mask element are updated. /// @return A vector of the old values at the memory locations before the /// update. /// template <atomic_op Op, typename Tx, int N, class T = detail::__raw_t<Tx>> __ESIMD_API std::enable_if_t<detail::check_atomic<Op, Tx, N, 1>(), simd<Tx, N>> atomic_update(Tx *p, simd<unsigned, N> offset, simd<Tx, N> src0, simd_mask<N> mask) { simd<uintptr_t, N> vAddr(reinterpret_cast<uintptr_t>(p)); simd<uintptr_t, N> offset_i1 = convert<uintptr_t>(offset); vAddr += offset_i1; return __esimd_svm_atomic1<Op, T, N>(vAddr.data(), src0.data(), mask.data()); } /// @anchor usm_atomic_update2 /// Atomically updates \c N memory locations represented by a USM pointer and /// a vector of offsets relative to the pointer, and returns a vector of old /// values found at the memory locations before update. The update operation /// has 2 additional arguments. /// /// @tparam Op The atomic operation - can be one of the following: /// \c atomic_op::cmpxchg, \c atomic_op::fcmpwr. /// @tparam Tx The vector element type. /// @tparam N The number of memory locations to update. /// @param p The USM pointer. /// @param offset The vector of 32-bit offsets in bytes. /// @param src0 The first additional argument (expected value). /// @param src1 The second additional argument (new value). /// @param mask Operation mask, only locations with non-zero in the /// corresponding mask element are updated. /// @return A vector of the old values at the memory locations before the /// update. /// template <atomic_op Op, typename Tx, int N, class T = detail::__raw_t<Tx>> __ESIMD_API std::enable_if_t<detail::check_atomic<Op, Tx, N, 2>(), simd<Tx, N>> atomic_update(Tx *p, simd<unsigned, N> offset, simd<Tx, N> src0, simd<Tx, N> src1, simd_mask<N> mask) { simd<uintptr_t, N> vAddr(reinterpret_cast<uintptr_t>(p)); simd<uintptr_t, N> offset_i1 = convert<uintptr_t>(offset); vAddr += offset_i1; return __esimd_svm_atomic2<Op, T, N>(vAddr.data(), src0.data(), src1.data(), mask.data()); } /// @} sycl_esimd_memory_atomics /// @addtogroup sycl_esimd_memory /// @{ /// Represetns a bit mask to control behavior of esimd::fence. /// Enum elements define semantics of the bits in the mask. enum fence_mask : uint8_t { /// “Commit enable” - wait for fence to complete before continuing. global_coherent_fence = 0x1, /// Flush the instruction cache. l3_flush_instructions = 0x2, /// Flush sampler (texture) cache. l3_flush_texture_data = 0x4, /// Flush constant cache. l3_flush_constant_data = 0x8, /// Flush constant cache. l3_flush_rw_data = 0x10, /// Issue SLM memory barrier only. If not set, the memory barrier is global. local_barrier = 0x20, /// Flush L1 read - only data cache. l1_flush_ro_data = 0x40, /// Enable thread scheduling barrier. sw_barrier = 0x80 }; /// esimd::fence sets the memory read/write order. /// @tparam cntl A bitmask composed from \c fence_mask bits. /// __ESIMD_API void fence(fence_mask cntl) { __esimd_fence(cntl); } /// Generic work-group barrier. /// Performs barrier synchronization for all threads within the same thread /// group. The barrier instruction causes the executing thread to wait until /// all threads in the same thread group have executed the barrier instruction. /// Memory ordering is also guaranteed by this instruction. /// The behavior is undefined if this instruction is executed in divergent /// control flow. /// __ESIMD_API void barrier() { __esimd_fence(fence_mask::global_coherent_fence | fence_mask::local_barrier); __esimd_barrier(); } /// Generic work-group split barrier __ESIMD_API void sbarrier(split_barrier_action flag) { __esimd_sbarrier(flag); } /// @} sycl_esimd_memory /// @addtogroup sycl_esimd_memory_slm /// @{ /// Declare per-work-group slm size. __ESIMD_API void slm_init(uint32_t size) { __esimd_slm_init(size); } /// Gather operation over the Shared Local Memory. /// This API has almost the same interface as the @ref accessor_gather /// "accessor-based gather", except that it does not have the accessor and the /// global offset parameters. /// template <typename T, int N> __ESIMD_API std::enable_if_t<(N == 1 || N == 8 || N == 16 || N == 32), simd<T, N>> slm_gather(simd<uint32_t, N> offsets, simd_mask<N> mask = 1) { detail::LocalAccessorMarker acc; return detail::gather_impl<T, N>(acc, offsets, 0, mask); } /// Load a scalar value from the Shared Local Memory. /// @tparam T type of the value /// @param offset SLM offset in bytes /// @return the loaded value /// template <typename T> __ESIMD_API T slm_scalar_load(uint32_t offset) { const simd<T, 1> Res = slm_gather<T, 1>(simd<uint32_t, 1>(offset)); return Res[0]; } /// Scatter operation over the Shared Local Memory. /// This API has almost the same interface as the @ref accessor_scatter /// "accessor-based scatter", except that it does not have the accessor and the /// global offset parameters. /// template <typename T, int N> __ESIMD_API std::enable_if_t<(N == 1 || N == 8 || N == 16 || N == 32) && (sizeof(T) <= 4)> slm_scatter(simd<uint32_t, N> offsets, simd<T, N> vals, simd_mask<N> mask = 1) { detail::LocalAccessorMarker acc; detail::scatter_impl<T, N>(acc, vals, offsets, 0, mask); } /// Store a scalar value into the Shared Local Memory. /// @tparam T type of the value /// @param offset SLM offset in bytes /// @param val value to store /// template <typename T> __ESIMD_API void slm_scalar_store(uint32_t offset, T val) { slm_scatter<T, 1>(simd<uint32_t, 1>(offset), simd<T, 1>(val), 1); } /// Gather data from the Shared Local Memory at specified \c offsets and return /// it as simd vector. See @ref usm_gather_rgba for information about the /// operation semantics and parameter restrictions/interdependencies. /// @tparam T The element type of the returned vector. /// @tparam N The number of elements to access. /// @tparam Mask Pixel's channel mask. /// @param offsets Byte offsets within the SLM of each element. /// @param mask Operation mask. All-1 by default. /// @return Gathered data as an \c N - element vector. /// template <typename T, int N, rgba_channel_mask Mask> __ESIMD_API std::enable_if_t<(N == 8 || N == 16 || N == 32) && (sizeof(T) == 4), simd<T, N * get_num_channels_enabled(Mask)>> slm_gather_rgba(simd<uint32_t, N> offsets, simd_mask<N> mask = 1) { const auto si = __ESIMD_GET_SURF_HANDLE(detail::LocalAccessorMarker()); return __esimd_gather4_scaled<T, N, decltype(si), Mask>( mask.data(), si, 0 /*global_offset*/, offsets.data()); } /// Gather data from the Shared Local Memory at specified \c offsets and return /// it as simd vector. See @ref usm_gather_rgba for information about the /// operation semantics and parameter restrictions/interdependencies. /// @tparam T The element type of the returned vector. /// @tparam N The number of elements to access. /// @tparam Mask Pixel's channel mask. /// @param offsets Byte offsets within the SLM of each element. /// @param vals values to be written. /// @param mask Operation mask. All-1 by default. /// template <typename T, int N, rgba_channel_mask Mask> __ESIMD_API std::enable_if_t<(N == 8 || N == 16 || N == 32) && (sizeof(T) == 4)> slm_scatter_rgba(simd<uint32_t, N> offsets, simd<T, N * get_num_channels_enabled(Mask)> vals, simd_mask<N> mask = 1) { const auto si = __ESIMD_GET_SURF_HANDLE(detail::LocalAccessorMarker()); constexpr int16_t Scale = 0; constexpr int global_offset = 0; __esimd_scatter4_scaled<T, N, decltype(si), Mask, Scale>( mask.data(), si, global_offset, offsets.data(), vals.data()); } /// Loads a contiguous block of memory from the SLM at given offset and /// returns the loaded data as a vector. /// @tparam T Element type. /// @tparam N Number of elements to load, <code>N * sizeof(Tx)</code> must be /// 1, 2, 4 or 8 owords long. /// @param offset The offset to load from in bytes. Must be oword-aligned. /// @return A vector of loaded elements. /// template <typename T, int N> __ESIMD_API simd<T, N> slm_block_load(uint32_t offset) { constexpr unsigned Sz = sizeof(T) * N; static_assert(Sz >= detail::OperandSize::OWORD, "block size must be at least 1 oword"); static_assert(Sz % detail::OperandSize::OWORD == 0, "block size must be whole number of owords"); static_assert(detail::isPowerOf2(Sz / detail::OperandSize::OWORD), "block must be 1, 2, 4 or 8 owords long"); static_assert(Sz <= 16 * detail::OperandSize::OWORD, "block size must be at most 16 owords"); const auto si = __ESIMD_GET_SURF_HANDLE(detail::LocalAccessorMarker()); return __esimd_oword_ld<detail::__raw_t<T>, N>(si, offset >> 4); } /// Stores elements of a vector to a contiguous block of SLM at given /// offset. /// @tparam T Element type. /// @tparam N Number of elements to store, <code>N * sizeof(Tx)</code> must be /// 1, 2, 4 or 8 owords long. /// @param offset The offset in bytes to store at. Must be oword-aligned. /// @param vals The vector to store. /// template <typename T, int N> __ESIMD_API void slm_block_store(uint32_t offset, simd<T, N> vals) { constexpr unsigned Sz = sizeof(T) * N; static_assert(Sz >= detail::OperandSize::OWORD, "block size must be at least 1 oword"); static_assert(Sz % detail::OperandSize::OWORD == 0, "block size must be whole number of owords"); static_assert(detail::isPowerOf2(Sz / detail::OperandSize::OWORD), "block must be 1, 2, 4 or 8 owords long"); static_assert(Sz <= 8 * detail::OperandSize::OWORD, "block size must be at most 8 owords"); const auto si = __ESIMD_GET_SURF_HANDLE(detail::LocalAccessorMarker()); // offset in genx.oword.st is in owords __esimd_oword_st<detail::__raw_t<T>, N>(si, offset >> 4, vals.data()); } /// Atomic update operation performed on SLM. No source operands version. /// See description of template and function parameters in @ref /// usm_atomic_update0 "atomic update" operation docs. template <atomic_op Op, typename Tx, int N, class T = detail::__raw_t<Tx>> __ESIMD_API std::enable_if_t<detail::check_atomic<Op, T, N, 0>(), simd<Tx, N>> slm_atomic_update(simd<uint32_t, N> offsets, simd_mask<N> mask) { const auto si = __ESIMD_GET_SURF_HANDLE(detail::LocalAccessorMarker()); return __esimd_dword_atomic0<Op, T, N>(mask.data(), si, offsets.data()); } /// Atomic update operation performed on SLM. One source operands version. /// See description of template and function parameters in @ref /// usm_atomic_update1 "atomic update" operation docs. template <atomic_op Op, typename Tx, int N, class T = detail::__raw_t<Tx>> __ESIMD_API std::enable_if_t<detail::check_atomic<Op, T, N, 1>(), simd<Tx, N>> slm_atomic_update(simd<uint32_t, N> offsets, simd<Tx, N> src0, simd_mask<N> mask) { const auto si = __ESIMD_GET_SURF_HANDLE(detail::LocalAccessorMarker()); return __esimd_dword_atomic1<Op, T, N>(mask.data(), si, offsets.data(), src0.data()); } /// Atomic update operation performed on SLM. Two source operands version. /// See description of template and function parameters in @ref /// usm_atomic_update2 "atomic update" operation docs. template <atomic_op Op, typename Tx, int N, class T = detail::__raw_t<Tx>> __ESIMD_API std::enable_if_t<detail::check_atomic<Op, T, N, 2>(), simd<Tx, N>> slm_atomic_update(simd<uint32_t, N> offsets, simd<Tx, N> src0, simd<Tx, N> src1, simd_mask<N> mask) { const auto si = __ESIMD_GET_SURF_HANDLE(detail::LocalAccessorMarker()); return __esimd_dword_atomic2<Op, T, N>(mask.data(), si, offsets.data(), src0.data(), src1.data()); } /// @} sycl_esimd_memory_slm /// @addtogroup sycl_esimd_memory /// @{ /// Media block load. /// /// @tparam T is the element data type. /// @tparam m is the height of the 2D block. /// @tparam N is the width of the 2D block. /// @tparam AccessorTy is type of the SYCL accessor. /// @tparam plane is planar surface index. /// @param acc is the SYCL accessor. /// @param x is X-coordinate of the left upper rectangle corner in BYTES. /// @param y is Y-coordinate of the left upper rectangle corner in ROWS. /// @return the linearized 2D block data read from surface. /// template <typename T, int m, int N, typename AccessorTy, unsigned plane = 0> __ESIMD_API simd<T, m * N> media_block_load(AccessorTy acc, unsigned x, unsigned y) { constexpr unsigned Width = N * sizeof(T); static_assert(Width * m <= 256u, "data does not fit into a single dataport transaction"); static_assert(Width <= 64u, "valid block width is in range [1, 64]"); static_assert(m <= 64u, "valid block height is in range [1, 64]"); static_assert(plane <= 3u, "valid plane index is in range [0, 3]"); const auto si = __ESIMD_GET_SURF_HANDLE(acc); using SurfIndTy = decltype(si); constexpr unsigned int RoundedWidth = Width < 4 ? 4 : detail::getNextPowerOf2<Width>(); constexpr int BlockWidth = sizeof(T) * N; constexpr int Mod = 0; if constexpr (Width < RoundedWidth) { constexpr unsigned int n1 = RoundedWidth / sizeof(T); simd<T, m *n1> temp = __esimd_media_ld<T, m, n1, Mod, SurfIndTy, (int)plane, BlockWidth>( si, x, y); return temp.template select<m, 1, N, 1>(0, 0); } else { return __esimd_media_ld<T, m, N, Mod, SurfIndTy, (int)plane, BlockWidth>( si, x, y); } } /// Media block store. /// /// @tparam T is the element data type. /// @tparam m is the height of the 2D block. /// @tparam N is the width of the 2D block. /// @tparam is AccessorTy type of the SYCL accessor. /// @tparam plane is planar surface index. /// @param acc is the SYCL accessor. /// @param x is X-coordinate of the left upper rectangle corner in BYTES. /// @param y is Y-coordinate of the left upper rectangle corner in ROWS. /// @param vals is the linearized 2D block data to be written to surface. /// template <typename T, int m, int N, typename AccessorTy, unsigned plane = 0> __ESIMD_API void media_block_store(AccessorTy acc, unsigned x, unsigned y, simd<T, m * N> vals) { constexpr unsigned Width = N * sizeof(T); static_assert(Width * m <= 256u, "data does not fit into a single dataport transaction"); static_assert(Width <= 64u, "valid block width is in range [1, 64]"); static_assert(m <= 64u, "valid block height is in range [1, 64]"); static_assert(plane <= 3u, "valid plane index is in range [0, 3]"); const auto si = __ESIMD_GET_SURF_HANDLE(acc); using SurfIndTy = decltype(si); constexpr unsigned int RoundedWidth = Width < 4 ? 4 : detail::getNextPowerOf2<Width>(); constexpr unsigned int n1 = RoundedWidth / sizeof(T); constexpr int BlockWidth = sizeof(T) * N; constexpr int Mod = 0; if constexpr (Width < RoundedWidth) { simd<T, m * n1> temp; auto temp_ref = temp.template bit_cast_view<T, m, n1>(); auto vals_ref = vals.template bit_cast_view<T, m, N>(); temp_ref.template select<m, 1, N, 1>() = vals_ref; __esimd_media_st<T, m, n1, Mod, SurfIndTy, plane, BlockWidth>(si, x, y, temp.data()); } else { __esimd_media_st<T, m, N, Mod, SurfIndTy, plane, BlockWidth>(si, x, y, vals.data()); } } /// @} sycl_esimd_memory /// @addtogroup sycl_esimd_raw_send /// @{ /// Raw sends load. "s" suffix designates "split" variant - i.e. two sources. /// /// @param msgDst is the old value of the destination operand. /// @param msgSrc0 is the first source operand of send message. /// @param msgSrc1 is the second source operand of send message. /// @param exDesc is the extended message descriptor. /// @param msgDesc is the message descriptor. /// @param execSize is the execution size, which must be a compile time /// constant. /// @param sfid is the shared function ID, which must be a compile time /// constant. /// @param numSrc0 is the number of GRFs for source-0, which must be a compile /// time constant. /// @param numSrc1 is the number of GRFs for source-1, which must be a compile /// constant. /// @param numDst is the number of GRFs for destination, which must be a compile /// time constant. /// @param isEOT is the flag that indicates whether this is an EOT message, /// which must be a compile time constant (optional - default to 0). /// @param isSendc is the flag that indicates whether sendc should be used, /// which must be a compile time constant (optional - default to 0). /// @param mask is the predicate to specify enabled channels (optional - default /// to on). /// @return the vector value read from memory. template <typename T1, int n1, typename T2, int n2, typename T3, int n3, int N = 16> __ESIMD_API simd<T1, n1> raw_sends_load(simd<T1, n1> msgDst, simd<T2, n2> msgSrc0, simd<T3, n3> msgSrc1, uint32_t exDesc, uint32_t msgDesc, uint8_t execSize, uint8_t sfid, uint8_t numSrc0, uint8_t numSrc1, uint8_t numDst, uint8_t isEOT = 0, uint8_t isSendc = 0, simd_mask<N> mask = 1) { constexpr unsigned _Width1 = n1 * sizeof(T1); static_assert(_Width1 % 32 == 0, "Invalid size for raw send rspVar"); constexpr unsigned _Width2 = n2 * sizeof(T2); static_assert(_Width2 % 32 == 0, "Invalid size for raw send msgSrc0"); constexpr unsigned _Width3 = n3 * sizeof(T3); static_assert(_Width3 % 32 == 0, "Invalid size for raw send msgSrc1"); uint8_t modifier = ((isEOT & 0x1) << 1) | (isSendc & 0x1); return __esimd_raw_sends2<T1, n1, T2, n2, T3, n3, N>( modifier, execSize, mask.data(), numSrc0, numSrc1, numDst, sfid, exDesc, msgDesc, msgSrc0.data(), msgSrc1.data(), msgDst.data()); } /// Raw send load. /// /// @param msgDst is the old value of the destination operand. /// @param msgSrc0 is the first source operand of send message. /// @param exDesc is the extended message descriptor. /// @param msgDesc is the message descriptor. /// @param execSize is the execution size, which must be a compile time /// constant. /// @param sfid is the shared function ID, which must be a compile time /// constant. /// @param numSrc0 is the number of GRFs for source-0, which must be a compile /// time constant. /// @param numDst is the number of GRFs for destination, which must be a compile /// time constant. /// @param isEOT is the flag that indicates whether this is an EOT message, /// which must be a compile time constant (optional - default to 0). /// @param isSendc is the flag that indicates whether sendc should be used, /// which must be a compile time constant (optional - default to 0). /// @param mask is the predicate to specify enabled channels (optional - default /// to on). /// @return the vector value read from memory. template <typename T1, int n1, typename T2, int n2, int N = 16> __ESIMD_API simd<T1, n1> raw_send_load(simd<T1, n1> msgDst, simd<T2, n2> msgSrc0, uint32_t exDesc, uint32_t msgDesc, uint8_t execSize, uint8_t sfid, uint8_t numSrc0, uint8_t numDst, uint8_t isEOT = 0, uint8_t isSendc = 0, simd_mask<N> mask = 1) { constexpr unsigned _Width1 = n1 * sizeof(T1); static_assert(_Width1 % 32 == 0, "Invalid size for raw send rspVar"); constexpr unsigned _Width2 = n2 * sizeof(T2); static_assert(_Width2 % 32 == 0, "Invalid size for raw send msgSrc0"); uint8_t modifier = ((isEOT & 0x1) << 1) | (isSendc & 0x1); return __esimd_raw_send2<T1, n1, T2, n2, N>( modifier, execSize, mask.data(), numSrc0, numDst, sfid, exDesc, msgDesc, msgSrc0.data(), msgDst.data()); } /// Raw sends store. "s" suffix designates "split" variant - i.e. two sources. /// /// @param msgSrc0 is the first source operand of send message. /// @param msgSrc1 is the second source operand of send message. /// @param exDesc is the extended message descriptor. /// @param msgDesc is the message descriptor. /// @param execSize is the execution size, which must be a compile time /// constant. /// @param sfid is the shared function ID, which must be a compile time /// constant. /// @param numSrc0 is the number of GRFs for source-0, which must be a compile /// time constant. /// @param numSrc1 is the number of GRFs for source-1, which must be a compile /// time constant. /// @param isEOT is the flag that indicates whether this is an EOT message, /// which must be a compile time constant (optional - default to 0). /// @param isSendc is the flag that indicates whether sendc should be used, /// which must be a compile time constant (optional - default to 0). /// @param mask is the predicate to specify enabled channels (optional - default /// to on). template <typename T1, int n1, typename T2, int n2, int N = 16> __ESIMD_API void raw_sends_store(simd<T1, n1> msgSrc0, simd<T2, n2> msgSrc1, uint32_t exDesc, uint32_t msgDesc, uint8_t execSize, uint8_t sfid, uint8_t numSrc0, uint8_t numSrc1, uint8_t isEOT = 0, uint8_t isSendc = 0, simd_mask<N> mask = 1) { constexpr unsigned _Width1 = n1 * sizeof(T1); static_assert(_Width1 % 32 == 0, "Invalid size for raw send msgSrc0"); constexpr unsigned _Width2 = n2 * sizeof(T2); static_assert(_Width2 % 32 == 0, "Invalid size for raw send msgSrc1"); uint8_t modifier = ((isEOT & 0x1) << 1) | (isSendc & 0x1); __esimd_raw_sends2_noresult<T1, n1, T2, n2, N>( modifier, execSize, mask.data(), numSrc0, numSrc1, sfid, exDesc, msgDesc, msgSrc0.data(), msgSrc1.data()); } /// Raw send store. Generates a \c send or \c sendc instruction for the message /// gateway. /// /// @param msgSrc0 is the first source operand of send message. /// @param exDesc is the extended message descriptor. /// @param msgDesc is the message descriptor. /// @param execSize is the execution size, which must be a compile time /// constant. /// @param sfid is the shared function ID, which must be a compile time /// constant. /// @param numSrc0 is the number of GRFs for source-0, which must be a compile /// time constant. /// @param isEOT is the flag that indicates whether this is an EOT message, /// which must be a compile time constant (optional - default to 0). /// @param isSendc is the flag that indicates whether sendc should be used, /// which must be a compile time constant (optional - default to 0). /// @param mask is the predicate to specify enabled channels (optional - default /// to on). template <typename T1, int n1, int N = 16> __ESIMD_API void raw_send_store(simd<T1, n1> msgSrc0, uint32_t exDesc, uint32_t msgDesc, uint8_t execSize, uint8_t sfid, uint8_t numSrc0, uint8_t isEOT = 0, uint8_t isSendc = 0, simd_mask<N> mask = 1) { constexpr unsigned _Width1 = n1 * sizeof(T1); static_assert(_Width1 % 32 == 0, "Invalid size for raw send msgSrc0"); uint8_t modifier = ((isEOT & 0x1) << 1) | (isSendc & 0x1); __esimd_raw_send2_noresult<T1, n1, N>(modifier, execSize, mask.data(), numSrc0, sfid, exDesc, msgDesc, msgSrc0.data()); } /// @} sycl_esimd_raw_send /// @defgroup sycl_esimd_memory_nbarrier Named barrier APIs. /// @ingroup sycl_esimd_memory /// @addtogroup sycl_esimd_memory_nbarrier /// @{ /// Wait on a named barrier /// Available only on PVC /// /// @param id - named barrier id __ESIMD_API void nbarrier_wait(uint8_t id) { __esimd_nbarrier(0 /*wait*/, id, 0 /*thread count*/); } /// Initialize number of named barriers for a kernel /// Available only on PVC /// /// @tparam NbarCount - number of named barriers template <uint8_t NbarCount> __ESIMD_API void nbarrier_init() { __esimd_nbarrier_init(NbarCount); } /// Perform signal operation for the given named barrier /// Available only on PVC /// /// @param barrier_id - named barrier id /// /// @param producer_consumer_mode - 2-bit flag to indicate if it's producer /// mode (0x1) or consumer mode (0x2). User must ensure the input value is set /// correctly and higher order bits are cleared. /// /// @param num_producers - number of producers /// /// @param num_consumers - number of consumers __ESIMD_API void nbarrier_signal(uint8_t barrier_id, uint8_t producer_consumer_mode, uint32_t num_producers, uint32_t num_consumers) { constexpr uint32_t gateway = 3; constexpr uint32_t barrier = 4; constexpr uint32_t descriptor = 1 << 25 | // Message length: 1 register 0 << 12 | // Fence Data Ports: No fence barrier; // Barrier subfunction detail::vector_type_t<uint32_t, 8> payload = 0; payload[2] = (num_consumers & 0xff) << 24 | (num_producers & 0xff) << 16 | producer_consumer_mode << 14 | (barrier_id & 0b11111) << 0; __esimd_raw_send_nbarrier_signal<uint32_t, 8>( 0 /*sendc*/, gateway, descriptor, payload, 1 /*pred*/); } /// @} sycl_esimd_memory_nbarrier #undef __ESIMD_GET_SURF_HANDLE /// @cond EXCLUDE namespace detail { // ----- Outlined implementations of simd_obj_impl class memory access APIs. template <typename T, int N, class T1, class SFINAE> template <typename Flags, int ChunkSize, typename> void simd_obj_impl<T, N, T1, SFINAE>::copy_from( const simd_obj_impl<T, N, T1, SFINAE>::element_type *Addr, Flags) SYCL_ESIMD_FUNCTION { using UT = simd_obj_impl<T, N, T1, SFINAE>::element_type; constexpr unsigned Size = sizeof(T) * N; constexpr unsigned Align = Flags::template alignment<T1>; constexpr unsigned BlockSize = OperandSize::OWORD * 8; constexpr unsigned NumBlocks = Size / BlockSize; constexpr unsigned RemSize = Size % BlockSize; if constexpr (Align >= OperandSize::DWORD && Size % OperandSize::OWORD == 0 && detail::isPowerOf2(RemSize / OperandSize::OWORD)) { if constexpr (NumBlocks > 0) { constexpr unsigned BlockN = BlockSize / sizeof(T); ForHelper<NumBlocks>::unroll([BlockN, Addr, this](unsigned Block) { select<BlockN, 1>(Block * BlockN) = block_load<UT, BlockN, Flags>(Addr + (Block * BlockN), Flags{}); }); } if constexpr (RemSize > 0) { constexpr unsigned RemN = RemSize / sizeof(T); constexpr unsigned BlockN = BlockSize / sizeof(T); select<RemN, 1>(NumBlocks * BlockN) = block_load<UT, RemN, Flags>(Addr + (NumBlocks * BlockN), Flags{}); } } else if constexpr (sizeof(T) == 8) { simd<int32_t, N * 2> BC(reinterpret_cast<const int32_t *>(Addr), Flags{}); bit_cast_view<int32_t>() = BC; } else { constexpr unsigned NumChunks = N / ChunkSize; if constexpr (NumChunks > 0) { simd<uint32_t, ChunkSize> Offsets(0u, sizeof(T)); ForHelper<NumChunks>::unroll([Addr, &Offsets, this](unsigned Block) { select<ChunkSize, 1>(Block * ChunkSize) = gather<UT, ChunkSize>(Addr + (Block * ChunkSize), Offsets); }); } constexpr unsigned RemN = N % ChunkSize; if constexpr (RemN > 0) { if constexpr (RemN == 1) { select<1, 1>(NumChunks * ChunkSize) = Addr[NumChunks * ChunkSize]; } else if constexpr (RemN == 8 || RemN == 16) { simd<uint32_t, RemN> Offsets(0u, sizeof(T)); select<RemN, 1>(NumChunks * ChunkSize) = gather<UT, RemN>(Addr + (NumChunks * ChunkSize), Offsets); } else { constexpr int N1 = RemN < 8 ? 8 : RemN < 16 ? 16 : 32; simd_mask_type<N1> Pred(0); Pred.template select<RemN, 1>() = 1; simd<uint32_t, N1> Offsets(0u, sizeof(T)); simd<UT, N1> Vals = gather<UT, N1>(Addr + (NumChunks * ChunkSize), Offsets, Pred); select<RemN, 1>(NumChunks * ChunkSize) = Vals.template select<RemN, 1>(); } } } } template <typename T, int N, class T1, class SFINAE> template <typename AccessorT, typename Flags, int ChunkSize, typename> ESIMD_INLINE EnableIfAccessor<AccessorT, accessor_mode_cap::can_read, sycl::access::target::global_buffer, void> simd_obj_impl<T, N, T1, SFINAE>::copy_from(AccessorT acc, uint32_t offset, Flags) SYCL_ESIMD_FUNCTION { using UT = simd_obj_impl<T, N, T1, SFINAE>::element_type; static_assert(sizeof(UT) == sizeof(T)); constexpr unsigned Size = sizeof(T) * N; constexpr unsigned Align = Flags::template alignment<T1>; constexpr unsigned BlockSize = OperandSize::OWORD * 8; constexpr unsigned NumBlocks = Size / BlockSize; constexpr unsigned RemSize = Size % BlockSize; if constexpr (Align >= OperandSize::DWORD && Size % OperandSize::OWORD == 0 && detail::isPowerOf2(RemSize / OperandSize::OWORD)) { if constexpr (NumBlocks > 0) { constexpr unsigned BlockN = BlockSize / sizeof(T); ForHelper<NumBlocks>::unroll([BlockN, acc, offset, this](unsigned Block) { select<BlockN, 1>(Block * BlockN) = block_load<UT, BlockN, AccessorT, Flags>( acc, offset + (Block * BlockSize), Flags{}); }); } if constexpr (RemSize > 0) { constexpr unsigned RemN = RemSize / sizeof(T); constexpr unsigned BlockN = BlockSize / sizeof(T); select<RemN, 1>(NumBlocks * BlockN) = block_load<UT, RemN, AccessorT, Flags>( acc, offset + (NumBlocks * BlockSize), Flags{}); } } else if constexpr (sizeof(T) == 8) { simd<int32_t, N * 2> BC(acc, offset, Flags{}); bit_cast_view<int32_t>() = BC; } else { constexpr unsigned NumChunks = N / ChunkSize; if constexpr (NumChunks > 0) { simd<uint32_t, ChunkSize> Offsets(0u, sizeof(T)); ForHelper<NumChunks>::unroll( [acc, offset, &Offsets, this](unsigned Block) { select<ChunkSize, 1>(Block * ChunkSize) = gather<UT, ChunkSize, AccessorT>( acc, Offsets, offset + (Block * ChunkSize * sizeof(T))); }); } constexpr unsigned RemN = N % ChunkSize; if constexpr (RemN > 0) { if constexpr (RemN == 1 || RemN == 8 || RemN == 16) { simd<uint32_t, RemN> Offsets(0u, sizeof(T)); select<RemN, 1>(NumChunks * ChunkSize) = gather<UT, RemN, AccessorT>( acc, Offsets, offset + (NumChunks * ChunkSize * sizeof(T))); } else { constexpr int N1 = RemN < 8 ? 8 : RemN < 16 ? 16 : 32; simd_mask_type<N1> Pred(0); Pred.template select<RemN, 1>() = 1; simd<uint32_t, N1> Offsets(0u, sizeof(T)); simd<UT, N1> Vals = gather<UT, N1>( acc, Offsets, offset + (NumChunks * ChunkSize * sizeof(T)), Pred); select<RemN, 1>(NumChunks * ChunkSize) = Vals.template select<RemN, 1>(); } } } } template <typename T, int N, class T1, class SFINAE> template <typename Flags, int ChunkSize, typename> void simd_obj_impl<T, N, T1, SFINAE>::copy_to( simd_obj_impl<T, N, T1, SFINAE>::element_type *Addr, Flags) const SYCL_ESIMD_FUNCTION { using UT = simd_obj_impl<T, N, T1, SFINAE>::element_type; constexpr unsigned Size = sizeof(T) * N; constexpr unsigned Align = Flags::template alignment<T1>; constexpr unsigned BlockSize = OperandSize::OWORD * 8; constexpr unsigned NumBlocks = Size / BlockSize; constexpr unsigned RemSize = Size % BlockSize; simd<UT, N> Tmp{data()}; if constexpr (Align >= OperandSize::OWORD && Size % OperandSize::OWORD == 0 && detail::isPowerOf2(RemSize / OperandSize::OWORD)) { if constexpr (NumBlocks > 0) { constexpr unsigned BlockN = BlockSize / sizeof(T); ForHelper<NumBlocks>::unroll([BlockN, Addr, &Tmp](unsigned Block) { block_store<UT, BlockN>(Addr + (Block * BlockN), Tmp.template select<BlockN, 1>(Block * BlockN)); }); } if constexpr (RemSize > 0) { constexpr unsigned RemN = RemSize / sizeof(T); constexpr unsigned BlockN = BlockSize / sizeof(T); block_store<UT, RemN>(Addr + (NumBlocks * BlockN), Tmp.template select<RemN, 1>(NumBlocks * BlockN)); } } else if constexpr (sizeof(T) == 8) { simd<int32_t, N * 2> BC = Tmp.template bit_cast_view<int32_t>(); BC.copy_to(reinterpret_cast<int32_t *>(Addr), Flags{}); } else { constexpr unsigned NumChunks = N / ChunkSize; if constexpr (NumChunks > 0) { simd<uint32_t, ChunkSize> Offsets(0u, sizeof(T)); ForHelper<NumChunks>::unroll([Addr, &Offsets, &Tmp](unsigned Block) { scatter<UT, ChunkSize>( Addr + (Block * ChunkSize), Offsets, Tmp.template select<ChunkSize, 1>(Block * ChunkSize)); }); } constexpr unsigned RemN = N % ChunkSize; if constexpr (RemN > 0) { if constexpr (RemN == 1) { Addr[NumChunks * ChunkSize] = Tmp[NumChunks * ChunkSize]; } else if constexpr (RemN == 8 || RemN == 16) { simd<uint32_t, RemN> Offsets(0u, sizeof(T)); scatter<UT, RemN>(Addr + (NumChunks * ChunkSize), Offsets, Tmp.template select<RemN, 1>(NumChunks * ChunkSize)); } else { constexpr int N1 = RemN < 8 ? 8 : RemN < 16 ? 16 : 32; simd_mask_type<N1> Pred(0); Pred.template select<RemN, 1>() = 1; simd<UT, N1> Vals; Vals.template select<RemN, 1>() = Tmp.template select<RemN, 1>(NumChunks * ChunkSize); simd<uint32_t, N1> Offsets(0u, sizeof(T)); scatter<UT, N1>(Addr + (NumChunks * ChunkSize), Offsets, Vals, Pred); } } } } template <typename T, int N, class T1, class SFINAE> template <typename AccessorT, typename Flags, int ChunkSize, typename> ESIMD_INLINE EnableIfAccessor<AccessorT, accessor_mode_cap::can_write, sycl::access::target::global_buffer, void> simd_obj_impl<T, N, T1, SFINAE>::copy_to(AccessorT acc, uint32_t offset, Flags) const SYCL_ESIMD_FUNCTION { using UT = simd_obj_impl<T, N, T1, SFINAE>::element_type; constexpr unsigned Size = sizeof(T) * N; constexpr unsigned Align = Flags::template alignment<T1>; constexpr unsigned BlockSize = OperandSize::OWORD * 8; constexpr unsigned NumBlocks = Size / BlockSize; constexpr unsigned RemSize = Size % BlockSize; simd<UT, N> Tmp{data()}; if constexpr (Align >= OperandSize::OWORD && Size % OperandSize::OWORD == 0 && detail::isPowerOf2(RemSize / OperandSize::OWORD)) { if constexpr (NumBlocks > 0) { constexpr unsigned BlockN = BlockSize / sizeof(T); ForHelper<NumBlocks>::unroll([BlockN, acc, offset, &Tmp](unsigned Block) { block_store<UT, BlockN, AccessorT>( acc, offset + (Block * BlockSize), Tmp.template select<BlockN, 1>(Block * BlockN)); }); } if constexpr (RemSize > 0) { constexpr unsigned RemN = RemSize / sizeof(T); constexpr unsigned BlockN = BlockSize / sizeof(T); block_store<UT, RemN, AccessorT>( acc, offset + (NumBlocks * BlockSize), Tmp.template select<RemN, 1>(NumBlocks * BlockN)); } } else if constexpr (sizeof(T) == 8) { simd<int32_t, N * 2> BC = Tmp.template bit_cast_view<int32_t>(); BC.copy_to(acc, offset, Flags{}); } else { constexpr unsigned NumChunks = N / ChunkSize; if constexpr (NumChunks > 0) { simd<uint32_t, ChunkSize> Offsets(0u, sizeof(T)); ForHelper<NumChunks>::unroll([acc, offset, &Offsets, &Tmp](unsigned Block) { scatter<UT, ChunkSize, AccessorT>( acc, Offsets, Tmp.template select<ChunkSize, 1>(Block * ChunkSize), offset + (Block * ChunkSize * sizeof(T))); }); } constexpr unsigned RemN = N % ChunkSize; if constexpr (RemN > 0) { if constexpr (RemN == 1 || RemN == 8 || RemN == 16) { simd<uint32_t, RemN> Offsets(0u, sizeof(T)); scatter<UT, RemN, AccessorT>( acc, Offsets, Tmp.template select<RemN, 1>(NumChunks * ChunkSize), offset + (NumChunks * ChunkSize * sizeof(T))); } else { constexpr int N1 = RemN < 8 ? 8 : RemN < 16 ? 16 : 32; simd_mask_type<N1> Pred(0); Pred.template select<RemN, 1>() = 1; simd<UT, N1> Vals; Vals.template select<RemN, 1>() = Tmp.template select<RemN, 1>(NumChunks * ChunkSize); simd<uint32_t, N1> Offsets(0u, sizeof(T)); scatter<UT, N1, AccessorT>(acc, Offsets, Vals, offset + (NumChunks * ChunkSize * sizeof(T)), Pred); } } } } } // namespace detail /// @endcond EXCLUDE } // namespace esimd } // namespace experimental } // namespace intel } // namespace ext } // namespace sycl } // __SYCL_INLINE_NAMESPACE(cl)
43.123077
80
0.65583
[ "object", "vector" ]
13129aa45affdd81abef89c1f9efdea06c82c65d
13,865
cpp
C++
nGram.cpp
vlee489/AC21008-Assignment-3
054327a5720efc3cdeb19111917860c92e75dab5
[ "MIT" ]
null
null
null
nGram.cpp
vlee489/AC21008-Assignment-3
054327a5720efc3cdeb19111917860c92e75dab5
[ "MIT" ]
null
null
null
nGram.cpp
vlee489/AC21008-Assignment-3
054327a5720efc3cdeb19111917860c92e75dab5
[ "MIT" ]
null
null
null
// // Created by Vincent Lee on 15/11/2019. // #include <iostream> #include <string> #include <fstream> #include <list> #include <vector> #include <sstream> #include "HashTable.h" using namespace std; typedef HashTable<string, int> HTSI; HTSI hashTable; /** * This is a more effiecent version of the print code * 8X more effiecent. * prints what's ever in the hashtable out * in the output stated in brief * @param k top x values to show */ void printToDisplayV2(int k){ int highestValue = 0; int printCounter = k; int totalValues = 0; vector<int> vectorLocations; // Used to check the requested amount to display isn't above the number of values in hashtable int totalEntriesInHashTable = hashTable.getNum(); if (printCounter > totalEntriesInHashTable) { printCounter = totalEntriesInHashTable; } // forms a list of all locations with a key/value pair in vector // and works out the largest value. for (int id = 0; id < hashTable.size(); id++) { if (hashTable.getIfFilledAtVector(id)) { vectorLocations.push_back(id); totalValues += hashTable.getValueAtVector(id); if (hashTable.getValueAtVector(id) > highestValue) { highestValue = hashTable.getValueAtVector(id); } } } while(printCounter > 0){ for (int &item : vectorLocations) { if(printCounter <= 0){ return; } if (hashTable.getValueAtVector(item) == highestValue) { float frequencyPercentage = (((float) hashTable.getValueAtVector(item) / (float) totalValues) *100); printf("%.2f", frequencyPercentage); cout << ":" << hashTable.getKeyAtVector(item) << endl; printCounter--; } } highestValue--; } } /** * nGram for chars * @param txtFile The text file to read from * @param n the number of items that form an N-gram, * @param k the number of top most frequent n-grams to output * @return 0 for success / error code */ int nChar(const string &txtFile, int n, int k) { if (n <= 0 || k <= 0) { cout << "Int pram out of accepted range" << endl; return 3; } // Holds vars for input string nGram; string inputString; char letter; int count = 0; ifstream reader(txtFile); if (!reader) { cout << "Error opening input file" << endl; return 1; } // Gets the count of the number of letters // and forms a string while (reader.get(letter)) { count++; if (letter == ' ') { inputString += '_'; } else if (letter != '\n') { inputString += letter; } } if (count < n) { cout << "not enough input to created desired length of nGram" << endl; return 10; } int iteratorAmount = (count - n); // stores the number of times we need to go through the file for the nchar int iterator = 0; int fromChar = -1; int toChar = n; int nGramLength = 0; for (int i = 0; i < iteratorAmount; i++) { for (char &l : inputString) { iterator++; //forms the nGram if (iterator > fromChar && iterator < toChar) { nGramLength++; nGram += l; } //Has formed the nGram if (nGramLength == n) { if (hashTable.doesContain(nGram)) { // if nGram is already in table int newValue = hashTable.getValue(nGram) + 1; // stores new value hashTable.erase(nGram); try { hashTable.insert(nGram, newValue); } catch (...) { cout << "Error inserting: " << nGram << endl; } } else {// if nGram isn't in table try { hashTable.insert(nGram, 1); } catch (...) { cout << "Error inserting: " << nGram << endl; } } break; } } // reset variable used for each nGram iterator = 0; nGram = ""; nGramLength = 0; // Set char to move up one char in list; fromChar++; toChar++; } reader.close(); printToDisplayV2(k); return 0; } int nCharV2(const string &txtFile, int n, int k) { if (n <= 0 || k <= 0) { cout << "Int pram out of accepted range" << endl; return 3; } // Holds vars for input string nGram; string inputString; char letter; int count = 0; ifstream reader(txtFile); if (!reader) { cout << "Error opening input file" << endl; return 1; } // Gets the count of the number of letters // and forms a string while (reader.get(letter)) { if (letter == ' ') { inputString += '_'; count++; } else if (letter != '\n') { inputString += letter; count++; } } vector<char> vectorOfChar; for(char &l : inputString){ vectorOfChar.push_back(l); } if (count < n) { cout << "not enough input to created desired length of nGram" << endl; return 10; } int iteratorAmount = ((count - n)+1); // stores the number of times we need to go through the file for the nchar int fromChar = 0; int toChar = n; for (int i = 0; i < iteratorAmount; i++) { for (int x = fromChar; x < toChar; x++) { // sanity check the int is in range if (x >= (int) vectorOfChar.size()) { cout << "nGram assembled has gone out of range of the vector containing Ints" << endl; return 10; } nGram += vectorOfChar[x]; } if (hashTable.doesContain(nGram)) { // if nGram is already in table int newValue = hashTable.getValue(nGram) + 1; // stores new value hashTable.erase(nGram); try { hashTable.insert(nGram, newValue); } catch (...) { cout << "Error inserting: " << nGram << endl; } } else {// if nGram isn't in table try { hashTable.insert(nGram, 1); } catch (...) { cout << "Error inserting: " << nGram << endl; } } nGram = ""; toChar++; fromChar++; } reader.close(); printToDisplayV2(k); return 0; } /** * nGram for Words * @param txtFile The text file to read from * @param n the number of items that form an N-gram, * @param k the number of top most frequent n-grams to output * @return 0 for success / error code */ int nWord(const string &txtFile, int n, int k) { if (n <= 0 || k <= 0) { cout << "Int pram out of accepted range" << endl; return 3; } ifstream reader(txtFile); if (!reader) { cout << "Error opening input file" << endl; return 1; } string inputString; char letter; // Following bool is used to avoid double spaces // That can break the nWord processing bool justPlacedSpace = false; while (reader.get(letter)) { if (letter == '.') { if (!justPlacedSpace) { inputString += ' '; justPlacedSpace = true; } } else if (letter == ',') { if (!justPlacedSpace) { inputString += ' '; justPlacedSpace = true; } } else if (letter == '!') { if (!justPlacedSpace) { inputString += ' '; justPlacedSpace = true; } } else if (letter == '?') { if (!justPlacedSpace) { inputString += ' '; justPlacedSpace = true; } } else if (letter == ' ') { if (!justPlacedSpace) { inputString += ' '; justPlacedSpace = true; } } else if (letter == '"') { if (!justPlacedSpace) { inputString += ' '; justPlacedSpace = true; } } else if (letter != '\n') { inputString += letter; justPlacedSpace = false; } } // Places each word into a location in the vector vector<string> wordList; stringstream ss(inputString); string vectorWord; int count = 0; while (getline(ss, vectorWord, ' ')) { wordList.push_back(vectorWord); count++; } reader.close(); if (count < n) { cout << "not enough input to created desired length of nGram" << endl; return 10; } int iteratorAmount = (count - n) + 1; // stores the number of times we need to go through the file for the nchar int fromWord = 0; int toWord = n; string nGram; for (int i = 0; i < iteratorAmount; i++) { for (int x = fromWord; x < toWord; x++) { // sanity check the int is in range if (x >= (int) wordList.size()) { cout << "nGram assembled has gone out of range of the vector containing words" << endl; return 10; } nGram += wordList[x]; nGram += ' '; } if (hashTable.doesContain(nGram)) { // if nGram is already in table int newValue = hashTable.getValue(nGram) + 1; hashTable.erase(nGram); try { hashTable.insert(nGram, newValue); } catch (...) { cout << "Error inserting: " << nGram << endl; } } else {// if nGram isn't in table try { hashTable.insert(nGram, 1); } catch (...) { cout << "Error inserting: " << nGram << endl; } } // reset variable used for each nGram nGram = ""; // Set char to move up one char in list; fromWord++; toWord++; } printToDisplayV2(k); return 0; } /** * nGram for Decimals * @param txtFile The text file to read from * @param n the number of items that form an N-gram, * @param k the number of top most frequent n-grams to output * @return 0 for success / error code */ int nDecimal(const string &txtFile, int n, int k) { if (n <= 0 || k <= 0) { cout << "Int pram out of accepted range" << endl; return 3; } ifstream reader(txtFile); if (!reader) { cout << "Error opening input file" << endl; return 1; } // Gets the count of the number of letters // and forms a string char letter; string inputString; while (reader.get(letter)) { //this if statment makes sure only numbers are taken in. if (letter == '1' || letter == '2' || letter == '3' || letter == '4' || letter == '5' || letter == '6' || letter == '7' || letter == '8' || letter == '9' || letter == '0') { inputString += letter; } } // This vector stores each int vector<int> intVector; int count = 0; for (char &c : inputString) { try { intVector.push_back((int) c); count++; } catch (...) { cout << "Failed to process char: " << "\"" << c << "\"" << endl; } } if (count < n) { cout << "not enough input to created desired length of nGram" << endl; return 10; } int iteratorAmount = (count - n) + 1; // stores the number of times we need to go through the file for the nchar int fromWord = 0; int toWord = n; string nGram; for (int i = 0; i < iteratorAmount; i++) { for (int x = fromWord; x < toWord; x++) { // sanity check the int is in range if (x >= (int) intVector.size()) { cout << "nGram assembled has gone out of range of the vector containing Ints" << endl; return 10; } nGram += (char) intVector[x]; } if (hashTable.doesContain(nGram)) { // if nGram is already in table int newValue = hashTable.getValue(nGram) + 1; hashTable.erase(nGram); try { hashTable.insert(nGram, newValue); } catch (...) { cout << "Error inserting: " << nGram << endl; } } else {// if nGram isn't in table try { hashTable.insert(nGram, 1); } catch (...) { cout << "Error inserting: " << nGram << endl; } } // reset variable used for each nGram nGram = ""; // Set char to move up one char in list; fromWord++; toWord++; } printToDisplayV2(k); return 0; } /** * Main method * @param argc Number arguments passed in via cmd * @param argv array of argument strings * @return error code/success code */ int main(int argc, char *argv[]) { int nSize; int kSize; if (argc == 1) { nCharV2("inputfile.txt", 3, 10); } else if (argc == 5) { string fileName = argv[1]; try { nSize = atoi(argv[2]); kSize = atoi(argv[3]); } catch (...) { cout << "Error parsing values for arguments as ints"; } string mode = argv[4]; if (mode == "word") { return nWord(fileName, nSize, kSize); } else if (mode == "char") { return nChar(fileName, nSize, kSize); } else if (mode == "decimal") { return nDecimal(fileName, nSize, kSize); } else { cout << "Invalid Pram Error" << endl; return 20; } } }
29.006276
116
0.504364
[ "vector" ]
131c6fd743de798ac784c9b493a66f32a7769af3
2,971
hpp
C++
video_e2e_sample/include/kuhn_munkres.hpp
intel-iot-devkit/concurrent-video-analytic-pipeline-optimzation-sample
38622b7b48e5414e14f0149ee280d5f9ecbe1ba8
[ "BSD-3-Clause" ]
38
2020-03-18T08:15:19.000Z
2022-03-02T17:32:05.000Z
video_e2e_sample/include/kuhn_munkres.hpp
intel-iot-devkit/concurrent-video-analytic-pipeline-optimzation-sample
38622b7b48e5414e14f0149ee280d5f9ecbe1ba8
[ "BSD-3-Clause" ]
7
2020-04-21T09:28:33.000Z
2022-02-23T01:11:34.000Z
video_e2e_sample/include/kuhn_munkres.hpp
intel-iot-devkit/concurrent-video-analytic-pipeline-optimzation-sample
38622b7b48e5414e14f0149ee280d5f9ecbe1ba8
[ "BSD-3-Clause" ]
9
2020-11-02T03:49:40.000Z
2021-11-24T08:36:38.000Z
// Copyright (C) 2018-2019 Intel Corporation // SPDX-License-Identifier: Apache-2.0 /******************************************************************************\ Copyright (c) 2005-2020, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \**********************************************************************************/ #pragma once #include "mot_core.hpp" #include <memory> #include <vector> /// /// \brief The KuhnMunkres class /// /// Solves the assignment problem. /// class KuhnMunkres { public: KuhnMunkres(); /// /// \brief Solves the assignment problem for given dissimilarity matrix. /// It returns a vector that where each element is a column index for /// corresponding row (e.g. result[0] stores optimal column index for very /// first row in the dissimilarity matrix). /// \param dissimilarity_matrix CV_32F dissimilarity matrix. /// \return Optimal column index for each row. -1 means that there is no /// column for row. /// std::vector<size_t> Solve(const cv::Mat &dissimilarity_matrix); private: static constexpr int kStar = 1; static constexpr int kPrime = 2; cv::Mat dm_; cv::Mat marked_; std::vector<cv::Point> points_; std::vector<int> is_row_visited_; std::vector<int> is_col_visited_; int n_; void TrySimpleCase(); bool CheckIfOptimumIsFound(); cv::Point FindUncoveredMinValPos(); void UpdateDissimilarityMatrix(float val); int FindInRow(int row, int what); int FindInCol(int col, int what); void Run(); };
42.442857
755
0.709525
[ "vector" ]
1332d5a46178cafe167fb80bb00a215778986ac2
73,794
cpp
C++
PrototypeEngine/src/opengl/PrototypeOpenglRenderer.cpp
o-micron/Prototype
5b9d60d9dd80e7c8a1a2b0aaf19c2d90c1814139
[ "Apache-2.0" ]
2
2021-08-19T17:15:49.000Z
2021-12-28T22:48:47.000Z
PrototypeEngine/src/opengl/PrototypeOpenglRenderer.cpp
o-micron/Prototype
5b9d60d9dd80e7c8a1a2b0aaf19c2d90c1814139
[ "Apache-2.0" ]
null
null
null
PrototypeEngine/src/opengl/PrototypeOpenglRenderer.cpp
o-micron/Prototype
5b9d60d9dd80e7c8a1a2b0aaf19c2d90c1814139
[ "Apache-2.0" ]
null
null
null
/// Copyright 2021 Omar Sherif Fathy /// /// 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 "PrototypeOpenglRenderer.h" #include "../core/PrototypeCameraSystem.h" #include "../core/PrototypeDatabase.h" #include "../core/PrototypeFrameBuffer.h" #include "../core/PrototypeInput.h" #include "../core/PrototypeMaterial.h" #include "../core/PrototypeMeshBuffer.h" #include "../core/PrototypePhysics.h" #include "../core/PrototypeProfiler.h" #include "../core/PrototypeScene.h" #include "../core/PrototypeSceneLayer.h" #include "../core/PrototypeSceneNode.h" #include "../core/PrototypeShaderBuffer.h" #include "../core/PrototypeShortcuts.h" #include "../core/PrototypeTextureBuffer.h" #include "PrototypeOpenglWindow.h" #include <PrototypeCommon/Algo.h> #include <PrototypeCommon/Logger.h> #include "../core/PrototypeEngine.h" #include "../core/PrototypeScene.h" #include <PrototypeTraitSystem/PrototypeTraitSystem.h> #define FMT_HEADER_ONLY #include <fmt/format.h> #include <fstream> #include <math.h> #define PROTOTYPE_REGISTER_PROFILER_FUNCTIONS() \ PrototypeEngineInternalApplication::profiler->addTimelineItem("PrototypeOpenglRenderer::update"); \ PrototypeEngineInternalApplication::profiler->setTimelineItemColor("PrototypeOpenglRenderer::update", \ { 0.498f, 0.235f, 0.552f, 1.0f }); \ PrototypeEngineInternalApplication::profiler->addTimelineItem("PrototypeOpenglRenderer::render3D"); \ PrototypeEngineInternalApplication::profiler->setTimelineItemColor("PrototypeOpenglRenderer::render3D", \ { 0.066f, 0.647f, 0.474f, 1.0f }); \ PrototypeEngineInternalApplication::profiler->addTimelineItem("PrototypeOpenglRenderer::render2D"); \ PrototypeEngineInternalApplication::profiler->setTimelineItemColor("PrototypeOpenglRenderer::render2D", \ { 0.223f, 0.411f, 0.674f, 1.0f }); \ PrototypeEngineInternalApplication::profiler->addTimelineItem("PrototypeOpenglRenderer::switchScenes"); \ PrototypeEngineInternalApplication::profiler->setTimelineItemColor("PrototypeOpenglRenderer::switchScenes", \ { 0.949f, 0.717f, 0.003f, 1.0f }); \ PrototypeEngineInternalApplication::profiler->addTimelineItem("PrototypeOpenglRenderer::scheduleRecordPass"); \ PrototypeEngineInternalApplication::profiler->setTimelineItemColor("PrototypeOpenglRenderer::scheduleRecordPass", \ { 0.905f, 0.247f, 0.454f, 1.0f }); \ PrototypeEngineInternalApplication::profiler->addTimelineItem("PrototypeOpenglRenderer::beginRecordPass"); \ PrototypeEngineInternalApplication::profiler->setTimelineItemColor("PrototypeOpenglRenderer::beginRecordPass", \ { 0.501f, 0.729f, 0.352f, 1.0f }); \ PrototypeEngineInternalApplication::profiler->addTimelineItem("PrototypeOpenglRenderer::endRecordPass"); \ PrototypeEngineInternalApplication::profiler->setTimelineItemColor("PrototypeOpenglRenderer::endRecordPass", \ { 0.901f, 0.513f, 0.062f, 1.0f }); \ PrototypeEngineInternalApplication::profiler->addTimelineItem("PrototypeOpenglRenderer::onMeshBufferGpuUpload"); \ PrototypeEngineInternalApplication::profiler->setTimelineItemColor("PrototypeOpenglRenderer::onMeshBufferGpuUpload", \ { 0.0f, 0.525f, 0.584f, 1.0f }); \ PrototypeEngineInternalApplication::profiler->addTimelineItem("PrototypeOpenglRenderer::onShaderBufferGpuUpload"); \ PrototypeEngineInternalApplication::profiler->setTimelineItemColor("PrototypeOpenglRenderer::onShaderBufferGpuUpload", \ { 0.811f, 0.109f, 0.564f, 1.0f }); \ PrototypeEngineInternalApplication::profiler->addTimelineItem("PrototypeOpenglRenderer::onTextureBufferGpuUpload"); \ PrototypeEngineInternalApplication::profiler->setTimelineItemColor("PrototypeOpenglRenderer::onTextureBufferGpuUpload", \ { 0.976f, 0.482f, 0.447f, 1.0f }); #define PROTOTYPE_REGISTER_PROFILER_FUNCTION_BEGIN() \ static auto profilerT1 = std::chrono::high_resolution_clock::now(); \ profilerT1 = std::chrono::high_resolution_clock::now(); #define PROTOTYPE_REGISTER_PROFILER_FUNCTION_END(NAME) \ static auto profilerT2 = std::chrono::high_resolution_clock::now(); \ profilerT2 = std::chrono::high_resolution_clock::now(); \ static u32 profilerDuration = 0; \ profilerDuration = std::chrono::duration_cast<std::chrono::microseconds>(profilerT2 - profilerT1).count(); \ PrototypeEngineInternalApplication::profiler->markTimelineItem(#NAME, profilerDuration); void PrototypeOpenglRenderer::onMaterialShaderUpdate(PglMaterial* material, PglShader* shader) { PrototypeAlgoCopyNewValues(shader->floatData, material->floatData); PrototypeAlgoCopyNewValues(shader->vec2Data, material->vec2Data); PrototypeAlgoCopyNewValues(shader->vec3Data, material->vec3Data); PrototypeAlgoCopyNewValues(shader->vec4Data, material->vec4Data); PrototypeAlgoCopyNewValues(shader->textureData, material->textureData); } PrototypeOpenglRenderer::PrototypeOpenglRenderer(PrototypeOpenglWindow* window) #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE : _editorSceneCamera({}) // , _editorPaintCamera({}) #else : _mainCamera({}) #endif , _window(window) , _fullscreenFramebuffer(nullptr) #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE , _ui(std::make_unique<PrototypeOpenglUI>()) #endif , _uiState(PrototypeUIState_None) , _needsRecord(true) {} bool PrototypeOpenglRenderer::init() { #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTIONS() #endif if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { PrototypeLogger::fatal("Couldn't load OpenGL Code"); return false; } for (auto& pair : PrototypeEngineInternalApplication::database->meshBuffers) { PrototypeMeshBuffer* meshBuffer = pair.second; mapPrototypeMeshBuffer(meshBuffer); } for (auto& pair : PrototypeEngineInternalApplication::database->shaderBuffers) { PrototypeShaderBuffer* shaderBuffer = pair.second; mapPrototypeShaderBuffer(shaderBuffer); } for (auto& pair : PrototypeEngineInternalApplication::database->textureBuffers) { PrototypeTextureBuffer* textureBuffer = pair.second; mapPrototypeTextureBuffer(textureBuffer); } for (auto& pair : PrototypeEngineInternalApplication::database->materials) { const std::string& name = pair.first; PrototypeMaterial* dbMaterial = pair.second; mapPrototypeMaterial(dbMaterial); } for (auto& pair : PrototypeEngineInternalApplication::database->framebuffers) { const std::string name = pair.first; PrototypeFrameBuffer* framebuffer = pair.second; if (_framebuffers.find(framebuffer->name()) != _framebuffers.end()) { continue; } auto shaderIt = _shaders.find(framebuffer->shader()); if (shaderIt == _shaders.end()) { continue; } auto fb = _framebuffersPool.newElement(); fb->name = name; fb->colorAttachments.resize(framebuffer->numColorAttachments()); PglUploadFramebufferFromData( shaderIt->second, fb, (i32)_window->_resolution.x, (i32)_window->_resolution.y, framebuffer->withDepthAttachment()); _framebuffers.insert({ framebuffer->name(), fb }); } #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE _ui->init(); #else _input = PROTOTYPE_NEW PrototypeInput(); _input->subscribeKeyForStreams(GLFW_KEY_W); _input->subscribeKeyForStreams(GLFW_KEY_S); _input->subscribeKeyForStreams(GLFW_KEY_D); _input->subscribeKeyForStreams(GLFW_KEY_A); _input->subscribeKeyForStreams(GLFW_KEY_I); _input->subscribeKeyForStreams(GLFW_KEY_K); _input->subscribeKeyForStreams(GLFW_KEY_UP); _input->subscribeKeyForStreams(GLFW_KEY_DOWN); _input->subscribeKeyForStreams(GLFW_KEY_RIGHT); _input->subscribeKeyForStreams(GLFW_KEY_LEFT); #endif // deferred auto deferredFramebufferIt = _framebuffers.find("deferred"); if (deferredFramebufferIt == _framebuffers.end()) { PrototypeLogger::fatal("Cannot run without deferred framebuffer"); } // gbuffer auto gbufferFramebufferIt = _framebuffers.find("gbuffer"); if (gbufferFramebufferIt == _framebuffers.end()) { PrototypeLogger::fatal("Cannot run without gbuffer framebuffer"); } // postprocessing auto postProcessingFramebufferIt = _framebuffers.find("postprocessing"); if (postProcessingFramebufferIt == _framebuffers.end()) { PrototypeLogger::fatal("Cannot run without postprocessing framebuffer"); } // final auto finalFramebufferIt = _framebuffers.find("final"); if (finalFramebufferIt == _framebuffers.end()) { PrototypeLogger::fatal("Cannot run without final framebuffer"); } switchScenes(PrototypeEngineInternalApplication::scene); // fullscreen fb auto fullscreenFramebufferIt = _framebuffers.find("fullscreen"); if (fullscreenFramebufferIt == _framebuffers.end()) { PrototypeLogger::fatal("Cannot run without framebuffer shaders"); } _fullscreenFramebuffer = fullscreenFramebufferIt->second; auto cube = _geometries.find("CUBE")->second; auto skyShader = _shaders.find("sky")->second; auto hdrShader = _shaders.find("hdr")->second; auto irradianceShader = _shaders.find("irradiance")->second; auto prefilterShader = _shaders.find("prefilter")->second; auto brdfShader = _shaders.find("brdf")->second; _skybox = std::make_shared<PglSkybox>(); PglUploadSkybox(cube, skyShader, hdrShader, irradianceShader, prefilterShader, brdfShader, _skybox.get()); #ifndef PROTOTYPE_ENGINE_DEVELOPMENT_MODE onWindowResize(_window->_resolution.x, _window->_resolution.y); #endif return true; } void PrototypeOpenglRenderer::deInit() { #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE _ui->deInit(); #else delete _input; #endif for (const auto& pair : _geometries) { PglReleaseMesh(pair.second); } _geometries.clear(); for (const auto& pair : _shaders) { PglReleaseShader(pair.second); } _shaders.clear(); for (const auto& pair : _textures) { PglReleaseTexture(pair.second); } _textures.clear(); for (const auto& pair : _framebuffers) { PglReleaseFramebuffer(pair.second); } _framebuffers.clear(); for (const auto& pair : _uniformBufferObjects) { PglReleaseUniformBufferObject(pair.second); } _uniformBufferObjects.clear(); _skybox.reset(); } bool PrototypeOpenglRenderer::update() { #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_BEGIN() #endif #if defined(PROTOTYPE_ENGINE_DEVELOPMENT_MODE) _ui->sceneView()->onUpdate(); #else _input->update(); f32 vehicleAcceleration = _input->fetchKeyNormalizedValue(GLFW_KEY_UP); f32 vehicleBrake = _input->fetchKeyNormalizedValue(GLFW_KEY_DOWN); f32 vehicleRight = _input->fetchKeyNormalizedValue(GLFW_KEY_RIGHT); f32 vehicleLeft = _input->fetchKeyNormalizedValue(GLFW_KEY_LEFT); f32 cameraForward = _input->fetchKeyNormalizedValue(GLFW_KEY_W); f32 cameraBackward = _input->fetchKeyNormalizedValue(GLFW_KEY_S); f32 cameraRight = _input->fetchKeyNormalizedValue(GLFW_KEY_D); f32 cameraLeft = _input->fetchKeyNormalizedValue(GLFW_KEY_A); f32 cameraUp = _input->fetchKeyNormalizedValue(GLFW_KEY_I); f32 cameraDown = _input->fetchKeyNormalizedValue(GLFW_KEY_K); auto vehicleObjets = PrototypeEngineInternalApplication::scene->fetchObjectsByTraits(PrototypeTraitTypeMaskTransform | PrototypeTraitTypeMaskVehicleChasis); for (auto& vehicleObject : vehicleObjets) { VehicleChasis* chasis = vehicleObject->getVehicleChasisTrait(); PrototypeEngineInternalApplication::physics->updateVehicleController( vehicleObject, vehicleAcceleration, vehicleBrake, vehicleRight - vehicleLeft); } Camera* cam = _mainCamera.object->getCameraTrait(); CameraSystemUpdateViewMatrix(cam, cameraLeft - cameraRight, cameraDown - cameraUp, cameraForward - cameraBackward); CameraSystemUpdateProjectionMatrix(cam); static glm::vec4 LightPosition; LightPosition = { 0.0f, 100.0f, 0.0f, _window->time() }; static glm::vec4 LightColor; LightColor = { 1.0f, 1.0f, 1.0f, 1.0f }; glBindBuffer(GL_UNIFORM_BUFFER, _mainCamera.ubo->id); glBufferSubData(GL_UNIFORM_BUFFER, 0, 64, &cam->viewMatrix()[0][0]); glBufferSubData(GL_UNIFORM_BUFFER, 64, 64, &cam->projectionMatrix()[0][0]); glBufferSubData(GL_UNIFORM_BUFFER, 128, 4, &cam->znear()); glBufferSubData(GL_UNIFORM_BUFFER, 132, 4, &cam->zfar()); glBufferSubData(GL_UNIFORM_BUFFER, 136, 8, &_window->_mouseDown.x); glBufferSubData(GL_UNIFORM_BUFFER, 144, 16, &LightPosition[0]); glBufferSubData(GL_UNIFORM_BUFFER, 160, 16, &LightColor[0]); glBindBuffer(GL_UNIFORM_BUFFER, 0); #endif #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_END(PrototypeOpenglRenderer::update) #endif return true; } bool PrototypeOpenglRenderer::render3D() { #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_BEGIN() #endif if (_uiState & PrototypeUIState_Iconified) return true; PglGeometry* cube = _geometries.find("CUBE")->second; glViewport(0, 0, (GLsizei)_window->_resolution.x, (GLsizei)_window->_resolution.y); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE PglCamera& camera = _editorSceneCamera; #else PglCamera& camera = _mainCamera; #endif PglFramebufferStartRecording3D(camera.deferredFramebuffer); #if 0 glDepthMask(GL_FALSE); glDepthFunc(GL_LEQUAL); glDisable(GL_CULL_FACE); glUseProgram(_skybox->skyShader->program); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, _skybox->skyTexture->id); glUniform1i(glGetUniformLocation(_skybox->skyShader->program, "t_sky"), 0); glUniformMatrix4fv(glGetUniformLocation(_skybox->skyShader->program, "View"), 1, 0, camera.viewMatrix); glUniformMatrix4fv(glGetUniformLocation(_skybox->skyShader->program, "Projection"), 1, 0, camera.projectionMatrix); glBindVertexArray(cube->vao); glDrawElements(GL_TRIANGLES, cube->indexCount, cube->type, 0); glBindVertexArray(0); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); glUseProgram(0); #endif glDepthMask(GL_TRUE); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); // glDepthFunc(GL_LEQUAL); for (PrototypeOpenglCommand* command : _commands) { command->dispatch(); } glDisable(GL_CULL_FACE); /*static auto lineShader = _shaders["ray"]; glUseProgram(lineShader->program); for () {}*/ PglFramebufferEndRecording(camera.deferredFramebuffer); // scene PglFramebufferStartRecording2D(camera.gbufferFramebuffer); glDepthMask(GL_FALSE); // glDepthFunc(GL_LEQUAL); PglFramebufferStartRendering(camera.deferredFramebuffer); // add skybox textures and View uniform !! { // values { for (auto& pair : camera.deferredFramebuffer->shader->floatData) { glUniform1fv( glGetUniformLocation(camera.deferredFramebuffer->shader->program, pair.first.c_str()), 1, &pair.second); } for (auto& pair : camera.deferredFramebuffer->shader->vec2Data) { glUniform2fv( glGetUniformLocation(camera.deferredFramebuffer->shader->program, pair.first.c_str()), 1, &pair.second[0]); } for (auto& pair : camera.deferredFramebuffer->shader->vec3Data) { glUniform3fv( glGetUniformLocation(camera.deferredFramebuffer->shader->program, pair.first.c_str()), 1, &pair.second[0]); } for (auto& pair : camera.deferredFramebuffer->shader->vec4Data) { glUniform4fv( glGetUniformLocation(camera.deferredFramebuffer->shader->program, pair.first.c_str()), 1, &pair.second[0]); } } size_t t = camera.deferredFramebuffer->colorAttachments.size(); // cube { glActiveTexture(GL_TEXTURE0 + t); glBindTexture(_skybox->skyTexture->target, _skybox->skyTexture->id); glUniform1i(glGetUniformLocation(camera.deferredFramebuffer->shader->program, "texSky"), t); } // irradaince ++t; { glActiveTexture(GL_TEXTURE0 + t); glBindTexture(_skybox->irradianceTexture->target, _skybox->irradianceTexture->id); glUniform1i(glGetUniformLocation(camera.deferredFramebuffer->shader->program, "texIrradiance"), t); } // prefilter ++t; { glActiveTexture(GL_TEXTURE0 + t); glBindTexture(_skybox->prefilterTexture->target, _skybox->prefilterTexture->id); glUniform1i(glGetUniformLocation(camera.deferredFramebuffer->shader->program, "texPrefilter"), t); } // brdf ++t; { glActiveTexture(GL_TEXTURE0 + t); glBindTexture(_skybox->brdfTexture->target, _skybox->brdfTexture->id); glUniform1i(glGetUniformLocation(camera.deferredFramebuffer->shader->program, "texBrdf"), t); } // depth ++t; { glActiveTexture(GL_TEXTURE0 + t); glBindTexture(camera.deferredFramebuffer->depthAttachment.target, camera.deferredFramebuffer->depthAttachment.id); glUniform1i(glGetUniformLocation(camera.deferredFramebuffer->shader->program, "texDepth"), t); } } PglFramebufferEndRendering(camera.deferredFramebuffer); // glDepthFunc(GL_LESS); glDepthMask(GL_TRUE); PglFramebufferEndRecording(camera.gbufferFramebuffer); // gbuffer PglFramebufferStartRecording2D(camera.postprocessingFramebuffer); glDepthMask(GL_FALSE); // glDepthFunc(GL_LEQUAL); PglFramebufferStartRendering(camera.gbufferFramebuffer); { // values { for (auto& pair : camera.gbufferFramebuffer->shader->floatData) { glUniform1fv( glGetUniformLocation(camera.gbufferFramebuffer->shader->program, pair.first.c_str()), 1, &pair.second); } for (auto& pair : camera.gbufferFramebuffer->shader->vec2Data) { glUniform2fv( glGetUniformLocation(camera.gbufferFramebuffer->shader->program, pair.first.c_str()), 1, &pair.second[0]); } for (auto& pair : camera.gbufferFramebuffer->shader->vec3Data) { glUniform3fv( glGetUniformLocation(camera.gbufferFramebuffer->shader->program, pair.first.c_str()), 1, &pair.second[0]); } for (auto& pair : camera.gbufferFramebuffer->shader->vec4Data) { glUniform4fv( glGetUniformLocation(camera.gbufferFramebuffer->shader->program, pair.first.c_str()), 1, &pair.second[0]); } } glActiveTexture(GL_TEXTURE0); glBindTexture(camera.gbufferFramebuffer->colorAttachments[0].target, camera.gbufferFramebuffer->colorAttachments[0].id); glUniform1i(glGetUniformLocation(camera.gbufferFramebuffer->shader->program, "tex0"), 0); } PglFramebufferEndRendering(camera.gbufferFramebuffer); // glDepthFunc(GL_LESS); glDepthMask(GL_TRUE); PglFramebufferEndRecording(camera.postprocessingFramebuffer); // post processing PglFramebufferStartRecording2D(camera.finalFramebuffer); glDepthMask(GL_FALSE); // glDepthFunc(GL_LEQUAL); PglFramebufferStartRendering(camera.postprocessingFramebuffer); { // values { for (auto& pair : camera.postprocessingFramebuffer->shader->floatData) { glUniform1fv( glGetUniformLocation(camera.postprocessingFramebuffer->shader->program, pair.first.c_str()), 1, &pair.second); } for (auto& pair : camera.postprocessingFramebuffer->shader->vec2Data) { glUniform2fv(glGetUniformLocation(camera.postprocessingFramebuffer->shader->program, pair.first.c_str()), 1, &pair.second[0]); } for (auto& pair : camera.postprocessingFramebuffer->shader->vec3Data) { glUniform3fv(glGetUniformLocation(camera.postprocessingFramebuffer->shader->program, pair.first.c_str()), 1, &pair.second[0]); } for (auto& pair : camera.postprocessingFramebuffer->shader->vec4Data) { glUniform4fv(glGetUniformLocation(camera.postprocessingFramebuffer->shader->program, pair.first.c_str()), 1, &pair.second[0]); } } glActiveTexture(GL_TEXTURE0); glBindTexture(camera.postprocessingFramebuffer->colorAttachments[0].target, camera.postprocessingFramebuffer->colorAttachments[0].id); glUniform1i(glGetUniformLocation(camera.postprocessingFramebuffer->shader->program, "tex0"), 0); } PglFramebufferEndRendering(camera.postprocessingFramebuffer); // glDepthFunc(GL_LESS); glDepthMask(GL_TRUE); PglFramebufferEndRecording(camera.finalFramebuffer); #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_END(PrototypeOpenglRenderer::render3D) #endif return true; } bool PrototypeOpenglRenderer::render2D() { #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_BEGIN() #endif #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE _ui->beginFrame(false); { _uiState = _ui->drawFrame(_editorSceneCamera.finalFramebuffer->colorAttachments[0].id, _editorSceneCamera.finalFramebuffer->colorAttachments[0].width, _editorSceneCamera.finalFramebuffer->colorAttachments[0].height); } _ui->endFrame(); #endif #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE PglFramebufferStartRecording2D(_fullscreenFramebuffer); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); _ui->render(0, 0, (i32)_window->_resolution.x, (i32)_window->_resolution.y); glDisable(GL_CULL_FACE); PglFramebufferEndRecording(_fullscreenFramebuffer); PglFramebufferStartRendering(_fullscreenFramebuffer); PglFramebufferEndRendering(_fullscreenFramebuffer); #else glEnable(GL_CULL_FACE); glCullFace(GL_BACK); PglFramebufferStartRendering(_mainCamera.finalFramebuffer); PglFramebufferEndRendering(_mainCamera.finalFramebuffer); glDisable(GL_CULL_FACE); #endif #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_END(PrototypeOpenglRenderer::render2D) #endif return true; } void PrototypeOpenglRenderer::switchScenes(PrototypeScene* scene) { #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_BEGIN() #endif PrototypeEngineInternalApplication::scene = scene; // deferred auto deferredFramebufferIt = _framebuffers.find("deferred"); if (deferredFramebufferIt == _framebuffers.end()) { PrototypeLogger::fatal("Cannot run without deferred framebuffer"); } // gbuffer auto gbufferFramebufferIt = _framebuffers.find("gbuffer"); if (gbufferFramebufferIt == _framebuffers.end()) { PrototypeLogger::fatal("Cannot run without gbuffer framebuffer"); } // postprocessing auto postProcessingFramebufferIt = _framebuffers.find("postprocessing"); if (postProcessingFramebufferIt == _framebuffers.end()) { PrototypeLogger::fatal("Cannot run without postprocessing framebuffer"); } // final auto finalFramebufferIt = _framebuffers.find("final"); if (finalFramebufferIt == _framebuffers.end()) { PrototypeLogger::fatal("Cannot run without final framebuffer"); } auto cameraObjects = PrototypeEngineInternalApplication::scene->fetchObjectsByTraits(PrototypeTraitTypeMaskCamera); for (auto cameraIterator = cameraObjects.begin(); cameraIterator != cameraObjects.end(); ++cameraIterator) { PrototypeSceneNode* cameraNode = (PrototypeSceneNode*)(*cameraIterator)->parentNode(); if (cameraNode) { if (cameraNode->name() == "SceneCamera") { #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE _editorSceneCamera.deferredFramebuffer = deferredFramebufferIt->second; _editorSceneCamera.gbufferFramebuffer = gbufferFramebufferIt->second; _editorSceneCamera.postprocessingFramebuffer = postProcessingFramebufferIt->second; _editorSceneCamera.finalFramebuffer = finalFramebufferIt->second; _editorSceneCamera.object = *cameraIterator; _editorSceneCamera.node = static_cast<PrototypeSceneNode*>(_editorSceneCamera.object->parentNode()); _editorSceneCamera.viewMatrix = static_cast<const GLfloat*>(&_editorSceneCamera.object->getCameraTrait()->viewMatrix()[0][0]); _editorSceneCamera.projectionMatrix = static_cast<const GLfloat*>(&_editorSceneCamera.object->getCameraTrait()->projectionMatrix()[0][0]); // set the corresponding ubo { auto commonUbo = _uniformBufferObjectsPool.newElement(); size_t bytes = 0; bytes += sizeof(float) * 16; // view matrix bytes += sizeof(float) * 16; // projection matrix bytes += sizeof(float) * 4; // near, far, mousex, mousey bytes += sizeof(float) * 4; // directional light position (x y z), time bytes += sizeof(float) * 4; // directional light color (x y z), (empty) PglUploadUniformBufferObject(bytes, 0, commonUbo); _uniformBufferObjects.insert({ "Common", commonUbo }); _editorSceneCamera.ubo = commonUbo; } _ui->sceneView()->setCamera(&_editorSceneCamera); #endif } else if (cameraNode->name() == "MainCamera") { #ifndef PROTOTYPE_ENGINE_DEVELOPMENT_MODE _mainCamera.deferredFramebuffer = deferredFramebufferIt->second; _mainCamera.gbufferFramebuffer = gbufferFramebufferIt->second; _mainCamera.postprocessingFramebuffer = postProcessingFramebufferIt->second; _mainCamera.finalFramebuffer = finalFramebufferIt->second; _mainCamera.object = *cameraIterator; _mainCamera.node = static_cast<PrototypeSceneNode*>(_mainCamera.object->parentNode()); _mainCamera.viewMatrix = static_cast<const GLfloat*>(&_mainCamera.object->getCameraTrait()->viewMatrix()[0][0]); _mainCamera.projectionMatrix = static_cast<const GLfloat*>(&_mainCamera.object->getCameraTrait()->projectionMatrix()[0][0]); // set the corresponding ubo { auto commonUbo = _uniformBufferObjectsPool.newElement(); size_t bytes = 0; bytes += sizeof(float) * 16; // view matrix bytes += sizeof(float) * 16; // projection matrix bytes += sizeof(float) * 4; // near, far, mousex, mousey bytes += sizeof(float) * 4; // directional light position (x y z), time bytes += sizeof(float) * 4; // directional light color (x y z), (empty) PglUploadUniformBufferObject(bytes, 0, commonUbo); _uniformBufferObjects.insert({ "Common", commonUbo }); _mainCamera.ubo = commonUbo; } #endif } else if (cameraNode->name() == "PaintCamera") { #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE _editorPaintCamera.deferredFramebuffer = deferredFramebufferIt->second; _editorPaintCamera.gbufferFramebuffer = gbufferFramebufferIt->second; _editorPaintCamera.postprocessingFramebuffer = postProcessingFramebufferIt->second; _editorPaintCamera.finalFramebuffer = finalFramebufferIt->second; _editorPaintCamera.object = *cameraIterator; _editorPaintCamera.node = static_cast<PrototypeSceneNode*>(_editorPaintCamera.object->parentNode()); _editorPaintCamera.viewMatrix = static_cast<const GLfloat*>(&_editorPaintCamera.object->getCameraTrait()->viewMatrix()[0][0]); _editorPaintCamera.projectionMatrix = static_cast<const GLfloat*>(&_editorPaintCamera.object->getCameraTrait()->projectionMatrix()[0][0]); #endif } } } PrototypeEngineInternalApplication::renderer->scheduleRecordPass(); PrototypeEngineInternalApplication::physics->scheduleRecordPass(); #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_END(PrototypeOpenglRenderer::switchScenes) #endif } void PrototypeOpenglRenderer::scheduleRecordPass() { #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_BEGIN() #endif _needsRecord = true; PglCallResetAllocations(); _commandsPool.clear(); _commands.clear(); #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_END(PrototypeOpenglRenderer::scheduleRecordPass) #endif } void PrototypeOpenglRenderer::beginRecordPass() { #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_BEGIN() #endif if (!_needsRecord) return; _needsRecord = false; // <shader use> // <texture data> // <vec4> // <vec3> // <vec2> // <float> // <matrices (Model)> // <mesh> struct MeshDrawCommand { GLenum mode; GLenum type; GLsizei count; }; struct OrderedDrawSubCommand { PrototypeOpenglCommand* modelMatrixCommand = {}; PrototypeOpenglCommand* objectIdCommand = {}; std::unordered_map<GLuint, std::vector<MeshDrawCommand>> meshCommands; }; struct OrderedDrawCommand { PrototypeOpenglCommand* shaderCommand = nullptr; std::vector<PrototypeOpenglCommand*> texturesCommand; std::vector<PrototypeOpenglCommand*> vec4sCommand; std::vector<PrototypeOpenglCommand*> vec3sCommand; std::vector<PrototypeOpenglCommand*> vec2sCommand; std::vector<PrototypeOpenglCommand*> floatsCommand; std::vector<OrderedDrawSubCommand*> subCommands; }; MemoryPool<OrderedDrawCommand, 100> _orderedCommandsPool; MemoryPool<OrderedDrawSubCommand, 100> _orderedSubCommandsPool; std::unordered_map<GLuint, std::unordered_map<std::string, OrderedDrawCommand*>> orderedCommands; std::vector<PrototypeSceneNode*> selectedNodes; for (const auto& selectedNode : PrototypeEngineInternalApplication::scene->selectedNodes()) { selectedNodes.push_back(selectedNode); } PrototypeEngineInternalApplication::scene->clearSelectedNodes(); auto meshRendererObjects = PrototypeEngineInternalApplication::scene->fetchObjectsByTraits( PrototypeTraitTypeMaskMeshRenderer | PrototypeTraitTypeMaskTransform); for (const auto& meshRendererObject : meshRendererObjects) { PrototypeObject* object = meshRendererObject; if (((PrototypeSceneNode*)object->parentNode())->absoluteLayer()->name() != "default") continue; MeshRenderer* mr = object->getMeshRendererTrait(); Transform* transform = object->getTransformTrait(); for (const auto& meshMaterialPair : mr->data()) { auto meshRendererMaterialIt = PrototypeEngineInternalApplication::database->materials.find(meshMaterialPair.material); if (meshRendererMaterialIt == PrototypeEngineInternalApplication::database->materials.end()) { continue; } auto geometryPair = _geometries.find(meshMaterialPair.mesh); auto materialPair = _materials.find(meshRendererMaterialIt->second->name()); if (geometryPair != _geometries.end() && materialPair != _materials.end()) { const PglGeometry* geometry = geometryPair->second; const PglMaterial* material = materialPair->second; const PglShader* shader = material->shader; const std::vector<PglTexture*>& textures = material->textures; OrderedDrawCommand orderedDrawCommand = {}; glUniformBlockBinding(shader->program, glGetUniformBlockIndex(shader->program, "Common"), 0); auto commandIt = orderedCommands[material->shader->program].find(material->name); if (commandIt != orderedCommands[material->shader->program].end()) { OrderedDrawSubCommand* subCommand = _orderedSubCommandsPool.newElement(); { { auto a = PglCall_glUniformMatrix4fv::_allocator.newElement(); a->location = glGetUniformLocation(shader->program, "Model"); a->count = 1; a->transpose = 0; a->value = (GLfloat*)&transform->modelScaled()[0][0]; subCommand->modelMatrixCommand = _commandsPool.newElement(); subCommand->modelMatrixCommand->record(a); } { auto a = PglCall_glUniform1ui::_allocator.newElement(); a->location = glGetUniformLocation(shader->program, "ObjectId"); a->v0 = object->id(); subCommand->objectIdCommand = _commandsPool.newElement(); subCommand->objectIdCommand->record(a); } { MeshDrawCommand meshDrawCommand = {}; switch (meshMaterialPair.polygonMode) { case MeshRendererPolygonMode_POINT: meshDrawCommand.mode = GL_POINTS; break; case MeshRendererPolygonMode_LINE: meshDrawCommand.mode = GL_LINES; break; case MeshRendererPolygonMode_FILL: meshDrawCommand.mode = GL_TRIANGLES; break; default: break; } meshDrawCommand.type = geometry->type; meshDrawCommand.count = geometry->indexCount; subCommand->meshCommands[geometry->vao].push_back(std::move(meshDrawCommand)); } } commandIt->second->subCommands.push_back(subCommand); } else { OrderedDrawCommand* mainCommand = _orderedCommandsPool.newElement(); { { auto a = PglCall_glUseProgram::_allocator.newElement(); a->program = shader->program; mainCommand->shaderCommand = _commandsPool.newElement(); mainCommand->shaderCommand->record(a); } { size_t t = 0; for (const auto& texture : material->textureData) { { PrototypeOpenglCommand* cmd = _commandsPool.newElement(); auto a = PglCall_glUniform1i::_allocator.newElement(); a->location = glGetUniformLocation(shader->program, texture.c_str()); a->v0 = t; cmd->record(a); mainCommand->texturesCommand.push_back(cmd); } { PrototypeOpenglCommand* cmd = _commandsPool.newElement(); auto a = PglCall_glActiveTexture::_allocator.newElement(); a->texture = GL_TEXTURE0 + t; cmd->record(a); mainCommand->texturesCommand.push_back(cmd); } { PrototypeOpenglCommand* cmd = _commandsPool.newElement(); auto a = PglCall_glBindTexture::_allocator.newElement(); a->target = material->textures[t]->target; a->id = material->textures[t]->id; cmd->record(a); mainCommand->texturesCommand.push_back(cmd); } ++t; } } { // base color { PrototypeOpenglCommand* cmd = _commandsPool.newElement(); auto a = PglCall_glUniform3fv::_allocator.newElement(); a->location = glGetUniformLocation(shader->program, "BaseColor"); a->count = 1; a->value = (GLfloat*)&material->baseColor[0]; cmd->record(a); mainCommand->vec3sCommand.push_back(cmd); }; // metallic { PrototypeOpenglCommand* cmd = _commandsPool.newElement(); auto a = PglCall_glUniform1fv::_allocator.newElement(); a->location = glGetUniformLocation(shader->program, "Metallic"); a->count = 1; a->value = (GLfloat*)&material->metallic; cmd->record(a); mainCommand->floatsCommand.push_back(cmd); }; // roughness { PrototypeOpenglCommand* cmd = _commandsPool.newElement(); auto a = PglCall_glUniform1fv::_allocator.newElement(); a->location = glGetUniformLocation(shader->program, "Roughness"); a->count = 1; a->value = (GLfloat*)&material->roughness; cmd->record(a); mainCommand->floatsCommand.push_back(cmd); }; } { for (const auto& pair : material->vec4Data) { { PrototypeOpenglCommand* cmd = _commandsPool.newElement(); auto a = PglCall_glUniform4fv::_allocator.newElement(); a->location = glGetUniformLocation(shader->program, pair.first.c_str()); a->count = 1; a->value = (GLfloat*)&pair.second; cmd->record(a); mainCommand->vec4sCommand.push_back(cmd); } } } { for (const auto& pair : material->vec3Data) { { PrototypeOpenglCommand* cmd = _commandsPool.newElement(); auto a = PglCall_glUniform3fv::_allocator.newElement(); a->location = glGetUniformLocation(shader->program, pair.first.c_str()); a->count = 1; a->value = (GLfloat*)&pair.second; cmd->record(a); mainCommand->vec3sCommand.push_back(cmd); } } } { for (const auto& pair : material->vec2Data) { { PrototypeOpenglCommand* cmd = _commandsPool.newElement(); auto a = PglCall_glUniform2fv::_allocator.newElement(); a->location = glGetUniformLocation(shader->program, pair.first.c_str()); a->count = 1; a->value = (GLfloat*)&pair.second; cmd->record(a); mainCommand->vec2sCommand.push_back(cmd); } } } { for (const auto& pair : material->floatData) { { PrototypeOpenglCommand* cmd = _commandsPool.newElement(); auto a = PglCall_glUniform1fv::_allocator.newElement(); a->location = glGetUniformLocation(shader->program, pair.first.c_str()); a->count = 1; a->value = (GLfloat*)&pair.second; cmd->record(a); mainCommand->floatsCommand.push_back(cmd); } } } { OrderedDrawSubCommand* subCommand = _orderedSubCommandsPool.newElement(); { { auto a = PglCall_glUniformMatrix4fv::_allocator.newElement(); a->location = glGetUniformLocation(shader->program, "Model"); a->count = 1; a->transpose = 0; a->value = (GLfloat*)&transform->modelScaled()[0][0]; subCommand->modelMatrixCommand = _commandsPool.newElement(); subCommand->modelMatrixCommand->record(a); } { auto a = PglCall_glUniform1ui::_allocator.newElement(); a->location = glGetUniformLocation(shader->program, "ObjectId"); a->v0 = object->id(); subCommand->objectIdCommand = _commandsPool.newElement(); subCommand->objectIdCommand->record(a); } { MeshDrawCommand meshDrawCommand = {}; switch (meshMaterialPair.polygonMode) { case MeshRendererPolygonMode_POINT: meshDrawCommand.mode = GL_POINTS; break; case MeshRendererPolygonMode_LINE: meshDrawCommand.mode = GL_LINES; break; case MeshRendererPolygonMode_FILL: meshDrawCommand.mode = GL_TRIANGLES; break; default: break; } meshDrawCommand.type = geometry->type; meshDrawCommand.count = geometry->indexCount; subCommand->meshCommands[geometry->vao].push_back(std::move(meshDrawCommand)); } } mainCommand->subCommands.push_back(subCommand); } } orderedCommands[material->shader->program].insert({ material->name, mainCommand }); } } } } for (auto& shaderMatPair : orderedCommands) { _commands.push_back(shaderMatPair.second.begin()->second->shaderCommand); for (const auto& matPair : shaderMatPair.second) { _commands.insert(_commands.end(), matPair.second->texturesCommand.begin(), matPair.second->texturesCommand.end()); _commands.insert(_commands.end(), matPair.second->vec4sCommand.begin(), matPair.second->vec4sCommand.end()); _commands.insert(_commands.end(), matPair.second->vec3sCommand.begin(), matPair.second->vec3sCommand.end()); _commands.insert(_commands.end(), matPair.second->vec2sCommand.begin(), matPair.second->vec2sCommand.end()); _commands.insert(_commands.end(), matPair.second->floatsCommand.begin(), matPair.second->floatsCommand.end()); for (auto& subCommand : matPair.second->subCommands) { _commands.push_back(subCommand->modelMatrixCommand); _commands.push_back(subCommand->objectIdCommand); for (auto& meshPair : subCommand->meshCommands) { { PrototypeOpenglCommand* cmd = _commandsPool.newElement(); auto a = PglCall_glBindVertexArray::_allocator.newElement(); a->index = meshPair.first; cmd->record(a); _commands.push_back(cmd); } { PrototypeOpenglCommand* cmd = _commandsPool.newElement(); auto a = PglCall_glDrawElements::_allocator.newElement(); a->mode = meshPair.second[0].mode; // GL_POINTS | GL_LINES | GL_TRIANGLES a->type = meshPair.second[0].type; // geometry->type; a->count = meshPair.second[0].count; // geometry->indexCount; a->indices = nullptr; // a->instanceCount = meshPair.second.size(); cmd->record(a); _commands.push_back(cmd); } } } } } for (auto selectedNode : selectedNodes) { PrototypeEngineInternalApplication::scene->addSelectedNode(selectedNode); } _window->resetDeltaTime(); #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_END(PrototypeOpenglRenderer::beginRecordPass) #endif } void PrototypeOpenglRenderer::endRecordPass() { #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_BEGIN() #endif #if defined(PROTOTYPE_ENABLE_PROFILER) PROTOTYPE_REGISTER_PROFILER_FUNCTION_END(PrototypeOpenglRenderer::endRecordPass) #endif } #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE PrototypeUI* PrototypeOpenglRenderer::ui() { return _ui.get(); } #endif #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE // Camera* PrototypeOpenglRenderer::editorGameCamera() {} Camera* PrototypeOpenglRenderer::editorSceneCamera() { return static_cast<PglCamera*>(_ui->sceneView()->camera())->object->getCameraTrait(); } // Camera* PrototypeOpenglRenderer::editorPaintCamera() {} #else Camera* PrototypeOpenglRenderer::mainCamera() { return _mainCamera.object->getCameraTrait(); } #endif void PrototypeOpenglRenderer::mapPrototypeMeshBuffer(PrototypeMeshBuffer* meshBuffer) { if (_geometries.find(meshBuffer->name()) != _geometries.end()) { return; } auto geometry = _geometriesPool.newElement(); meshBuffer->userData = (void*)geometry; PglUploadMeshFromBuffer(meshBuffer, geometry); _geometries.insert({ meshBuffer->name(), geometry }); } void PrototypeOpenglRenderer::mapPrototypeShaderBuffer(PrototypeShaderBuffer* shaderBuffer) { if (_shaders.find(shaderBuffer->name()) != _shaders.end()) { return; } auto shader = _shadersPool.newElement(); shaderBuffer->userData = (void*)shader; PglUploadShaderFromBuffer(shaderBuffer, shader); for (const auto& source : shaderBuffer->sources()) { if (source->type == PrototypeShaderBufferSourceType_VertexShader) { PrototypeAlgoCopyNewValues(source->bindingSource.floatData, shader->floatData); PrototypeAlgoCopyNewValues(source->bindingSource.vec2Data, shader->vec2Data); PrototypeAlgoCopyNewValues(source->bindingSource.vec3Data, shader->vec3Data); PrototypeAlgoCopyNewValues(source->bindingSource.vec4Data, shader->vec4Data); } else if (source->type == PrototypeShaderBufferSourceType_FragmentShader) { PrototypeAlgoCopyNewValues(source->bindingSource.textureData, shader->textureData); } } _shaders.insert({ shaderBuffer->name(), shader }); } void PrototypeOpenglRenderer::mapPrototypeTextureBuffer(PrototypeTextureBuffer* textureBuffer) { if (_textures.find(textureBuffer->name()) != _textures.end()) { return; } auto texture = _texturesPool.newElement(); textureBuffer->userData = (void*)texture; PglUploadTextureFromBuffer(textureBuffer, texture); _textures.insert({ textureBuffer->name(), texture }); } void PrototypeOpenglRenderer::mapPrototypeMaterial(PrototypeMaterial* material) { if (_materials.find(material->name()) != _materials.end()) { return; } const PrototypeShaderBuffer* dbMaterialShaderBuffer = material->shader(); auto mat = _materialsPool.newElement(); mat->name = material->name(); mat->shader = _shaders[dbMaterialShaderBuffer->name()]; mat->baseColor = material->baseColor(); mat->metallic = material->metallic(); mat->roughness = material->roughness(); onMaterialShaderUpdate(mat, mat->shader); mat->textures.resize(mat->textureData.size()); for (size_t t = 0; t < mat->textures.size(); ++t) { mat->textures[t] = _textures[material->textures()[t]->name()]; } _materials.insert({ material->name(), mat }); } void PrototypeOpenglRenderer::onMeshBufferGpuUpload(PrototypeMeshBuffer* meshBuffer) { #if defined(PROTOTYPE_ENABLE_PROFILER) static auto profilerT1 = std::chrono::high_resolution_clock::now(); #endif if (meshBuffer->userData) { PglGeometry* geometry = static_cast<PglGeometry*>(meshBuffer->userData); PglReleaseMesh(geometry); PglUploadMeshFromBuffer(meshBuffer, geometry); PrototypeEngineInternalApplication::renderer->scheduleRecordPass(); } #if defined(PROTOTYPE_ENABLE_PROFILER) static auto profilerT2 = std::chrono::high_resolution_clock::now(); static auto profilerDuration = std::chrono::duration_cast<std::chrono::microseconds>(profilerT2 - profilerT1).count(); PrototypeEngineInternalApplication::profiler->markTimelineItem("PrototypeOpenglRenderer::onMeshBufferGpuUpload", profilerDuration); #endif } void PrototypeOpenglRenderer::onShaderBufferGpuUpload(PrototypeShaderBuffer* shaderBuffer) { #if defined(PROTOTYPE_ENABLE_PROFILER) static auto profilerT1 = std::chrono::high_resolution_clock::now(); #endif if (shaderBuffer->userData) { PglShader* shader = static_cast<PglShader*>(shaderBuffer->userData); PglReleaseShader(shader); PglUploadShaderFromBuffer(shaderBuffer, shader); for (const auto& source : shaderBuffer->sources()) { if (source->type == PrototypeShaderBufferSourceType_VertexShader) { PrototypeAlgoCopyNewValues(source->bindingSource.floatData, shader->floatData); PrototypeAlgoCopyNewValues(source->bindingSource.vec2Data, shader->vec2Data); PrototypeAlgoCopyNewValues(source->bindingSource.vec3Data, shader->vec3Data); PrototypeAlgoCopyNewValues(source->bindingSource.vec4Data, shader->vec4Data); } else if (source->type == PrototypeShaderBufferSourceType_FragmentShader) { PrototypeAlgoCopyNewValues(source->bindingSource.textureData, shader->textureData); } } const auto& materials = ((PrototypeOpenglRenderer*)PrototypeEngineInternalApplication::renderer)->materials(); for (const auto& pair : materials) { PglMaterial* material = pair.second; if (material->shader == shader) { ((PrototypeOpenglRenderer*)PrototypeEngineInternalApplication::renderer) ->onMaterialShaderUpdate(material, shader); } } PrototypeEngineInternalApplication::renderer->scheduleRecordPass(); } #if defined(PROTOTYPE_ENABLE_PROFILER) static auto profilerT2 = std::chrono::high_resolution_clock::now(); static auto profilerDuration = std::chrono::duration_cast<std::chrono::microseconds>(profilerT2 - profilerT1).count(); PrototypeEngineInternalApplication::profiler->markTimelineItem("PrototypeOpenglRenderer::onShaderBufferGpuUpload", profilerDuration); #endif } void PrototypeOpenglRenderer::onTextureBufferGpuUpload(PrototypeTextureBuffer* textureBuffer) { #if defined(PROTOTYPE_ENABLE_PROFILER) static auto profilerT1 = std::chrono::high_resolution_clock::now(); #endif if (textureBuffer->userData) { PglTexture* texture = static_cast<PglTexture*>(textureBuffer->userData); PglReleaseTexture(texture); PglUploadTextureFromBuffer(textureBuffer, texture); PrototypeEngineInternalApplication::renderer->scheduleRecordPass(); } #if defined(PROTOTYPE_ENABLE_PROFILER) static auto profilerT2 = std::chrono::high_resolution_clock::now(); static auto profilerDuration = std::chrono::duration_cast<std::chrono::microseconds>(profilerT2 - profilerT1).count(); PrototypeEngineInternalApplication::profiler->markTimelineItem("PrototypeOpenglRenderer::onTextureBufferGpuUpload", profilerDuration); #endif } void PrototypeOpenglRenderer::fetchCamera(const std::string& name, void** data) { #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE if (name == "SceneCamera") { *data = &_editorSceneCamera; } else { *data = nullptr; } #else *data = &_mainCamera; #endif } void PrototypeOpenglRenderer::fetchDefaultMesh(void** data) { auto it = _geometries.find(PROTOTYPE_DEFAULT_MESH); if (it != _geometries.end()) { *data = it->second; } } void PrototypeOpenglRenderer::fetchMesh(const std::string& name, void** data) { auto it = _geometries.find(name); if (it != _geometries.end()) { *data = it->second; } } void PrototypeOpenglRenderer::fetchDefaultShader(void** data) { auto it = _shaders.find(PROTOTYPE_DEFAULT_SHADER); if (it != _shaders.end()) { *data = it->second; } } void PrototypeOpenglRenderer::fetchShader(const std::string& name, void** data) { auto it = _shaders.find(name); if (it != _shaders.end()) { *data = it->second; } } void PrototypeOpenglRenderer::fetchDefaultTexture(void** data) { auto it = _textures.find("default.jpg"); if (it != _textures.end()) { *data = it->second; } } void PrototypeOpenglRenderer::fetchTexture(const std::string& name, void** data) { auto it = _textures.find(name); if (it != _textures.end()) { *data = it->second; } } void PrototypeOpenglRenderer::fetchDefaultMaterial(void** data) { auto it = _materials.find(PROTOTYPE_DEFAULT_MATERIAL); if (it != _materials.end()) { *data = it->second; } } void PrototypeOpenglRenderer::fetchMaterial(const std::string& name, void** data) { auto it = _materials.find(name); if (it != _materials.end()) { *data = it->second; } } void PrototypeOpenglRenderer::fetchDefaultFramebuffer(void** data) { auto it = _framebuffers.find(PROTOTYPE_DEFAULT_FRAMEBUFFER); if (it != _framebuffers.end()) { *data = it->second; } } void PrototypeOpenglRenderer::fetchFramebuffer(const std::string& name, void** data) { auto it = _framebuffers.find(name); if (it != _framebuffers.end()) { *data = it->second; } } // [[nodiscard]] PrototypeSceneNode* // PrototypeOpenglRenderer::onSceneViewClick(const glm::vec2& coordinates, const glm::vec2& Size) // { // /*Camera* cam = _mainCamera.object->getCameraTrait(); // const auto& camPosition = cam->position(); // const auto& camViewMatrix = cam->viewMatrix(); // const auto& camProjectionMatrix = cam->projectionMatrix(); // glm::vec3 ray;*/ // float UVObjectIDPixel[4]; // #define UVObjectIDColorAttachmentId 4 // #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE // glm::vec2 dimensions = _ui->sceneView().dimensions(); // glm::vec2 cursorCoordinates = _ui->sceneView().cursorCoordinates(); // /*PrototypeMaths::projectRayFromClipSpacePoint(ray, // camViewMatrix, // camProjectionMatrix, // _ui->sceneViewCursorCoordinates().x, // _ui->sceneViewCursorCoordinates().y, // _ui->sceneViewSize().x, // _ui->sceneViewSize().y);*/ // f32 u = (cursorCoordinates.x / dimensions.x) * dimensions.x; // f32 v = (1.0f - cursorCoordinates.y / dimensions.y) * dimensions.y; // glBindFramebuffer(GL_FRAMEBUFFER, _mainCamera.deferredFramebuffer->fbo); // glReadBuffer(GL_COLOR_ATTACHMENT0 + UVObjectIDColorAttachmentId); // glReadPixels(u, v, 1, 1, GL_RGBA, GL_FLOAT, &UVObjectIDPixel); // glReadBuffer(GL_NONE); // glBindFramebuffer(GL_FRAMEBUFFER, 0); // #else // /*PrototypeMaths::projectRayFromClipSpacePoint(ray, // camViewMatrix, // camProjectionMatrix, // _window->_mouseLocation.x, // _window->_mouseLocation.y, // _window->_resolution.x, // _window->_resolution.y);*/ // f32 u = ((2.0f * _window->_mouseLocation.x) / _window->_resolution.x - 1.0f) * _window->_resolution.x; // f32 v = (1.0f - (2.0f * _window->_mouseLocation.y) / _window->_resolution.y) * _window->_resolution.y; // // snprintf(buff, sizeof(buff), "uv [%f, %f]", u, v); // // PrototypeLogger::log(__FILE__, __LINE__, buff); // glBindFramebuffer(GL_FRAMEBUFFER, _mainCamera.deferredFramebuffer->fbo); // glReadBuffer(GL_COLOR_ATTACHMENT0 + UVObjectIDColorAttachmentId); // glReadPixels(u, v, 1, 1, GL_RGBA, GL_FLOAT, &UVObjectIDPixel); // glReadBuffer(GL_NONE); // glBindFramebuffer(GL_FRAMEBUFFER, 0); // #endif // u32 objectId = UVObjectIDPixel[2]; // if (objectId == 0) { return nullptr; } // auto meshRendererMap = PrototypeTraitSystem::meshRendererMap(); // auto meshRendererIt = meshRendererMap.find(objectId); // if (meshRendererIt != meshRendererMap.end()) { // MeshRenderer* mr = PrototypeTraitSystem::meshRendererVector()[meshRendererIt->second]; // PrototypeObject* object = mr->object(); // if (object) { // if (object->parentNode()) { // auto node = static_cast<PrototypeSceneNode*>(object->parentNode()); // return node; // } // } // } // /*auto optHit = // PrototypeEngineInternalApplication::physics->raycast({ camPosition.x, camPosition.y, camPosition.z }, ray, cam->zfar()); // if (optHit) { // auto hit = optHit.value(); // if (hit && hit->parentNode()) { // auto node = static_cast<PrototypeSceneNode*>(hit->parentNode()); // return node; // } // }*/ // return nullptr; // } void PrototypeOpenglRenderer::onMouse(i32 button, i32 action, i32 mods) { #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE if (_ui->sceneView()->onMouse(button, action, mods)) return; if (_ui->needsMouse() && !_ui->sceneView()->isHovered()) return; #endif } void PrototypeOpenglRenderer::onMouseMove(f64 xpos, f64 ypos) { #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE if (_ui->sceneView()->onMouseMove(xpos, ypos)) return; if (_ui->needsMouse() && !_ui->sceneView()->isHovered()) return; #endif } void PrototypeOpenglRenderer::onMouseDrag(i32 button, f64 xoffset, f64 yoffset) { #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE if (_ui->sceneView()->onMouseDrag(button, xoffset, yoffset)) return; if (_ui->needsMouse() && !_ui->sceneView()->isHovered()) return; #else if (_window->_mouseDown.z) { CameraSystemRotate(_mainCamera.object->getCameraTrait(), (f32)xoffset, (f32)yoffset); } #endif } void PrototypeOpenglRenderer::onMouseScroll(f64 xoffset, f64 yoffset) { #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE if (_ui->sceneView()->onMouseScroll(xoffset, yoffset)) return; if (_ui->needsMouse() && !_ui->sceneView()->isHovered()) return; #else CameraSystemRotate(_mainCamera.object->getCameraTrait(), (f32)xoffset, (f32)yoffset); #endif } void PrototypeOpenglRenderer::onKeyboard(i32 key, i32 scancode, i32 action, i32 mods) { #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE if (_ui->sceneView()->onKeyboard(key, scancode, action, mods)) return; if (_ui->needsKeyboard() || (_ui->needsMouse() && !_ui->sceneView()->isHovered())) return; #else _input->onKeyboard(key, scancode, action, mods); if (action == GLFW_PRESS) { // spawning stuff in scene { Camera* cam = _mainCamera.object->getCameraTrait(); const auto& cameraPosition = cam->position(); const auto& cameraRotation = cam->rotation(); const auto& cameraResolution = cam->resolution(); const auto& camViewMatrix = cam->viewMatrix(); const auto& camProjectionMatrix = cam->projectionMatrix(); glm::vec3 ray; PrototypeMaths::projectRayFromClipSpacePoint(ray, camViewMatrix, camProjectionMatrix, _window->_mouseLocation.x, _window->_mouseLocation.y, _window->_resolution.x, _window->_resolution.y); glm::vec3 pos = { cameraPosition.x, cameraPosition.y, cameraPosition.z }; glm::vec3 rot = { cameraRotation.x, cameraRotation.y, 0.0f }; const f32 speed = 10.0f; ray.x *= speed; ray.y *= speed; ray.z *= speed; if (key == GLFW_KEY_1) { shortcutSpawnSphere(pos, rot, ray); PrototypeEngineInternalApplication::renderer->scheduleRecordPass(); } else if (key == GLFW_KEY_2) { shortcutSpawnCube(pos, rot, ray); PrototypeEngineInternalApplication::renderer->scheduleRecordPass(); } else if (key == GLFW_KEY_3) { shortcutSpawnConvexMesh(pos, rot, ray, "ico.obj", PROTOTYPE_DEFAULT_MATERIAL); PrototypeEngineInternalApplication::renderer->scheduleRecordPass(); } else if (key == GLFW_KEY_4) { shortcutSpawnConvexMesh(pos, rot, ray, "monkey.obj", PROTOTYPE_DEFAULT_MATERIAL); PrototypeEngineInternalApplication::renderer->scheduleRecordPass(); } else if (key == GLFW_KEY_5) { shortcutSpawnConvexMesh(pos, rot, ray, "capsule.obj", PROTOTYPE_DEFAULT_MATERIAL); PrototypeEngineInternalApplication::renderer->scheduleRecordPass(); } else if (key == GLFW_KEY_6) { shortcutSpawnConvexMesh(pos, rot, ray, "cylinder.obj", PROTOTYPE_DEFAULT_MATERIAL); PrototypeEngineInternalApplication::renderer->scheduleRecordPass(); } else if (key == GLFW_KEY_7) { shortcutSpawnVehicle(pos, rot, ray, "CUBE", PROTOTYPE_DEFAULT_MATERIAL); PrototypeEngineInternalApplication::physics->spawnVehicle(); } } } else if (action == GLFW_RELEASE) { if (key == GLFW_KEY_G) { PrototypeEngineInternalApplication::physics->controlledVehiclesToggleGearDirection(); } else if (key == GLFW_KEY_EQUAL) { PrototypeEngineInternalApplication::physics->requestNextVehicleAccessControl(); } else if (key == GLFW_KEY_MINUS) { PrototypeEngineInternalApplication::physics->requestPreviousVehicleAccessControl(); } else if (key == GLFW_KEY_0) { PrototypeEngineInternalApplication::physics->controlledVehiclesFlip(); } } #endif } void PrototypeOpenglRenderer::onWindowResize(i32 width, i32 height) { #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE if (_ui->sceneView()->onWindowResize(width, height)) return; #endif // _actions.push_back([this]() { _framebufferResized = true; }); PglFramebufferResize(_fullscreenFramebuffer, width, height); #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE Camera* cam = _editorSceneCamera.object->getCameraTrait(); glm::vec2 dimensions = _ui->sceneView()->dimensions(); PglFramebufferResize(_editorSceneCamera.finalFramebuffer, dimensions.x, dimensions.y); PglFramebufferResize(_editorSceneCamera.postprocessingFramebuffer, dimensions.x, dimensions.y); PglFramebufferResize(_editorSceneCamera.gbufferFramebuffer, dimensions.x, dimensions.y); PglFramebufferResize(_editorSceneCamera.deferredFramebuffer, dimensions.x, dimensions.y); CameraSystemSetResolution(cam, dimensions.x, dimensions.y); #else Camera* cam = _mainCamera.object->getCameraTrait(); PglFramebufferResize(_mainCamera.finalFramebuffer, width, height); PglFramebufferResize(_mainCamera.postprocessingFramebuffer, width, height); PglFramebufferResize(_mainCamera.gbufferFramebuffer, width, height); PglFramebufferResize(_mainCamera.deferredFramebuffer, width, height); CameraSystemSetResolution(cam, width, height); #endif } void PrototypeOpenglRenderer::onWindowDragDrop(i32 numFiles, const char** names) { #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE if (_ui->sceneView()->onWindowDragDrop(numFiles, names)) return; #endif } const std::unordered_map<std::string, PglGeometry*>& PrototypeOpenglRenderer::geometries() const { return _geometries; } const std::unordered_map<std::string, PglShader*>& PrototypeOpenglRenderer::shaders() const { return _shaders; } const std::unordered_map<std::string, PglTexture*>& PrototypeOpenglRenderer::textures() const { return _textures; } const std::unordered_map<std::string, PglMaterial*>& PrototypeOpenglRenderer::materials() const { return _materials; } const std::unordered_map<std::string, PglFramebuffer*>& PrototypeOpenglRenderer::framebuffers() const { return _framebuffers; } #ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE PglCamera& PrototypeOpenglRenderer::pglEditorSceneCamera() { return _editorSceneCamera; } PglCamera& PrototypeOpenglRenderer::pglEditorPaintCamera() { return _editorPaintCamera; } #else PglCamera& PrototypeOpenglRenderer::pglMainCamera() { return _mainCamera; } #endif
49.196
131
0.583706
[ "mesh", "geometry", "render", "object", "vector", "model", "transform" ]
1339c39f3f28e31bd08fd89d589a96ea9e24c329
8,678
cpp
C++
Marlin/src/lcd/extui/anycubic_chiron/FileNavigator.cpp
violigon/3DPrinter-DE2LV
5c8960f07085cc11d232a52cb029aa92533287bd
[ "MIT" ]
null
null
null
Marlin/src/lcd/extui/anycubic_chiron/FileNavigator.cpp
violigon/3DPrinter-DE2LV
5c8960f07085cc11d232a52cb029aa92533287bd
[ "MIT" ]
null
null
null
Marlin/src/lcd/extui/anycubic_chiron/FileNavigator.cpp
violigon/3DPrinter-DE2LV
5c8960f07085cc11d232a52cb029aa92533287bd
[ "MIT" ]
null
null
null
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * lcd/extui/anycubic_chiron/FileNavigator.cpp * * Extensible_UI implementation for Anycubic Chiron * Written By Nick Wells, 2020 [https://github.com/SwiftNick] * (not affiliated with Anycubic, Ltd.) * * The AC panel wants files in block of 4 and can only display a flat list * This library allows full folder traversal or flat file display and supports both standerd and new style panels. * * ## Old Style TFT panel * Supported chars {}[]-+=_"$%^&*()~<>| * Max display length 22 chars * Max path len 29 chars * (DOS 8.3 filepath max 29chars) * (long filepath Max 22) * * ## New TFT Panel Format file display format * Supported chars {}[]-+=_!"$%^&*()~<>\| * Max display length 26 chars * Max path len 29 chars * (DOS 8.3 filepath must end '.GCO') * (long filepath must end '.gcode') * */ #include "../../../inc/MarlinConfigPre.h" #if ENABLED(ANYCUBIC_LCD_CHIRON) #include "FileNavigator.h" #include "chiron_tft.h" using namespace ExtUI; #define DEBUG_OUT ACDEBUG(AC_FILE) #include "../../../core/debug_out.h" namespace Anycubic { FileNavigator filenavigator; FileList FileNavigator::filelist; // Instance of the Marlin file API uint16_t FileNavigator::lastpanelindex; uint16_t FileNavigator::currentindex; // override the panel request uint8_t FileNavigator::currentfolderdepth; uint16_t FileNavigator::currentfolderindex[MAX_FOLDER_DEPTH]; // track folder pos for iteration char FileNavigator::currentfoldername[MAX_PATH_LEN + 1]; // Current folder path FileNavigator::FileNavigator() { reset(); } void FileNavigator::reset() { DEBUG_ECHOLNPGM("reset()"); currentfoldername[0] = '\0'; currentfolderdepth = 0; currentindex = 0; lastpanelindex = 0; ZERO(currentfolderindex); // Start at root folder while (!filelist.isAtRootDir()) filelist.upDir(); refresh(); } void FileNavigator::refresh() { filelist.refresh(); } void FileNavigator::changeDIR(const char *folder) { if (currentfolderdepth >= MAX_FOLDER_DEPTH) return; // limit the folder depth DEBUG_ECHOLNPGM("FD:" , folderdepth, " FP:",currentindex, " currentfolder:", currentfoldername, " enter:", folder); currentfolderindex[currentfolderdepth] = currentindex; strcat(currentfoldername, folder); strcat(currentfoldername, "/"); filelist.changeDir(folder); currentfolderdepth++; currentindex = 0; } void FileNavigator::upDIR() { DEBUG_ECHOLNPGM("upDIR() from D:", currentfolderdepth, " N:", currentfoldername); if (!filelist.isAtRootDir()) { filelist.upDir(); currentfolderdepth--; currentindex = currentfolderindex[currentfolderdepth]; // restore last position in the folder filelist.seek(currentindex); // restore file information } // Remove the child folder from the stored path if (currentfolderdepth == 0) currentfoldername[0] = '\0'; else { char * const pos = strchr(currentfoldername, '/'); *(pos + 1) = '\0'; } } void FileNavigator::skiptofileindex(uint16_t skip) { if (skip == 0) return; while (skip > 0) { if (filelist.seek(currentindex)) { DEBUG_ECHOLNPGM("CI:", currentindex, " FD:", currentfolderdepth, " N:", skip, " ", filelist.longFilename()); if (!filelist.isDir()) { skip--; currentindex++; } else changeDIR(filelist.shortFilename()); } // valid file if (currentindex == filelist.count()) { if (currentfolderdepth > 0) { upDIR(); currentindex++; } else break; // end of root folder } // end of folder } // files needed // No more files available. } #if ENABLED(AC_SD_FOLDER_VIEW) // SD Folder navigation void FileNavigator::getFiles(uint16_t index, panel_type_t paneltype, uint8_t filesneeded) { if (index == 0) currentindex = 0; // Each time we change folder we reset the file index to 0 and keep track // of the current position, since the TFT panel isn't aware of folder trees. if (index > 0) { --currentindex; // go back a file to take account of the .. we added to the root. if (index > lastpanelindex) currentindex += filesneeded; else currentindex = currentindex < 4 ? 0 : currentindex - filesneeded; } lastpanelindex = index; DEBUG_ECHOLNPGM("index=", index, " currentindex=", currentindex); if (currentindex == 0 && currentfolderdepth > 0) { // Add a link to go up a folder // The new panel ignores entries that don't end in .GCO or .gcode so add and pad them. if (paneltype == AC_panel_new) { TFTSer.println("<<.GCO"); Chiron.SendtoTFTLN(PSTR(".. .gcode")); } else { TFTSer.println("<<"); TFTSer.println(".."); } filesneeded--; } for (uint16_t seek = currentindex; seek < currentindex + filesneeded; seek++) { if (filelist.seek(seek)) { sendFile(paneltype); DEBUG_ECHOLNPGM("-", seek, " '", filelist.longFilename(), "' '", currentfoldername, "", filelist.shortFilename(), "'"); } } } void FileNavigator::sendFile(panel_type_t paneltype) { if (filelist.isDir()) { // Add mandatory tags for new panel otherwise lines are ignored. if (paneltype == AC_panel_new) { TFTSer.print(filelist.shortFilename()); TFTSer.println(".GCO"); TFTSer.print(filelist.shortFilename()); TFTSer.write('/'); // Make sure we fill all 29 chars of the display line to clear the text buffer otherwise the last line is still visible for (int8_t i = strlen(filelist.shortFilename()); i < 19; i++) TFTSer.write(' '); TFTSer.println(".gcode"); } else { TFTSer.println(filelist.shortFilename()); TFTSer.print(filelist.shortFilename()); TFTSer.write('/'); TFTSer.println(); } } else { // Not DIR TFTSer.write('/'); if (currentfolderdepth > 0) TFTSer.print(currentfoldername); TFTSer.println(filelist.shortFilename()); TFTSer.print(filelist.longFilename()); // Make sure we fill all 29 chars of the display line to clear the text buffer otherwise the last line is still visible if (paneltype == AC_panel_new) for (int8_t i = strlen(filelist.longFilename()); i < 26; i++) TFTSer.write(' '); TFTSer.println(); } } // AC_SD_FOLDER_VIEW #else // Flat file list void FileNavigator::getFiles(uint16_t index, panel_type_t paneltype, uint8_t filesneeded) { DEBUG_ECHOLNPGM("getFiles() I:", index," L:", lastpanelindex); // if we're searching backwards, jump back to start and search forward if (index < lastpanelindex) { reset(); skiptofileindex(index); } lastpanelindex = index; while (filesneeded > 0) { if (filelist.seek(currentindex)) { if (!filelist.isDir()) { sendFile(paneltype); filesneeded--; currentindex++; } else changeDIR(filelist.shortFilename()); } // valid file if (currentindex == filelist.count()) { if (currentfolderdepth > 0) { upDIR(); currentindex++; } else break; // end of root folder } // end of folder } // files needed // No more files available. } void FileNavigator::sendFile(panel_type_t paneltype) { TFTSer.write('/'); if (currentfolderdepth > 0) TFTSer.print(currentfoldername); TFTSer.println(filelist.shortFilename()); if (currentfolderdepth > 0) TFTSer.print(currentfoldername); TFTSer.println(filelist.longFilename()); DEBUG_ECHOLNPGM("/", currentfoldername, "", filelist.shortFilename(), " ", filelist.longFilename()); } #endif // Flat file list } // Anycubic namespace #endif // ANYCUBIC_LCD_CHIRON
33.505792
127
0.651302
[ "3d" ]
133c7678dd2d69b3beb382f6a97c825ccf3af177
850
cpp
C++
util.cpp
xpspectre/distance
3fb31f5e8703ea9ee1a1ae2c2d891376a4762364
[ "MIT" ]
null
null
null
util.cpp
xpspectre/distance
3fb31f5e8703ea9ee1a1ae2c2d891376a4762364
[ "MIT" ]
null
null
null
util.cpp
xpspectre/distance
3fb31f5e8703ea9ee1a1ae2c2d891376a4762364
[ "MIT" ]
null
null
null
#include "util.h" #include <random> #include <algorithm> using std::string; using std::vector; using std::size_t; string random_str(size_t n) { // Generate random string // TODO: also make it have a random length, more efficient initialization of the RNG const static string chars = "abcdefghijklmnaoqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; std::mt19937_64 gen { std::random_device()() }; std::uniform_int_distribution<size_t> dist { 0, chars.length()-1 }; std::string str; std::generate_n(std::back_inserter(str), n, [&] { return chars[dist(gen)]; }); return str; } vector<string> random_strs(size_t N, size_t n) { // Generate vector of random strings vector<string> strs; strs.reserve(N); for (size_t i = 0; i < N; ++i) { strs.emplace_back(random_str(n)); } return strs; }
29.310345
97
0.676471
[ "vector" ]
133c841da3536333b60bdeb4c998fa001e7f5765
4,896
cpp
C++
0_driver/variant/variant_topic_tools/src/Message.cpp
huying163/ros_environment
bac3343bf92e6fa2bd852baf261e80712564f990
[ "MIT" ]
8
2018-01-30T11:40:31.000Z
2021-05-03T05:52:47.000Z
0_driver/variant/variant_topic_tools/src/Message.cpp
huying163/ros_environment
bac3343bf92e6fa2bd852baf261e80712564f990
[ "MIT" ]
null
null
null
0_driver/variant/variant_topic_tools/src/Message.cpp
huying163/ros_environment
bac3343bf92e6fa2bd852baf261e80712564f990
[ "MIT" ]
1
2020-12-23T08:14:57.000Z
2020-12-23T08:14:57.000Z
/****************************************************************************** * Copyright (C) 2014 by Ralf Kaestner * * ralf.kaestner@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the Lesser GNU General Public License as published by* * the Free Software Foundation; either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * Lesser GNU General Public License for more details. * * * * You should have received a copy of the Lesser GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #include "variant_topic_tools/DataTypeRegistry.h" #include "variant_topic_tools/Message.h" #include "variant_topic_tools/MessageDefinition.h" #include "variant_topic_tools/MessageSerializer.h" #include "variant_topic_tools/MessageVariant.h" namespace variant_topic_tools { /*****************************************************************************/ /* Constructors and Destructor */ /*****************************************************************************/ Message::Message() { } Message::Message(const Message& src) : header(src.header), type(src.type), data(src.data) { } Message::~Message() { } /*****************************************************************************/ /* Accessors */ /*****************************************************************************/ void Message::setHeader(const MessageHeader& header) { this->header = header; type.setMD5Sum(header["md5sum"]); type.setDataType(header["type"]); type.setDefinition(header["message_definition"]); } const MessageHeader& Message::getHeader() const { return header; } void Message::setType(const MessageType& type) { this->type = type; header["md5sum"] = type.getMD5Sum(); header["type"] = type.getDataType(); header["message_definition"] = type.getDefinition(); } const MessageType& Message::getType() const { return type; } void Message::setData(const std::vector<uint8_t>& data) { this->data = data; } std::vector<uint8_t>& Message::getData() { return data; } const std::vector<uint8_t>& Message::getData() const { return data; } void Message::setSize(size_t size) { data.resize(size); } size_t Message::getSize() const { return data.size(); } /*****************************************************************************/ /* Methods */ /*****************************************************************************/ void Message::serialize(const MessageVariant& variant) { MessageDataType dataType = variant.getType(); MessageType type(dataType.getIdentifier(), dataType.getMD5Sum(), dataType.getDefinition()); setType(type); MessageSerializer serializer = variant.createSerializer(); data.resize(serializer.getSerializedLength(variant)); ros::serialization::OStream stream(const_cast<uint8_t*>( data.data()), data.size()); serializer.serialize(stream, variant); } void Message::deserialize(MessageVariant& variant) const { DataTypeRegistry registry; DataType dataType = registry.getDataType(type.getDataType()); if (!dataType) { MessageDefinition definition(type); dataType = definition.getMessageDataType(); } variant = dataType.createVariant(); MessageSerializer serializer = variant.createSerializer(); ros::serialization::IStream stream(const_cast<uint8_t*>( data.data()), data.size()); serializer.deserialize(stream, variant); } boost::shared_ptr<variant_msgs::Variant> Message::toVariantMessage() const { boost::shared_ptr<variant_msgs::Variant> variant( new variant_msgs::Variant()); variant->header.publisher = header.getPublisher(); variant->header.topic = header.getTopic(); variant->header.latched = header.isLatched(); variant->type.data_type = type.getDataType(); variant->type.md5_sum = type.getMD5Sum(); variant->type.definition = type.getDefinition(); variant->data = data; return variant; } }
34
80
0.537173
[ "vector" ]
13438f836e5026b9c777c27232aa7639bcbe2c4d
18,710
cpp
C++
src/EnergyEfficientAgent.cpp
alawibaba/geopm
dc5dd54cf260b0b51d517bb50d1ba5db9e013c71
[ "BSD-3-Clause" ]
null
null
null
src/EnergyEfficientAgent.cpp
alawibaba/geopm
dc5dd54cf260b0b51d517bb50d1ba5db9e013c71
[ "BSD-3-Clause" ]
null
null
null
src/EnergyEfficientAgent.cpp
alawibaba/geopm
dc5dd54cf260b0b51d517bb50d1ba5db9e013c71
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015, 2016, 2017, 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sstream> #include <cmath> #include "contrib/json11/json11.hpp" #include "geopm.h" #include "geopm_hash.h" #include "geopm_message.h" #include "EnergyEfficientAgent.hpp" #include "PlatformIO.hpp" #include "PlatformTopo.hpp" #include "Helper.hpp" #include "Exception.hpp" #include "config.h" using json11::Json; namespace geopm { EnergyEfficientAgent::EnergyEfficientAgent() : EnergyEfficientAgent(platform_io(), platform_topo()) { } EnergyEfficientAgent::EnergyEfficientAgent(IPlatformIO &plat_io, IPlatformTopo &topo) : m_platform_io(plat_io) , m_platform_topo(topo) , m_freq_min(cpu_freq_min()) , m_freq_max(cpu_freq_max()) , M_FREQ_STEP(get_limit("CPUINFO::FREQ_STEP")) , M_SEND_PERIOD(10) , m_last_freq(NAN) , m_curr_adapt_freq(NAN) , m_last_wait{{0, 0}} { parse_env_map(); const char* env_freq_online_str = getenv("GEOPM_EFFICIENT_FREQ_ONLINE"); if (env_freq_online_str) { m_is_online = true; } init_platform_io(); } std::string EnergyEfficientAgent::plugin_name(void) { return "energy_efficient"; } std::unique_ptr<Agent> EnergyEfficientAgent::make_plugin(void) { return geopm::make_unique<EnergyEfficientAgent>(); } void EnergyEfficientAgent::init(int level, const std::vector<int> &fan_in, bool is_level_root) { m_level = level; if (level == 0) { m_num_children = 0; } else { m_num_children = fan_in[level - 1]; } } bool EnergyEfficientAgent::update_freq_range(const std::vector<double> &in_policy) { #ifdef GEOPM_DEBUG if (in_policy.size() != M_NUM_POLICY) { throw Exception("EnergyEfficientAgent::" + std::string(__func__) + "(): in_policy vector not correctly sized.", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } #endif bool result = false; double target_freq_min = std::isnan(in_policy[M_POLICY_FREQ_MIN]) ? cpu_freq_min() : in_policy[M_POLICY_FREQ_MIN]; double target_freq_max = std::isnan(in_policy[M_POLICY_FREQ_MAX]) ? cpu_freq_max() : in_policy[M_POLICY_FREQ_MAX]; if (target_freq_min > target_freq_max) { throw Exception("EnergyEfficientAgent::" + std::string(__func__) + "(): invalid frequency bounds.", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } if (m_freq_min != target_freq_min || m_freq_max != target_freq_max) { m_freq_min = target_freq_min; m_freq_max = target_freq_max; for (auto &eer : m_region_map) { eer.second->update_freq_range(m_freq_min, m_freq_max, M_FREQ_STEP); } result = true; } return result; } bool EnergyEfficientAgent::descend(const std::vector<double> &in_policy, std::vector<std::vector<double> >&out_policy) { #ifdef GEOPM_DEBUG if (out_policy.size() != (size_t) m_num_children) { throw Exception("EnergyEfficientAgent::" + std::string(__func__) + "(): out_policy vector not correctly sized.", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } #endif bool result = update_freq_range(in_policy); if (result) { for (auto &child_policy : out_policy) { #ifdef GEOPM_DEBUG if (child_policy.size() != M_NUM_POLICY) { throw Exception("EnergyEfficientAgent::" + std::string(__func__) + "(): child_policy vector not correctly sized.", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } #endif child_policy[M_POLICY_FREQ_MIN] = m_freq_min; child_policy[M_POLICY_FREQ_MAX] = m_freq_max; } } return result; } bool EnergyEfficientAgent::ascend(const std::vector<std::vector<double> > &in_sample, std::vector<double> &out_sample) { #ifdef GEOPM_DEBUG if (out_sample.size() != m_num_sample) { throw Exception("EnergyEfficientAgent::" + std::string(__func__) + "(): out_sample vector not correctly sized.", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } #endif bool result = false; if (m_num_ascend == 0) { aggregate_sample(in_sample, m_agg_func, out_sample); result = true; } ++m_num_ascend; if (m_num_ascend == M_SEND_PERIOD) { m_num_ascend = 0; } return result; } bool EnergyEfficientAgent::adjust_platform(const std::vector<double> &in_policy) { update_freq_range(in_policy); bool result = false; double freq = m_last_freq; auto it = m_rid_freq_map.find(geopm_region_id_hash(m_last_region_id)); if (it != m_rid_freq_map.end()) { freq = it->second; } else if (m_is_online) { if (!std::isnan(m_curr_adapt_freq)) { freq = m_curr_adapt_freq; } else { freq = m_freq_max - M_FREQ_STEP; } } else { switch(geopm_region_id_hint(m_last_region_id)) { // Hints for low CPU frequency case GEOPM_REGION_HINT_MEMORY: case GEOPM_REGION_HINT_NETWORK: case GEOPM_REGION_HINT_IO: freq = m_freq_min; break; // Hints for maximum CPU frequency case GEOPM_REGION_HINT_COMPUTE: case GEOPM_REGION_HINT_SERIAL: case GEOPM_REGION_HINT_PARALLEL: freq = m_freq_max; break; // Hint Inconclusive //case GEOPM_REGION_HINT_UNKNOWN: //case GEOPM_REGION_HINT_IGNORE: default: freq = m_freq_min; break; } } if (freq != m_last_freq) { /// freq initialized to m_last_freq but frequency bounds may have changed since /// the time of the caching. Need to make sure when we're within our bounds if (m_freq_min > freq) { freq = m_freq_min; } else if (m_freq_max < freq) { freq = m_freq_max; } for (auto ctl_idx : m_control_idx) { m_platform_io.adjust(ctl_idx, freq); } m_last_freq = freq; result = true; } return result; } bool EnergyEfficientAgent::sample_platform(std::vector<double> &out_sample) { #ifdef GEOPM_DEBUG if (out_sample.size() != m_num_sample) { throw Exception("EnergyEfficientAgent::" + std::string(__func__) + "(): out_sample vector not correctly sized.", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } #endif for (size_t sample_idx = 0; sample_idx < m_num_sample; ++sample_idx) { out_sample[sample_idx] = m_platform_io.sample(m_sample_idx[sample_idx]); } const uint64_t current_region_id = geopm_signal_to_field(m_platform_io.sample(m_signal_idx[M_SIGNAL_REGION_ID])); if (m_is_online) { if (current_region_id != GEOPM_REGION_ID_UNMARKED && current_region_id != GEOPM_REGION_ID_UNDEFINED) { bool is_region_boundary = m_last_region_id != current_region_id; if (is_region_boundary) { // set the freq for the current region (entry) auto region_it = m_region_map.find(current_region_id); if (region_it == m_region_map.end()) { auto tmp = m_region_map.emplace( current_region_id, std::unique_ptr<EnergyEfficientRegion>( new EnergyEfficientRegion(m_platform_io, m_freq_min, m_freq_max, M_FREQ_STEP, m_signal_idx[M_SIGNAL_RUNTIME], m_signal_idx[M_SIGNAL_PKG_ENERGY]))); region_it = tmp.first; } region_it->second->update_entry(); m_curr_adapt_freq = region_it->second->freq(); } if (m_last_region_id != 0 && is_region_boundary) { // update previous region (exit) auto region_it = m_region_map.find(m_last_region_id); if (region_it == m_region_map.end()) { auto tmp = m_region_map.emplace( m_last_region_id, std::unique_ptr<EnergyEfficientRegion>( new EnergyEfficientRegion(m_platform_io, m_freq_min, m_freq_max, M_FREQ_STEP, m_signal_idx[M_SIGNAL_RUNTIME], m_signal_idx[M_SIGNAL_PKG_ENERGY]))); region_it = tmp.first; } region_it->second->update_exit(); } } } m_last_region_id = current_region_id; return true; } void EnergyEfficientAgent::wait(void) { static double M_WAIT_SEC = 0.005; while(geopm_time_since(&m_last_wait) < M_WAIT_SEC) { } geopm_time(&m_last_wait); } std::vector<std::string> EnergyEfficientAgent::policy_names(void) { return {"FREQ_MIN", "FREQ_MAX"}; } std::vector<std::string> EnergyEfficientAgent::sample_names(void) { return {"ENERGY_PACKAGE"}; } std::vector<std::pair<std::string, std::string> > EnergyEfficientAgent::report_header(void) const { return {}; } std::vector<std::pair<std::string, std::string> > EnergyEfficientAgent::report_node(void) const { std::vector<std::pair<std::string, std::string> > result; std::ostringstream oss; for (const auto &region : m_region_map) { oss << region.first << ":" << region.second->freq() << " "; } if (m_region_map.size()) { result.push_back({"Final freq map", oss.str()}); } return result; } std::map<uint64_t, std::vector<std::pair<std::string, std::string> > > EnergyEfficientAgent::report_region(void) const { std::map<uint64_t, std::vector<std::pair<std::string, std::string> > > result; for (const auto &region : m_region_map) { result[region.first] = {std::make_pair("REQUESTED_FREQUENCY", std::to_string(region.second->freq()))}; } return result; } std::vector<std::string> EnergyEfficientAgent::trace_names(void) const { return {}; } void EnergyEfficientAgent::trace_values(std::vector<double> &values) { } double EnergyEfficientAgent::get_limit(const std::string &sig_name) const { const int domain_type = m_platform_io.signal_domain_type(sig_name); double result = NAN; const double sticker_freq = m_platform_io.read_signal("CPUINFO::FREQ_STICKER", domain_type, 0); if (sig_name == "CPUINFO::FREQ_MIN") { if (domain_type == IPlatformTopo::M_DOMAIN_INVALID) { if (m_platform_io.signal_domain_type("CPUINFO::FREQ_STICKER") == IPlatformTopo::M_DOMAIN_INVALID) { throw Exception("EnergyEfficientAgent::" + std::string(__func__) + "(): unable to parse min and sticker frequencies.", GEOPM_ERROR_DECIDER_UNSUPPORTED, __FILE__, __LINE__); } } else { result = m_platform_io.read_signal(sig_name, domain_type, 0); } } else if (sig_name == "CPUINFO::FREQ_MAX") { if (domain_type == IPlatformTopo::M_DOMAIN_INVALID) { if (m_platform_io.signal_domain_type("CPUINFO::FREQ_STICKER") == IPlatformTopo::M_DOMAIN_INVALID) { throw Exception("EnergyEfficientAgent::" + std::string(__func__) + "(): unable to parse max and sticker frequencies.", GEOPM_ERROR_DECIDER_UNSUPPORTED, __FILE__, __LINE__); } result = sticker_freq + M_FREQ_STEP; } else { result = m_platform_io.read_signal(sig_name, domain_type, 0); } } else if (sig_name == "CPUINFO::FREQ_STEP") { result = m_platform_io.read_signal(sig_name, domain_type, 0); } #ifdef GEOPM_DEBUG else { throw Exception("EnergyEfficientAgent::" + std::string(__func__) + "(): requested invalid signal name.", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } #endif return result; } void EnergyEfficientAgent::init_platform_io(void) { // All columns sampled will be in the trace for (auto sample : sample_names()) { m_sample_idx.push_back(m_platform_io.push_signal(sample, IPlatformTopo::M_DOMAIN_BOARD, 0)); m_agg_func.push_back(m_platform_io.agg_function(sample)); } m_num_sample = m_sample_idx.size(); const int freq_ctl_domain_type = m_platform_io.control_domain_type("FREQUENCY"); const int num_freq_ctl_domain = m_platform_topo.num_domain(freq_ctl_domain_type); for (int ctl_dom_idx = 0; ctl_dom_idx != num_freq_ctl_domain; ++ctl_dom_idx) { m_control_idx.push_back(m_platform_io.push_control("FREQUENCY", freq_ctl_domain_type, ctl_dom_idx)); } std::vector<std::string> signal_names = {"REGION_ID#", "REGION_RUNTIME", "ENERGY_PACKAGE", "ENERGY_DRAM",}; size_t signal = 0; m_signal_idx.push_back(m_platform_io.push_signal(signal_names[signal], IPlatformTopo::M_DOMAIN_BOARD, 0)); if (m_is_online) { // All signals needed for adaptive mode for (signal = 1; signal < signal_names.size(); ++signal) { m_signal_idx.push_back(m_platform_io.push_signal(signal_names[signal], IPlatformTopo::M_DOMAIN_BOARD, 0)); } } } void EnergyEfficientAgent::parse_env_map(void) { const char* env_freq_rid_map_str = getenv("GEOPM_EFFICIENT_FREQ_RID_MAP"); if (env_freq_rid_map_str) { std::string full_str(env_freq_rid_map_str); std::string err; Json root = Json::parse(full_str, err); if (!err.empty() || !root.is_object()) { throw Exception("EnergyEfficientAgent::" + std::string(__func__) + "(): detected a malformed json config file: " + err, GEOPM_ERROR_FILE_PARSE, __FILE__, __LINE__); } for (const auto &obj : root.object_items()) { if (obj.second.type() != Json::NUMBER) { throw Exception("EnergyEfficientAgent::" + std::string(__func__) + ": Region best-fit frequency must be a number", GEOPM_ERROR_FILE_PARSE, __FILE__, __LINE__); } uint64_t rid = geopm_crc32_str(0, obj.first.c_str()); m_rid_freq_map[rid] = obj.second.number_value(); } } } double EnergyEfficientAgent::cpu_freq_min(void) const { double result = NAN; const char* env_efficient_freq_min = getenv("GEOPM_EFFICIENT_FREQ_MIN"); if (env_efficient_freq_min) { try { result = std::stod(env_efficient_freq_min); } catch (const std::invalid_argument &) { } } if (std::isnan(result)) { result = get_limit("CPUINFO::FREQ_MIN"); } return result; } double EnergyEfficientAgent::cpu_freq_max(void) const { double result = NAN; const char* env_efficient_freq_max = getenv("GEOPM_EFFICIENT_FREQ_MAX"); if (env_efficient_freq_max) { try { result = std::stod(env_efficient_freq_max); } catch (const std::invalid_argument &) { } } if (std::isnan(result)) { result = get_limit("CPUINFO::FREQ_MAX"); } return result; } }
39.306723
138
0.569268
[ "vector" ]
134550203e4145d28143ef9f18baa55536cdeffa
5,568
hpp
C++
include/chemfiles/Topology.hpp
jjzhang166/chemfiles
8b5ca75ef5af9cd4499aaf79a78e0cbc6e83429a
[ "BSD-3-Clause" ]
null
null
null
include/chemfiles/Topology.hpp
jjzhang166/chemfiles
8b5ca75ef5af9cd4499aaf79a78e0cbc6e83429a
[ "BSD-3-Clause" ]
null
null
null
include/chemfiles/Topology.hpp
jjzhang166/chemfiles
8b5ca75ef5af9cd4499aaf79a78e0cbc6e83429a
[ "BSD-3-Clause" ]
null
null
null
// Chemfiles, a modern library for chemistry file reading and writing // Copyright (C) Guillaume Fraux and contributors -- BSD license #ifndef CHEMFILES_TOPOLOGY_HPP #define CHEMFILES_TOPOLOGY_HPP #include <vector> #include <unordered_map> #include "chemfiles/Atom.hpp" #include "chemfiles/Connectivity.hpp" #include "chemfiles/Residue.hpp" #include "chemfiles/exports.hpp" #include "chemfiles/optional.hpp" namespace chemfiles { /// A topology contains the definition of all the atoms in the system, and /// the liaisons between the particles (bonds, angles, dihedrals, ...). /// /// Only the atoms and the bonds are stored, the angles and the dihedrals are /// computed automaticaly. /// /// Iterating over a `Topology` will yield the atoms in the system. class CHFL_EXPORT Topology { public: using iterator = std::vector<Atom>::iterator; using const_iterator = std::vector<Atom>::const_iterator; /// Construct an empty topology Topology() {} Topology(const Topology&) = default; Topology& operator=(const Topology&) = default; Topology(Topology&&) = default; Topology& operator=(Topology&&) = default; /// Get a reference to the atom at the position `index`. /// /// @throws OutOfBounds if `index` is greater than `natoms()` Atom& operator[](size_t index) { if (index >= natoms()) { throw OutOfBounds( "Atomic index out of bounds in topology: we have " + std::to_string(natoms()) + " atoms, but the index is " + std::to_string(index) ); } return atoms_[index]; } /// Get a const (non-modifiable) reference to the atom at the position /// `index`. /// /// @throws OutOfBounds if `index` is greater than `natoms()` const Atom& operator[](size_t index) const { if (index >= natoms()) { throw OutOfBounds( "Atomic index out of bounds in topology: we have " + std::to_string(natoms()) + " atoms, but the index is " + std::to_string(index) ); } return atoms_[index]; } iterator begin() {return atoms_.begin();} const_iterator begin() const {return atoms_.begin();} const_iterator cbegin() const {return atoms_.cbegin();} iterator end() {return atoms_.end();} const_iterator end() const {return atoms_.end();} const_iterator cend() const {return atoms_.cend();} /// Add an `atom` at the end of this topology. void add_atom(Atom atom); /// Delete the atom at index `i` in the system. /// /// @throws OutOfBounds if `i` is greater than natoms() void remove(size_t i); /// Add a bond in the system, between the atoms at index `atom_i` and /// `atom_j`. /// /// @throws OutOfBounds if `atom_i` or `atom_j` are greater than `natoms()` void add_bond(size_t atom_i, size_t atom_j); /// Remove a bond in the system, between the atoms at index `atom_i` and /// `atom_j`. /// /// @throws OutOfBounds if `atom_i` or `atom_j` are greater than `natoms()` void remove_bond(size_t atom_i, size_t atom_j); /// Get the number of atoms in the topology size_t natoms() const { return atoms_.size(); } /// Resize the topology to hold `natoms` atoms, adding `UNDEFINED` atoms /// as needed. void resize(size_t natoms); /// Reserve size in the topology to store data for `natoms` atoms. void reserve(size_t natoms); /// Get the bonds in the system, in a sorted vector const std::vector<Bond>& bonds() const; /// Get the angles in the system, in a sorted vector const std::vector<Angle>& angles() const; /// Get the dihedral angles in the system, in a sorted vector const std::vector<Dihedral>& dihedrals() const; /// Get the improper dihedral angles in the system, in a sorted vector const std::vector<Improper>& impropers() const; /// Remove all bonding information in the topology (bonds, angles and /// dihedrals) void clear_bonds() { connect_ = Connectivity(); } /// Add a `residue` to this topology. /// /// This function throws a `chemfiles::Error` if any atom in the `residue` /// is already in another residue in this topology. In that case, the /// topology is not modified. void add_residue(Residue residue); /// Check if two residues are linked together, i.e. if there is a bond /// between one atom in the `first` residue and one atom in the `second` /// one. Both residues should be in this topology. /// /// If `first == second`, this function returns `true`. bool are_linked(const Residue& first, const Residue& second) const; /// Get the residue containing the `atom` at the given index. optional<const Residue&> residue(size_t atom) const; /// Get all the residues in the topology const std::vector<Residue>& residues() const { return residues_; } private: /// Check wether the atoms at indexes `i` and `j` are bonded or not bool is_bond(size_t i, size_t j) const; /// Atoms in the system. std::vector<Atom> atoms_; /// Connectivity of the system. All the indexes refers to the positions in /// `atoms_` Connectivity connect_; /// List of residues in the system. All the indexes refers to the positions /// in `atoms_` std::vector<Residue> residues_; /// Association between atom indexes and residues indexes. std::unordered_map<size_t, size_t> residue_mapping_; }; } // namespace chemfiles #endif
35.240506
79
0.649246
[ "vector" ]
1346a4cc04eb552ce49cf85003723b98bdae000c
2,107
cpp
C++
examples/hello-triangle/binary_triangle_two_vbo.cpp
cjdb/doge
421e1dce86df0eb73a6907408e93d0982adf057d
[ "Apache-2.0" ]
6
2017-10-13T23:01:29.000Z
2019-07-05T16:04:51.000Z
examples/hello-triangle/binary_triangle_two_vbo.cpp
cjdb/doge
421e1dce86df0eb73a6907408e93d0982adf057d
[ "Apache-2.0" ]
46
2018-02-05T21:54:11.000Z
2018-03-12T10:00:08.000Z
examples/hello-triangle/binary_triangle_two_vbo.cpp
cjdb/doge
421e1dce86df0eb73a6907408e93d0982adf057d
[ "Apache-2.0" ]
3
2018-02-07T14:15:51.000Z
2018-03-01T11:40:54.000Z
// // Copyright 2017 Christopher Di Bella // // 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 <gl/gl_core.hpp> #include <doge/engine.hpp> #include <doge/gl/vertex_array.hpp> #include <doge/gl/shader_binary.hpp> #include <doge/gl/shader_source.hpp> #include <doge/utility/screen_data.hpp> #include <doge/hid.hpp> #include <glm/vec3.hpp> #include "../static_objects.hpp" #include <vector> namespace ranges = std::experimental::ranges; int main() { auto engine = doge::engine{}; auto shaders = std::vector<doge::shader_binary>{ {{std::make_pair(doge::shader_source::vertex, "vertex.glsl"), std::make_pair(doge::shader_source::fragment, "fragment.glsl")}}, {{std::make_pair(doge::shader_source::vertex, "vertex.glsl"), std::make_pair(doge::shader_source::fragment, "yellow.glsl")}} }; auto vbo = []{ auto result = std::vector<doge::vertex_array_buffer<doge::basic_buffer_usage::static_draw, doge::vec3>>{}; result.emplace_back(triangle[0]); result.emplace_back(triangle[1]); return result; }(); engine.play([&]{ doge::hid::on_key_press<doge::hid::keyboard>(GLFW_KEY_ESCAPE, [&engine]{ engine.close(); }); gl::ClearColor(0.2f, 0.3f, 0.4f, 1.0f); gl::Clear(gl::COLOR_BUFFER_BIT); using std::experimental::ranges::Integral; for (Integral i = decltype(vbo.size()){}; i != vbo.size() && i != shaders.size(); ++i) { shaders[i].use([i, &vbo]{ vbo[i].draw([]{}); }); } }); }
34.540984
99
0.639298
[ "vector" ]
134936b5f655418d4f7f725f338edf81194ad377
4,799
cpp
C++
VGP332/HelloSteering/Interceptor.cpp
CyroPCJr/OmegaEngine
65fbd6cff54266a9c934e3a875a4493d26758661
[ "MIT" ]
1
2021-04-23T19:18:12.000Z
2021-04-23T19:18:12.000Z
VGP332/HelloSteering/Interceptor.cpp
CyroPCJr/OmegaEngine
65fbd6cff54266a9c934e3a875a4493d26758661
[ "MIT" ]
null
null
null
VGP332/HelloSteering/Interceptor.cpp
CyroPCJr/OmegaEngine
65fbd6cff54266a9c934e3a875a4493d26758661
[ "MIT" ]
1
2021-06-15T10:42:08.000Z
2021-06-15T10:42:08.000Z
#include "Interceptor.h" #include "UnitType.h" using namespace Steering; using namespace Omega; using namespace Omega::Graphics; using namespace Omega::Math; using namespace Omega::AI; namespace { float width = 0.0f; float height = 0.0f; } Interceptor::Interceptor(AIWorld& world) noexcept : Agent(world, UnitType::Interceptor) { mSteeringModule = std::make_unique<SteeringModule>(*this); } void Interceptor::Load() { // Load images for (size_t i = 0; i < mTexturesIds.size(); ++i) { char name[128]; sprintf_s(name, "Sprites/interceptor_%02zu.png", i + 1); mTexturesIds[i] = SpriteRendererManager::Get()->LoadTexture(name); } // Initial settings auto worldSize = world.GetSettings(); width = worldSize.worldSize.x; height = worldSize.worldSize.y; maxSpeed = 200.0f; // Group Behaviours mSteeringModule->AddBehavior<AI::AlignmentBehaviour>("Alignment"); mSteeringModule->AddBehavior<AI::CohesionBehaviour>("Cohesion"); mSteeringModule->AddBehavior<AI::SeparationBehaviour>("Separation"); // Steerin Behaviours mSteeringModule->AddBehavior<AI::ArriveBehaviour>("Arrive"); mSteeringModule->AddBehavior<AI::EvadeBehaviour>("Evade"); mSteeringModule->AddBehavior<AI::FleeBehaviour>("Flee"); mSteeringModule->AddBehavior<AI::HideBehaviour>("Hide"); mSteeringModule->AddBehavior<AI::ObstacleAvoidance>("Avoidance"); mSteeringModule->AddBehavior<AI::PursuitBehaviour>("Pursuit"); mSteeringModule->AddBehavior<AI::WanderBehaviour>("Wandering"); mSteeringModule->AddBehavior<AI::Interpose>("Interpose"); // Initial steering mSteeringModule->GetBehavior<AI::WanderBehaviour>("Wandering")->SetActive(true); } void Interceptor::Unload() { mSteeringModule.reset(); } void Interceptor::Update(float deltaTime) { neighbors = world.GetNeighborhood({ position, 100.0f }, UnitType::Interceptor); // To avoid warning in compilation, I used [[maybe_unused]]. // The reason that std::remove_if return type is flagged with [[no_discard]] [[maybe_unused]] auto notUsed = std::remove_if(neighbors.begin(), neighbors.end(), [this](auto neighbor) { return this == neighbor; }); destination = threat->position; auto force = mSteeringModule->Calculate(); auto acceleration = (force / mass); velocity += acceleration * deltaTime; velocity = Truncate(velocity, maxSpeed); position += velocity * deltaTime; if (Magnitude(velocity) > 0.0f) { heading = Normalize(velocity); } // show debug draw if (isDebugShowDraw) { mSteeringModule->ShowDebugDraw(); } if (position.x < 0.0f) // left border { position.x += width; } if (position.x >= width) // right border { position.x -= width; } if (position.y < 0.0f) // botton border { position.y += height; } if (position.y >= height) // top border { position.y -= height; } } void Interceptor::Render() { const float angle = atan2(-heading.x, heading.y) + Math::Constants::Pi; const size_t numFrames = mTexturesIds.size(); size_t index = static_cast<size_t>(angle / Math::Constants::TwoPi * numFrames); SpriteRendererManager::Get()->DrawSprite(mTexturesIds[index], position); } void Interceptor::SwitchBehaviour(const Behaviours& behaviours, bool active) const { switch (behaviours) { case Interceptor::Behaviours::Alignment: mSteeringModule->GetBehavior<AI::AlignmentBehaviour>("Alignment")->SetActive(active); break; case Interceptor::Behaviours::Cohesion: mSteeringModule->GetBehavior<AI::CohesionBehaviour>("Cohesion")->SetActive(active); break; case Interceptor::Behaviours::Separation: mSteeringModule->GetBehavior<AI::SeparationBehaviour>("Separation")->SetActive(active); break; case Interceptor::Behaviours::Evade: mSteeringModule->GetBehavior<AI::EvadeBehaviour>("Evade")->SetActive(active); break; case Interceptor::Behaviours::Flee: mSteeringModule->GetBehavior<AI::FleeBehaviour>("Cohesion")->SetActive(active); break; case Interceptor::Behaviours::Hide: mSteeringModule->GetBehavior<AI::HideBehaviour>("Hide")->SetActive(active); break; case Interceptor::Behaviours::ObstacleAvoidance: mSteeringModule->GetBehavior<AI::ObstacleAvoidance>("Avoidance")->SetActive(active); break; case Interceptor::Behaviours::Pursuit: mSteeringModule->GetBehavior<AI::PursuitBehaviour>("Pursuit")->SetActive(active); break; case Interceptor::Behaviours::Wandering: mSteeringModule->GetBehavior<AI::WanderBehaviour>("Wandering")->SetActive(active); break; case Interceptor::Behaviours::Interpose: mSteeringModule->GetBehavior<AI::Interpose>("Interpose")->SetActive(active); break; default: mSteeringModule->GetBehavior<AI::WanderBehaviour>("Wandering")->SetActive(active); break; } }
31.162338
90
0.715982
[ "render" ]
134c3dba973a6366c4073dd461443a66e59399a5
10,655
cpp
C++
apps/rand_forest/src/rand_forest_engine.cpp
daiwei89/wdai_petuum_public
4068859897061201d0a63630a3da6011b0d0f75f
[ "BSD-3-Clause" ]
null
null
null
apps/rand_forest/src/rand_forest_engine.cpp
daiwei89/wdai_petuum_public
4068859897061201d0a63630a3da6011b0d0f75f
[ "BSD-3-Clause" ]
null
null
null
apps/rand_forest/src/rand_forest_engine.cpp
daiwei89/wdai_petuum_public
4068859897061201d0a63630a3da6011b0d0f75f
[ "BSD-3-Clause" ]
null
null
null
// Author: Jiesi Zhao (jiesizhao0423@gmail.com), Wei Dai (wdai@cs.cmu.edu) // Date: 2014.11.6 #include "common.hpp" #include "decision_tree.hpp" #include "rand_forest.hpp" #include "rand_forest_engine.hpp" #include <ml/include/ml.hpp> #include <vector> #include <cstdint> #include <atomic> #include <cmath> #include <iostream> #include <fstream> #include <iterator> #include <algorithm> #include <petuum_ps_common/include/petuum_ps.hpp> namespace tree { RandForestEngine::RandForestEngine() : num_train_data_(0), num_test_data_(0), feature_dim_(0), num_labels_(0), num_train_eval_(0), num_test_eval_(0), read_format_("libsvm"), feature_one_based_(0), label_one_based_(0), thread_counter_(0) { process_barrier_.reset(new boost::barrier(FLAGS_num_app_threads)); perform_test_ = FLAGS_perform_test; // Params for saving prediction on test set save_pred_ = FLAGS_save_pred; pred_file_ = FLAGS_pred_file; if (save_pred_) { CHECK(!pred_file_.empty()) << "Need to specify a prediction " "output file path."; } // Params for saving trained trees save_trees_ = FLAGS_save_trees; output_file_ = FLAGS_output_file + ".part" + std::to_string(FLAGS_client_id); if (save_trees_) { CHECK(!output_file_.empty()) << "Need to specify an output " "file path."; } // Params for loading trees load_trees_ = FLAGS_load_trees; input_file_ = FLAGS_input_file; if (load_trees_) { CHECK(!input_file_.empty()) << "Need to specify an input " "file path."; } if (!load_trees_) { SetReader(); } else { // Only set meta file reader for test file std::string test_meta_file = FLAGS_test_file + ".meta"; petuum::ml::MetafileReader mreader_test(test_meta_file); num_test_data_ = mreader_test.get_int32("num_test"); feature_dim_ = mreader_test.get_int32("feature_dim"); num_labels_ = mreader_test.get_int32("num_labels"); read_format_ = mreader_test.get_string("format"); feature_one_based_ = mreader_test.get_bool("feature_one_based"); label_one_based_ = mreader_test.get_bool("label_one_based"); } } void RandForestEngine::SetReader() { // Append client_id if the train_data isn't global. std::string meta_file = FLAGS_train_file + (FLAGS_global_data ? "" : "." + std::to_string(FLAGS_client_id)) + ".meta"; petuum::ml::MetafileReader mreader(meta_file); num_train_data_ = mreader.get_int32("num_train_this_partition"); num_train_data_ = std::max(num_train_data_, FLAGS_num_train_data); feature_dim_ = mreader.get_int32("feature_dim"); num_labels_ = mreader.get_int32("num_labels"); read_format_ = mreader.get_string("format"); feature_one_based_ = mreader.get_bool("feature_one_based"); label_one_based_ = mreader.get_bool("label_one_based"); // Read test meta file. if (perform_test_) { std::string test_meta_file = FLAGS_test_file + ".meta"; petuum::ml::MetafileReader mreader_test(test_meta_file); num_test_data_ = mreader_test.get_int32("num_test"); CHECK_EQ(feature_dim_, mreader_test.get_int32("feature_dim")); CHECK_EQ(num_labels_, mreader_test.get_int32("num_labels")); CHECK_EQ(read_format_, mreader_test.get_string("format")); CHECK_EQ(feature_one_based_, mreader_test.get_bool("feature_one_based")); CHECK_EQ(label_one_based_, mreader_test.get_bool("label_one_based")); } // If save trees to file, check if the file exists. // If exists, clear the file. If not, create the file. if (save_trees_) { std::ofstream fout; fout.open(output_file_, std::ios::out); fout.close(); } } void RandForestEngine::ReadData(std::string type) { if (type == "train") { std::string train_file = FLAGS_train_file + (FLAGS_global_data ? "" : "." + std::to_string(FLAGS_client_id)); LOG(INFO) << "Reading train file: " << train_file; if (read_format_ == "bin") { petuum::ml::ReadDataLabelBinary(train_file, feature_dim_, num_train_data_, &train_features_, &train_labels_); } else if (read_format_ == "libsvm") { petuum::ml::ReadDataLabelLibSVM(train_file, feature_dim_, num_train_data_, &train_features_, &train_labels_, feature_one_based_, label_one_based_); } } if (type == "test") { if (read_format_ == "bin") { LOG(INFO) << "Reading test file: " << FLAGS_test_file; petuum::ml::ReadDataLabelBinary(FLAGS_test_file, feature_dim_, num_test_data_, &test_features_, &test_labels_); } else if (read_format_ == "libsvm") { LOG(INFO) << "Reading test file: " << FLAGS_test_file; petuum::ml::ReadDataLabelLibSVM(FLAGS_test_file, feature_dim_, num_test_data_, &test_features_, &test_labels_, feature_one_based_, label_one_based_); } } } void RandForestEngine::Start() { petuum::PSTableGroup::RegisterThread(); // Initialize local thread data structures. int thread_id = thread_counter_++; DecisionTreeConfig dt_config; dt_config.max_depth = FLAGS_max_depth; dt_config.num_data_subsample = FLAGS_num_data_subsample; dt_config.num_features_subsample = FLAGS_num_features_subsample; dt_config.num_labels = num_labels_; dt_config.feature_dim = feature_dim_; dt_config.features = &train_features_; dt_config.labels = &train_labels_; // Set number of trees assigned to each thread int num_trees_per_thread = std::floor(static_cast<float>(FLAGS_num_trees) / (FLAGS_num_clients * FLAGS_num_app_threads)); int num_left_trees = FLAGS_num_trees - FLAGS_num_clients * FLAGS_num_app_threads * num_trees_per_thread; int num_left_clients = std::floor(static_cast<float>(num_left_trees) / FLAGS_num_app_threads); num_left_trees -= num_left_clients * FLAGS_num_app_threads; if (FLAGS_client_id < num_left_clients) { num_trees_per_thread ++; } else if ((FLAGS_client_id == num_left_clients) && (thread_id < num_left_trees)) { num_trees_per_thread ++; } RandForestConfig rf_config; rf_config.client_id = FLAGS_client_id; rf_config.thread_id = thread_id; rf_config.num_threads = FLAGS_num_app_threads; rf_config.num_trees = num_trees_per_thread; rf_config.save_trees = save_trees_; rf_config.tree_config = dt_config; if (thread_id == 0) { test_vote_table_ = petuum::PSTableGroup::GetTableOrDie<int>(FLAGS_test_vote_table_id); } // Barrier to ensure test_vote_table_ is initialized. process_barrier_->wait(); // Build the trees. RandForest rand_forest(rf_config); // Load trees from file and perform test. Use only one thread. if (load_trees_) { if (FLAGS_client_id == 0 && thread_id == 0) { rand_forest.LoadTrees(input_file_); LOG(INFO) << "Trees loaded from file."; // Evaluating overall test error float test_error = VoteOnTestData(rand_forest); test_error = ComputeTestError(); petuum::PSTableGroup::GlobalBarrier(); LOG(INFO) << "Test error: " << test_error << " computed on " << test_features_.size() << " test instances."; petuum::PSTableGroup::DeregisterThread(); } return; } // Train the trees if (FLAGS_client_id == 0 && thread_id == 0) { LOG(INFO) << "Each thread train about " << num_trees_per_thread << " trees."; } rand_forest.Train(); // Save trained trees to file if (save_trees_) { rand_forest.SaveTrees(output_file_); } // Evaluating training error on one thread of each machine. if (thread_id == 0) { float train_error = EvaluateErrorLocal(rand_forest, train_features_, train_labels_); LOG(INFO) << "Approximate train error: " << train_error << " (evaluated on " << num_train_data_ << " training data on thread 0 of each client.)"; } // Test error. if (perform_test_) { VoteOnTestData(rand_forest); petuum::PSTableGroup::GlobalBarrier(); // Evaluating overall test error if (FLAGS_client_id == 0 && thread_id == 0) { petuum::HighResolutionTimer test_timer; float test_error = ComputeTestError(); LOG(INFO) << "Test error: " << test_error << " computed on " << test_features_.size() << " test instances in " << test_timer.elapsed() << " seconds"; } } petuum::PSTableGroup::DeregisterThread(); } // =========== Private Functions ============= float RandForestEngine::EvaluateErrorLocal(const RandForest& rand_forest, const std::vector<petuum::ml::AbstractFeature<float>*>& features, const std::vector<int32_t>& labels) { float error = 0.; for (int i = 0; i < features.size(); ++i) { const petuum::ml::AbstractFeature<float>& x = *(features[i]); int pred_label = rand_forest.Predict(x); error += (labels[i] == pred_label) ? 0 : 1.; } return error / features.size(); } float RandForestEngine::VoteOnTestData(const RandForest& rand_forest) { float error = 0.; for (int i = 0; i < test_features_.size(); ++i) { std::vector<int> votes; const petuum::ml::AbstractFeature<float>& x = *(test_features_[i]); int pred_label = rand_forest.Predict(x, &votes); error += (test_labels_[i] == pred_label) ? 0 : 1.; // add votes to test_vote_table_ petuum::UpdateBatch<int> vote_update_batch(num_labels_); for (int j = 0; j < num_labels_; ++j) { vote_update_batch.UpdateSet(j, j, votes[j]); } test_vote_table_.BatchInc(i, vote_update_batch); } return error / test_features_.size(); } namespace { int SumVector(const std::vector<int> vec) { int sum = 0; for (const auto& elem : vec) { sum += elem; } return sum; } } // anonymous namespace float RandForestEngine::ComputeTestError() { // Head thread collects the votes. float error = 0.; int num_trees = 0; // Save predict result to file std::ofstream fpred; if (save_pred_) { fpred.open(pred_file_, std::ios::out); CHECK(fpred != NULL) << "Cannot open prediction output file "; } for (int i = 0; i < test_features_.size(); ++i) { petuum::RowAccessor row_acc; test_vote_table_.Get(i, &row_acc); const auto& test_vote_row = row_acc.Get<petuum::DenseRow<int> >(); std::vector<int> test_votes; test_vote_row.CopyToVector(&test_votes); int max_label = 0; for (int j = 1; j < num_labels_; ++j) { if (test_votes[max_label] < test_votes[j]) { max_label = j; } } if (save_pred_) { fpred << max_label << std::endl; } error += (test_labels_[i] == max_label) ? 0 : 1.; if (i == 0) { num_trees = SumVector(test_votes); } else { CHECK_EQ(num_trees, SumVector(test_votes)); } } LOG(INFO) << "Test using " << num_trees << " trees."; return error / test_features_.size(); } } // namespace tree
33.825397
81
0.686157
[ "vector" ]
134f1034870c9cd442257e2051d68458fcce16de
22,027
cpp
C++
libs/scripting/lua/cocos2dx_support/CCLuaEngine.cpp
qq2588258/floweers
c7f117f29dee21473821b89ff9b18058f7ebdadf
[ "MIT" ]
17
2015-01-09T07:34:32.000Z
2021-06-25T02:50:03.000Z
libs/scripting/lua/cocos2dx_support/CCLuaEngine.cpp
qq2588258/floweers
c7f117f29dee21473821b89ff9b18058f7ebdadf
[ "MIT" ]
null
null
null
libs/scripting/lua/cocos2dx_support/CCLuaEngine.cpp
qq2588258/floweers
c7f117f29dee21473821b89ff9b18058f7ebdadf
[ "MIT" ]
4
2015-01-24T02:48:46.000Z
2020-07-02T06:29:06.000Z
/**************************************************************************** Copyright (c) 2011 cocos2d-x.org http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCLuaEngine.h" #include "cocos2d.h" #include "cocoa/CCArray.h" #include "CCScheduler.h" #include "LuaScriptHandlerMgr.h" #include "GUI/CCControlExtension/CCControl.h" #include "LuaOpengl.h" NS_CC_BEGIN LuaEngine* LuaEngine::_defaultEngine = NULL; LuaEngine* LuaEngine::getInstance(void) { if (!_defaultEngine) { _defaultEngine = new LuaEngine(); _defaultEngine->init(); } return _defaultEngine; } LuaEngine::~LuaEngine(void) { CC_SAFE_RELEASE(_stack); _defaultEngine = NULL; } bool LuaEngine::init(void) { _stack = LuaStack::create(); _stack->retain(); extendLuaObject(); //executeScriptFile("Deprecated.lua"); // 在lua里面require return true; } void LuaEngine::addSearchPath(const char* path) { _stack->addSearchPath(path); } void LuaEngine::addLuaLoader(lua_CFunction func) { _stack->addLuaLoader(func); } void LuaEngine::removeScriptObjectByObject(Object* pObj) { _stack->removeScriptObjectByObject(pObj); ScriptHandlerMgr::getInstance()->removeObjectAllHandlers(pObj); } void LuaEngine::removeScriptHandler(int nHandler) { _stack->removeScriptHandler(nHandler); } int LuaEngine::executeString(const char *codes) { int ret = _stack->executeString(codes); _stack->clean(); return ret; } int LuaEngine::executeScriptFile(const char* filename) { int ret = _stack->executeScriptFile(filename); _stack->clean(); return ret; } int LuaEngine::executeGlobalFunction(const char* functionName) { int ret = _stack->executeGlobalFunction(functionName); _stack->clean(); return ret; } int LuaEngine::executeNodeEvent(Node* pNode, int nAction) { return 0; } int LuaEngine::executeMenuItemEvent(MenuItem* pMenuItem) { return 0; } int LuaEngine::executeNotificationEvent(NotificationCenter* pNotificationCenter, const char* pszName) { int nHandler = pNotificationCenter->getObserverHandlerByName(pszName); if (!nHandler) return 0; _stack->pushString(pszName); int ret = _stack->executeFunctionByHandler(nHandler, 1); _stack->clean(); return ret; } int LuaEngine::executeCallFuncActionEvent(CallFunc* pAction, Object* pTarget/* = NULL*/) { return 0; } int LuaEngine::executeSchedule(int nHandler, float dt, Node* pNode/* = NULL*/) { if (!nHandler) return 0; _stack->pushFloat(dt); int ret = _stack->executeFunctionByHandler(nHandler, 1); _stack->clean(); return ret; } int LuaEngine::executeLayerTouchEvent(Layer* pLayer, int eventType, Touch *pTouch) { return 0; } int LuaEngine::executeLayerTouchesEvent(Layer* pLayer, int eventType, Set *pTouches) { return 0; } int LuaEngine::executeLayerKeypadEvent(Layer* pLayer, int eventType) { return 0; } int LuaEngine::executeAccelerometerEvent(Layer* pLayer, Acceleration* pAccelerationValue) { return 0; } int LuaEngine::executeEvent(int nHandler, const char* pEventName, Object* pEventSource /* = NULL*/, const char* pEventSourceClassName /* = NULL*/) { _stack->pushString(pEventName); if (pEventSource) { _stack->pushObject(pEventSource, pEventSourceClassName ? pEventSourceClassName : "CCObject"); } int ret = _stack->executeFunctionByHandler(nHandler, pEventSource ? 2 : 1); _stack->clean(); return ret; } bool LuaEngine::handleAssert(const char *msg) { bool ret = _stack->handleAssert(msg); _stack->clean(); return ret; } int LuaEngine::reallocateScriptHandler(int nHandler) { int nRet = _stack->reallocateScriptHandler(nHandler); _stack->clean(); return nRet; } int LuaEngine::sendEvent(ScriptEvent* evt) { if (NULL == evt) return 0; switch (evt->type) { case kNodeEvent: { return handleNodeEvent(evt->data); } break; case kMenuClickedEvent: { return handleMenuClickedEvent(evt->data); } break; case kNotificationEvent: { return handleNotificationEvent(evt->data); } break; case kCallFuncEvent: { return handleCallFuncActionEvent(evt->data); } break; case kScheduleEvent: { return handleScheduler(evt->data); } break; case kTouchEvent: { return handleTouchEvent(evt->data); } break; case kTouchesEvent: { return handleTouchesEvent(evt->data); } break; case kKeypadEvent: { return handleKeypadEvent(evt->data); } break; case kAccelerometerEvent: { return handleAccelerometerEvent(evt->data); } break; case kCommonEvent: { return handleCommonEvent(evt->data); } break; case kControlEvent: { return handlerControlEvent(evt->data); } break; default: break; } return 0; } int LuaEngine::handleNodeEvent(void* data) { if (NULL == data) return 0; BasicScriptData* basicScriptData = (BasicScriptData*)data; if (NULL == basicScriptData->nativeObject || NULL == basicScriptData->value) return 0; int handler = ScriptHandlerMgr::getInstance()->getObjectHandler(basicScriptData->nativeObject, ScriptHandlerMgr::kNodeHandler); if (0 == handler) return 0; int action = *((int*)(basicScriptData->value)); switch (action) { case kNodeOnEnter: _stack->pushString("enter"); break; case kNodeOnExit: _stack->pushString("exit"); break; case kNodeOnEnterTransitionDidFinish: _stack->pushString("enterTransitionFinish"); break; case kNodeOnExitTransitionDidStart: _stack->pushString("exitTransitionStart"); break; case kNodeOnCleanup: _stack->pushString("cleanup"); break; default: return 0; } int ret = _stack->executeFunctionByHandler(handler, 1); _stack->clean(); return ret; } int LuaEngine::handleMenuClickedEvent(void* data) { if (NULL == data) return 0; BasicScriptData* basicScriptData = (BasicScriptData*)data; if (NULL == basicScriptData->nativeObject) return 0; MenuItem* menuItem = static_cast<MenuItem*>(basicScriptData->nativeObject); int handler = ScriptHandlerMgr::getInstance()->getObjectHandler(menuItem, ScriptHandlerMgr::kMenuClickHandler); if (0 == handler) return 0; _stack->pushInt(menuItem->getTag()); _stack->pushObject(menuItem, "CCMenuItem"); int ret = _stack->executeFunctionByHandler(handler, 2); _stack->clean(); return ret; } int LuaEngine::handleNotificationEvent(void* data) { if ( NULL == data) return 0; BasicScriptData* basicScriptData = (BasicScriptData*)(data); if (NULL == basicScriptData->nativeObject ||NULL == basicScriptData->value) return 0; NotificationCenter* center = static_cast<NotificationCenter*>(basicScriptData->nativeObject); int handler = center->getObserverHandlerByName((const char*)basicScriptData->value); if (0 == handler) return 0; _stack->pushString((const char*)basicScriptData->value); int ret = _stack->executeFunctionByHandler(handler, 1); _stack->clean(); return ret; } int LuaEngine::handleCallFuncActionEvent(void* data) { if (NULL == data) return 0; BasicScriptData* basicScriptData = static_cast<BasicScriptData*>(data); if (NULL == basicScriptData->nativeObject) return 0; int handler =ScriptHandlerMgr::getInstance()->getObjectHandler(basicScriptData->nativeObject, ScriptHandlerMgr::kCallFuncHandler); if (0 == handler) return 0; Object* target = static_cast<Object*>(basicScriptData->value); if (NULL != target) { _stack->pushObject(target, "CCNode"); } int ret = _stack->executeFunctionByHandler(handler, target ? 1 : 0); _stack->clean(); return ret; } int LuaEngine::handleScheduler(void* data) { if (NULL == data) return 0; SchedulerScriptData* schedulerInfo = static_cast<SchedulerScriptData*>(data); _stack->pushFloat(schedulerInfo->elapse); int ret = _stack->executeFunctionByHandler(schedulerInfo->handler, 1); _stack->clean(); return ret; } int LuaEngine::handleKeypadEvent(void* data) { if (NULL == data) return 0; KeypadScriptData* keypadScriptData = static_cast<KeypadScriptData*>(data); if (NULL == keypadScriptData->nativeObject) return 0; int handler = ScriptHandlerMgr::getInstance()->getObjectHandler(keypadScriptData->nativeObject, ScriptHandlerMgr::kKeypadHandler); if (0 == handler) return 0; int action = keypadScriptData->actionType; switch (action) { case kTypeBackClicked: _stack->pushString("backClicked"); break; case kTypeMenuClicked: _stack->pushString("menuClicked"); break; default: return 0; } int ret = _stack->executeFunctionByHandler(handler, 1); _stack->clean(); return ret; } int LuaEngine::handleAccelerometerEvent(void* data) { if (NULL == data) return 0; BasicScriptData* basicScriptData = static_cast<BasicScriptData*>(data); if (NULL == basicScriptData->nativeObject || NULL == basicScriptData->value) return 0; int handler = ScriptHandlerMgr::getInstance()->getObjectHandler(basicScriptData->nativeObject, ScriptHandlerMgr::kAccelerometerHandler); if (0 == handler) return 0; Acceleration* accelerationValue = static_cast<Acceleration*>(basicScriptData->value); _stack->pushFloat(accelerationValue->x); _stack->pushFloat(accelerationValue->y); _stack->pushFloat(accelerationValue->z); _stack->pushFloat(accelerationValue->timestamp); int ret = _stack->executeFunctionByHandler(handler, 4); _stack->clean(); return ret; } int LuaEngine::handleCommonEvent(void* data) { if (NULL == data) return 0; CommonScriptData* commonInfo = static_cast<CommonScriptData*>(data); if (NULL == commonInfo->eventName || 0 == commonInfo->handler) return 0; _stack->pushString(commonInfo->eventName); if (NULL != commonInfo->eventSource) { if (NULL != commonInfo->eventSourceClassName && strlen(commonInfo->eventSourceClassName) > 0) { _stack->pushObject(commonInfo->eventSource, commonInfo->eventSourceClassName); } else { _stack->pushObject(commonInfo->eventSource, "CCObject"); } } int ret = _stack->executeFunctionByHandler(commonInfo->handler, commonInfo->eventSource ? 2 : 1); _stack->clean(); return ret; } int LuaEngine::handleTouchEvent(void* data) { if (NULL == data) return 0; TouchScriptData* touchScriptData = static_cast<TouchScriptData*>(data); if (NULL == touchScriptData->nativeObject || NULL == touchScriptData->touch) return 0; int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)touchScriptData->nativeObject, ScriptHandlerMgr::kTouchesHandler); if (0 == handler) return 0; switch (touchScriptData->actionType) { case CCTOUCHBEGAN: _stack->pushString("began"); break; case CCTOUCHMOVED: _stack->pushString("moved"); break; case CCTOUCHENDED: _stack->pushString("ended"); break; case CCTOUCHCANCELLED: _stack->pushString("cancelled"); break; default: return 0; } int ret = 0; Touch* touch = touchScriptData->touch; if (NULL != touch) { const Point pt = Director::getInstance()->convertToGL(touch->getLocationInView()); _stack->pushFloat(pt.x); _stack->pushFloat(pt.y); ret = _stack->executeFunctionByHandler(handler, 3); } _stack->clean(); return ret; } int LuaEngine::handleTouchesEvent(void* data) { if (NULL == data) return 0; TouchesScriptData* touchesScriptData = static_cast<TouchesScriptData*>(data); if (NULL == touchesScriptData->nativeObject || NULL == touchesScriptData->touches) return 0; int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)touchesScriptData->nativeObject, ScriptHandlerMgr::kTouchesHandler); if (0 == handler) return 0; switch (touchesScriptData->actionType) { case CCTOUCHBEGAN: _stack->pushString("began"); break; case CCTOUCHMOVED: _stack->pushString("moved"); break; case CCTOUCHENDED: _stack->pushString("ended"); break; case CCTOUCHCANCELLED: _stack->pushString("cancelled"); break; default: return 0; } Director* pDirector = Director::getInstance(); lua_State *L = _stack->getLuaState(); int ret = 0; lua_newtable(L); int i = 1; for (SetIterator it = touchesScriptData->touches->begin(); it != touchesScriptData->touches->end(); ++it) { Touch* pTouch = static_cast<Touch*>(*it); Point pt = pDirector->convertToGL(pTouch->getLocationInView()); lua_pushnumber(L, pt.x); lua_rawseti(L, -2, i++); lua_pushnumber(L, pt.y); lua_rawseti(L, -2, i++); lua_pushinteger(L, pTouch->getID()); lua_rawseti(L, -2, i++); } ret = _stack->executeFunctionByHandler(handler, 2); _stack->clean(); return ret; } int LuaEngine::handlerControlEvent(void* data) { if ( NULL == data ) return 0; BasicScriptData* basicScriptData = static_cast<BasicScriptData*>(data); if (NULL == basicScriptData->nativeObject) return 0; int controlEvents = *((int*)(basicScriptData->value)); int handler = 0; int ret = 0; for (int i = 0; i < kControlEventTotalNumber; i++) { if ((controlEvents & (1 << i))) { handler = ScriptHandlerMgr::getInstance()->getObjectHandler(basicScriptData->nativeObject, ScriptHandlerMgr::kControlTouchDownHandler + i); if (0 != handler) { _stack->pushObject((Object*)basicScriptData->nativeObject, "CCObject"); ret = _stack->executeFunctionByHandler(handler, 1); _stack->clean(); } } } return ret; } void LuaEngine::extendLuaObject() { if ( NULL == _stack || NULL == _stack->getLuaState()) return; lua_State* lua_S = _stack->getLuaState(); extendNode(lua_S); extendMenuItem(lua_S); extendLayer(lua_S); extendControl(lua_S); extendWebsocket(lua_S); extendGLNode(lua_S); extendScrollView(lua_S); extendDrawNode(lua_S); _stack->clean(); } void LuaEngine::extendNode(lua_State* lua_S) { if(NULL == lua_S) return; lua_pushstring(lua_S,"CCNode"); lua_rawget(lua_S,LUA_REGISTRYINDEX); if (lua_istable(lua_S,-1)) { lua_pushstring(lua_S,"registerScriptHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_registerScriptHandler00); lua_rawset(lua_S,-3); lua_pushstring(lua_S,"unregisterScriptHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_unregisterScriptHandler00); lua_rawset(lua_S, -3); } } void LuaEngine::extendMenuItem(lua_State* lua_S) { if (NULL == lua_S) return; lua_pushstring(lua_S,"CCMenuItem"); lua_rawget(lua_S,LUA_REGISTRYINDEX); if (lua_istable(lua_S,-1)) { lua_pushstring(lua_S,"registerScriptTapHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_registerScriptTapHandler00); lua_rawset(lua_S,-3); lua_pushstring(lua_S, "unregisterScriptTapHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_unregisterScriptTapHandler00); lua_rawset(lua_S, -3); } } void LuaEngine::extendLayer(lua_State* lua_S) { if (NULL == lua_S) return; lua_pushstring(lua_S,"CCLayer"); lua_rawget(lua_S,LUA_REGISTRYINDEX); if (lua_istable(lua_S,-1)) { lua_pushstring(lua_S,"registerScriptTouchHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_registerScriptTouchHandler00); lua_rawset(lua_S,-3); lua_pushstring(lua_S, "unregisterScriptTouchHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_unregisterScriptTouchHandler00); lua_rawset(lua_S, -3); lua_pushstring(lua_S, "registerScriptKeypadHandler"); lua_pushcfunction(lua_S, tolua_Cocos2d_registerScriptKeypadHandler00); lua_rawset(lua_S, -3); lua_pushstring(lua_S, "unregisterScriptKeypadHandler"); lua_pushcfunction(lua_S, tolua_Cocos2d_unregisterScriptKeypadHandler00); lua_rawset(lua_S, -3); lua_pushstring(lua_S, "registerScriptAccelerateHandler"); lua_pushcfunction(lua_S, tolua_Cocos2d_registerScriptAccelerateHandler00); lua_rawset(lua_S, -3); lua_pushstring(lua_S, "unregisterScriptAccelerateHandler"); lua_pushcfunction(lua_S, tolua_Cocos2d_unregisterScriptAccelerateHandler00); lua_rawset(lua_S, -3); } } void LuaEngine::extendControl(lua_State* lua_S) { if (NULL == lua_S) return; lua_pushstring(lua_S,"CCControl"); lua_rawget(lua_S,LUA_REGISTRYINDEX); if (lua_istable(lua_S,-1)) { lua_pushstring(lua_S,"registerControlEventHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_registerControlEventHandler00); lua_rawset(lua_S,-3); lua_pushstring(lua_S,"unregisterControlEventHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_unregisterControlEventHandler00); lua_rawset(lua_S,-3); } } void LuaEngine::extendWebsocket(lua_State* lua_S) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) if (NULL == lua_S) return; lua_pushstring(lua_S,"WebSocket"); lua_rawget(lua_S,LUA_REGISTRYINDEX); if (lua_istable(lua_S,-1)) { lua_pushstring(lua_S,"registerScriptHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_WebSocket_registerScriptHandler00); lua_rawset(lua_S,-3); lua_pushstring(lua_S,"unregisterScriptHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_WebSocket_unregisterScriptHandler00); lua_rawset(lua_S,-3); } #endif } void LuaEngine::extendGLNode(lua_State* lua_S) { if (NULL == lua_S) return; lua_pushstring(lua_S,"GLNode"); lua_rawget(lua_S,LUA_REGISTRYINDEX); if (lua_istable(lua_S,-1)) { lua_pushstring(lua_S,"registerScriptDrawHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_GLNode_registerScriptDrawHandler00); lua_rawset(lua_S,-3); lua_pushstring(lua_S,"unregisterScriptDrawHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_GLNode_unregisterScriptDrawHandler00); lua_rawset(lua_S,-3); } } void LuaEngine::extendScrollView(lua_State* lua_S) { if (NULL == lua_S) return; lua_pushstring(lua_S,"CCScrollView"); lua_rawget(lua_S,LUA_REGISTRYINDEX); if (lua_istable(lua_S,-1)) { lua_pushstring(lua_S,"registerScriptHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_ScrollView_registerScriptHandler00); lua_rawset(lua_S,-3); lua_pushstring(lua_S,"unregisterScriptHandler"); lua_pushcfunction(lua_S,tolua_Cocos2d_ScrollView_unregisterScriptHandler00); lua_rawset(lua_S,-3); } } void LuaEngine::extendDrawNode(lua_State* lua_S) { if (NULL == lua_S) return; lua_pushstring(lua_S,"CCDrawNode"); lua_rawget(lua_S,LUA_REGISTRYINDEX); if (lua_istable(lua_S,-1)) { lua_pushstring(lua_S,"drawPolygon"); lua_pushcfunction(lua_S,tolua_Cocos2d_CCDrawNode_drawPolygon00); lua_rawset(lua_S,-3); } } NS_CC_END
28.312339
151
0.638444
[ "object" ]
134fb1e17b280fd7cfdd5ac095689923d8df0c24
2,687
hh
C++
nlp/prototype/matrix.hh
leaveschen/nlp-lite
3896fbf7d024cf66f4c39a18e1101caaf574066b
[ "MIT" ]
null
null
null
nlp/prototype/matrix.hh
leaveschen/nlp-lite
3896fbf7d024cf66f4c39a18e1101caaf574066b
[ "MIT" ]
null
null
null
nlp/prototype/matrix.hh
leaveschen/nlp-lite
3896fbf7d024cf66f4c39a18e1101caaf574066b
[ "MIT" ]
null
null
null
// // Created by c on 29/11/2018 12:08 // #ifndef NLP_PROTOTYPE_MATRIX_HH #define NLP_PROTOTYPE_MATRIX_HH /* include section */ #include <memory> #include <cassert> /* class & function section */ namespace nlp { namespace prototype { /* basic class for matrix */ template<class Derived> class MatBase { protected: /* members */ size_t row_; size_t col_; public: /* ctor */ MatBase(size_t row, size_t col) : row_(row), col_(col) {} /* derived object */ Derived& derived() { return static_cast<Derived&>(*this); } Derived const& derived() const { return static_cast<Derived const&>(*this); } /* size */ inline size_t& row() { return row_; } inline size_t& col() { return col_; } }; /* dense matrix class */ template<class Scalar, int Option> class MatDense : public MatBase< MatDense<Scalar, Option> > { public: /* type alias */ using base_t = MatBase< MatDense<Scalar, Option> >; using coef_ptr_t = std::unique_ptr<Scalar[]>; protected: /* members */ coef_ptr_t coef_; // coefficient the storage major determined by the template parameter 'Option' public: /* ctor & dtor */ MatDense(size_t row, size_t col) : base_t(row, col), coef_(nullptr) { // TODO: check dimension valid assert(row > 0 and col > 0); coef_ = std::make_unique<Scalar[]>(this->row() * this->col()); } /* coefficient accessor */ Scalar& coef_nocheck(size_t i) { return coef_[i]; } Scalar const& coef_nocheck(size_t i) const { return coef_[i]; } Scalar& coef(size_t i) { assert(i < this->row() * this->col()); return coef_[i]; } Scalar const& coef(size_t i) const { assert(i < this->row() * this->col()); return coef_[i]; } Scalar& coef_nocheck(size_t i, size_t j) { return coef_[i*this->row()+j]; } Scalar const& coef_nocheck(size_t i, size_t j) const { return coef_[i*this->row()+j]; } Scalar& coef(size_t i, size_t j) { assert(i < this->row() and j < this->col()); return coef_[i*this->row()+j]; } Scalar const& coef(size_t i, size_t j) const { assert(i < this->row() and j < this->col()); return coef_[i*this->row()+j]; } /* addition */ template<class OtherDerived> void add(OtherDerived const& other); /* multiply */ template<class OtherDerived> void mul(OtherDerived const& other); }; /* sparse matrix class */ // TODO: implement template<class Scalar, int Option> class MatSparse : public MatBase< MatSparse<Scalar, Option> > { public: /* type alias */ using base_t = MatBase< MatSparse<Scalar, Option> >; struct coef_unit_t { size_t inner_index; Scalar value; }; struct coef_array_t { size_t outer_index; std::vector<coef_unit_t> array; }; /* members */ }; } // namespace prototype } // namespace nlp #endif//
21.845528
97
0.668403
[ "object", "vector" ]
135029c3a3194ed43c8f85735d59549942a04fbb
1,365
cpp
C++
src/resreq.cpp
fsaadatmand/ResReq
b1a6793dff1e186bd8d7a29578eefaaf2e061c08
[ "BSD-2-Clause" ]
null
null
null
src/resreq.cpp
fsaadatmand/ResReq
b1a6793dff1e186bd8d7a29578eefaaf2e061c08
[ "BSD-2-Clause" ]
null
null
null
src/resreq.cpp
fsaadatmand/ResReq
b1a6793dff1e186bd8d7a29578eefaaf2e061c08
[ "BSD-2-Clause" ]
null
null
null
#include "resreq.h" #include "Absence.h" #include <boost/date_time/gregorian/greg_duration.hpp> #include <boost/date_time/gregorian/gregorian.hpp> #include <boost/date_time/gregorian/parsers.hpp> #include <iostream> #include <map> #include <sstream> #include <stdexcept> #include <string> #include <vector> int main(int argc, char **argv) { using boost::gregorian::date_period; using boost::gregorian::days; using boost::gregorian::from_string; using boost::gregorian::date; auto [filename, end_date, period_years, inclusive] = parseArguments(argc, argv); std::vector<std::string> dates_input; try { dates_input = loadFile(filename); } catch (std::runtime_error &e) { std::cout << e.what() << '\n'; return EXIT_FAILURE; } const auto main_period = setPeriod(end_date, period_years); auto absences = std::map<date_period, days>(); for (const auto &line : dates_input) { try { std::stringstream sstream(line); std::string s1, s2; sstream >> s1 >> s2; auto dates = date_period(from_string(s1), from_string(s2)); auto duration = dates_difference(main_period, dates, inclusive); if (duration.days() != 0) { absences[dates] = duration; } } catch (std::exception &e) { die({ "Error: bad date format entry:", "\nDetail:", e.what() }); } } print_dates(std::cout, main_period, absences); std::exit(EXIT_SUCCESS); }
27.857143
67
0.695971
[ "vector" ]
1351bd92cf583c8514b59273eb1ce6734a1cf844
4,302
cpp
C++
src/tests/functional/plugin/cpu/single_layer_tests/log_softmax.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
1
2019-09-22T01:05:07.000Z
2019-09-22T01:05:07.000Z
src/tests/functional/plugin/cpu/single_layer_tests/log_softmax.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
58
2020-11-06T12:13:45.000Z
2022-03-28T13:20:11.000Z
src/tests/functional/plugin/cpu/single_layer_tests/log_softmax.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
4
2021-09-29T20:44:49.000Z
2021-10-20T13:02:12.000Z
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "test_utils/cpu_test_utils.hpp" #include "ngraph_functions/builders.hpp" #include "shared_test_classes/base/ov_subgraph.hpp" using namespace ngraph; using namespace InferenceEngine; using namespace CPUTestUtils; using namespace ov::test; namespace CPULayerTestsDefinitions { using logSoftmaxLayerTestParams = std::tuple< std::vector<InputShape>, // inputShape Precision, // netPrecision int64_t>; // axis class LogSoftmaxLayerCPUTest : public testing::WithParamInterface<logSoftmaxLayerTestParams>, public SubgraphBaseTest, public CPUTestsBase { public: static std::string getTestCaseName(testing::TestParamInfo<logSoftmaxLayerTestParams> obj) { std::vector<InputShape> inputShapes; Precision netPrecision; int64_t axis; std::tie(inputShapes, netPrecision, axis) = obj.param; std::ostringstream result; if (inputShapes.front().first.size() != 0) { result << "IS=("; for (const auto &shape : inputShapes) { result << CommonTestUtils::partialShape2str({shape.first}) << "_"; } result.seekp(-1, result.cur); result << ")_"; } result << "TS="; for (const auto &shape : inputShapes) { for (const auto &item : shape.second) { result << CommonTestUtils::vec2str(item) << "_"; } } result << "netPRC=" << netPrecision.name(); result << "Axis=" << axis; return result.str(); } protected: void SetUp() override { targetDevice = CommonTestUtils::DEVICE_CPU; std::vector<InputShape> inputShapes; Precision netPrecision; int64_t axis; std::tie(inputShapes, netPrecision, axis) = this->GetParam(); auto ngPrc = FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(netPrecision); inType = outType = ngPrc; selectedType = std::string("unknown_") + netPrecision.name(); init_input_shapes(inputShapes); const auto params = ngraph::builder::makeDynamicParams(ngPrc, {inputDynamicShapes.front()}); const auto paramOuts = ngraph::helpers::convert2OutputVector(ngraph::helpers::castOps2Nodes<ngraph::op::Parameter>(params)); const auto logSoftmax = std::make_shared<ngraph::op::v5::LogSoftmax>(paramOuts[0], axis); const ngraph::ResultVector results{std::make_shared<ngraph::opset1::Result>(logSoftmax)}; function = std::make_shared<ngraph::Function>(results, params, "logSoftmax"); } }; TEST_P(LogSoftmaxLayerCPUTest, CompareWithRefs) { SKIP_IF_CURRENT_TEST_IS_DISABLED() run(); CheckPluginRelatedResults(executableNetwork, "logSoftmax"); } namespace { const std::vector<InferenceEngine::Precision> netPrecisions = { Precision::FP32 }; const std::vector<std::vector<InputShape>> inputShapes2D = { { {{{-1, -1}, {{1, 100}, {100, 1}, {10, 10}}}}, {{{-1, {1}}, {{1, 1}, {100, 1}, {10, 1}}}} } }; const std::vector<int64_t> axis2D = { -2, -1, 0, 1 }; const auto params2D = testing::Combine( testing::ValuesIn(inputShapes2D), testing::ValuesIn(netPrecisions), testing::ValuesIn(axis2D)); INSTANTIATE_TEST_SUITE_P(smoke_LogSoftmax2D_dynamic, LogSoftmaxLayerCPUTest, params2D, LogSoftmaxLayerCPUTest::getTestCaseName); const std::vector<std::vector<InputShape>> inputShapes4D = { { {{{-1, -1, -1, -1}, {{1, 100, 1, 1}, {1, 3, 4, 3}, {2, 3, 4, 5}}}}, {{{{1, 2}, -1, {1, 5}, -1}, {{1, 100, 1, 1}, {1, 3, 5, 3}, {2, 3, 4, 5}}}} } }; const std::vector<int64_t> axis4D = { -4, -3, -2, -1, 0, 1, 2, 3 }; const auto params4D = testing::Combine( testing::ValuesIn(inputShapes4D), testing::ValuesIn(netPrecisions), testing::ValuesIn(axis4D)); INSTANTIATE_TEST_SUITE_P(smoke_LogSoftmax4D_dynamic, LogSoftmaxLayerCPUTest, params4D, LogSoftmaxLayerCPUTest::getTestCaseName); } // namespace } // namespace CPULayerTestsDefinitions
33.874016
132
0.613203
[ "shape", "vector" ]
1356cc69aad7b5d2a9fafc814bf644754087f9f8
2,279
cpp
C++
socket_practice_Basic/chatroom/sockets_server_with_multiple_clients(chatroom)/serverMain.cpp
13thFinance/C-Plus-Plus-Practice
955deb9035fbf0fe20eee2be3ceafe5d516d0702
[ "MIT" ]
null
null
null
socket_practice_Basic/chatroom/sockets_server_with_multiple_clients(chatroom)/serverMain.cpp
13thFinance/C-Plus-Plus-Practice
955deb9035fbf0fe20eee2be3ceafe5d516d0702
[ "MIT" ]
null
null
null
socket_practice_Basic/chatroom/sockets_server_with_multiple_clients(chatroom)/serverMain.cpp
13thFinance/C-Plus-Plus-Practice
955deb9035fbf0fe20eee2be3ceafe5d516d0702
[ "MIT" ]
null
null
null
//server #define _WINSOCK_DEPRECATED_NO_WARNINGS #pragma comment(lib, "ws2_32.lib") #include <WinSock2.h> #include <iostream> #include <vector> using namespace std; vector<SOCKET> connections; void clientHandlerThread(int client) { char buffer[256]; while (true) { recv(connections[client], buffer, sizeof(buffer), NULL); for (int i = 0 ; i < connections.size(); i++) { if (i != client) //skip sending message to user who sent it { send(connections[i], buffer, sizeof(buffer), NULL); } } } } int main() { //start up winsock WSAData wsaData; WORD DLLVersion = MAKEWORD(2, 1); if (WSAStartup(DLLVersion, &wsaData) != 0) //if anything else than zero, startup fails { MessageBoxA(NULL, "Winsock startup failed!\n", "Error", MB_OK | MB_ICONERROR); exit(1); } SOCKADDR_IN addr; //address that we will bind our listening socket to int addrlen = sizeof(addr);//length of addrs (required to accept call) addr.sin_addr.s_addr = inet_addr("127.0.0.1");//broadcast locally addr.sin_port = htons(1111);//port addr.sin_family = AF_INET; //IPv4 Socket cout << "Listening...\n"; SOCKET sListen = socket(AF_INET, SOCK_STREAM, NULL);//create socket to listen bind(sListen, (SOCKADDR*)&addr, sizeof(addr));//bind address to socket listen(sListen, SOMAXCONN);//socket is now listening for connections, somaxconn limits to max connections //handles new connections while (true) { SOCKET newConnection;//socket to hold the client's connection newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen); if (newConnection == 0) { cout << "\nFailed to accept the clients connection.\n"; } else //if client connected properly { //send message connections.push_back(newConnection);//store connection cout << "\nClient connected!\nNumber of clients is: " << connections.size(); char MOTD[256] = "Welcome! *Insert Message of the Day here*."; send(newConnection, MOTD, sizeof(MOTD), NULL);//sizeof returns the number of bytes, char = 1, int = 4 etc, make sure to use accordingly CreateThread(NULL,NULL, (LPTHREAD_START_ROUTINE)clientHandlerThread, (LPVOID)(connections.size() - 1), NULL, NULL); } } system("pause"); return 0; }
29.217949
140
0.677051
[ "vector" ]
135726eb993d85193dadbba7b7b93b20c67a9eff
44,228
cpp
C++
test/test_log.cpp
fengzhongye/braft
51863ee36d2165e03c224fcdb29db9dbe8cc41ab
[ "Apache-2.0" ]
1,844
2017-09-20T06:35:49.000Z
2019-12-09T12:30:42.000Z
test/test_log.cpp
fengzhongye/braft
51863ee36d2165e03c224fcdb29db9dbe8cc41ab
[ "Apache-2.0" ]
146
2019-12-11T06:48:10.000Z
2022-03-14T04:08:42.000Z
test/test_log.cpp
fengzhongye/braft
51863ee36d2165e03c224fcdb29db9dbe8cc41ab
[ "Apache-2.0" ]
440
2017-09-20T16:49:40.000Z
2019-12-09T08:42:03.000Z
// libraft - Quorum-based replication of states across machines. // Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved // Author: WangYao (fisherman), wangyao02@baidu.com // Date: 2015/10/08 17:00:05 #include <gtest/gtest.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <butil/atomicops.h> #include <butil/file_util.h> #include <butil/files/file_path.h> #include <butil/files/file_enumerator.h> #include <butil/files/dir_reader_posix.h> #include <butil/string_printf.h> #include <butil/logging.h> #include "braft/util.h" #include "braft/log.h" #include "braft/storage.h" namespace braft { DECLARE_bool(raft_trace_append_entry_latency); } class LogStorageTest : public testing::Test { protected: void SetUp() { braft::FLAGS_raft_sync = false; GFLAGS_NS::SetCommandLineOption("minloglevel", "3"); } void TearDown() {} }; TEST_F(LogStorageTest, open_segment) { // open segment operation ::system("mkdir data/"); braft::Segment* seg1 = new braft::Segment("./data", 1L, 0); // not open braft::LogEntry* entry = seg1->get(1); ASSERT_TRUE(entry == NULL); // create and open ASSERT_EQ(0, seg1->create()); ASSERT_TRUE(seg1->is_open()); // append entry for (int i = 0; i < 10; i++) { braft::LogEntry* entry = new braft::LogEntry(); entry->AddRef(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = i + 1; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %d", i + 1); entry->data.append(data_buf); ASSERT_EQ(0, seg1->append(entry)); entry->Release(); } // read entry for (int i = 0; i < 10; i++) { int64_t term = seg1->get_term(i+1); ASSERT_EQ(term, 1); braft::LogEntry* entry = seg1->get(i+1); ASSERT_EQ(entry->id.term, 1); ASSERT_EQ(entry->type, braft::ENTRY_TYPE_DATA); ASSERT_EQ(entry->id.index, i+1); char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %d", i + 1); ASSERT_EQ(data_buf, entry->data.to_string()); entry->Release(); } { braft::LogEntry* entry = seg1->get(0); ASSERT_TRUE(entry == NULL); entry = seg1->get(11); ASSERT_TRUE(entry == NULL); } braft::ConfigurationManager* configuration_manager = new braft::ConfigurationManager; // load open segment braft::Segment* seg2 = new braft::Segment("./data", 1, 0); ASSERT_EQ(0, seg2->load(configuration_manager)); for (int i = 0; i < 10; i++) { braft::LogEntry* entry = seg2->get(i+1); ASSERT_EQ(entry->id.term, 1); ASSERT_EQ(entry->type, braft::ENTRY_TYPE_DATA); ASSERT_EQ(entry->id.index, i+1); char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %d", i + 1); ASSERT_EQ(data_buf, entry->data.to_string()); entry->Release(); } { braft::LogEntry* entry = seg2->get(0); ASSERT_TRUE(entry == NULL); entry = seg2->get(11); ASSERT_TRUE(entry == NULL); } delete seg2; // truncate and read ASSERT_EQ(0, seg1->truncate(5)); for (int i = 0; i < 5; i++) { braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = i + 6; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "HELLO, WORLD: %d", i + 6); entry->data.append(data_buf); ASSERT_EQ(0, seg1->append(entry)); entry->Release(); } for (int i = 0; i < 10; i++) { braft::LogEntry* entry = seg1->get(i+1); ASSERT_EQ(entry->id.term, 1); ASSERT_EQ(entry->type, braft::ENTRY_TYPE_DATA); ASSERT_EQ(entry->id.index, i+1); char data_buf[128]; if (i < 5) { snprintf(data_buf, sizeof(data_buf), "hello, world: %d", i + 1); } else { snprintf(data_buf, sizeof(data_buf), "HELLO, WORLD: %d", i + 1); } ASSERT_EQ(data_buf, entry->data.to_string()); entry->Release(); } ASSERT_EQ(0, seg1->close()); ASSERT_FALSE(seg1->is_open()); ASSERT_EQ(0, seg1->unlink()); delete configuration_manager; } TEST_F(LogStorageTest, closed_segment) { // open segment operation braft::Segment* seg1 = new braft::Segment("./data", 1L, 0); ASSERT_EQ(0, seg1->create()); ASSERT_TRUE(seg1->is_open()); // append entry for (int i = 0; i < 10; i++) { braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = i + 1; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %d", i + 1); entry->data.append(data_buf); ASSERT_EQ(0, seg1->append(entry)); entry->Release(); } seg1->close(); // read entry for (int i = 0; i < 10; i++) { braft::LogEntry* entry = seg1->get(i+1); ASSERT_EQ(entry->id.term, 1); ASSERT_EQ(entry->type, braft::ENTRY_TYPE_DATA); ASSERT_EQ(entry->id.index, i+1); char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %d", i + 1); ASSERT_EQ(data_buf, entry->data.to_string()); entry->Release(); } { braft::LogEntry* entry = seg1->get(0); ASSERT_TRUE(entry == NULL); entry = seg1->get(11); ASSERT_TRUE(entry == NULL); } braft::ConfigurationManager* configuration_manager = new braft::ConfigurationManager; // load open segment braft::Segment* seg2 = new braft::Segment("./data", 1, 10, 0); ASSERT_EQ(0, seg2->load(configuration_manager)); for (int i = 0; i < 10; i++) { braft::LogEntry* entry = seg2->get(i+1); ASSERT_EQ(entry->id.term, 1); ASSERT_EQ(entry->type, braft::ENTRY_TYPE_DATA); ASSERT_EQ(entry->id.index, i+1); char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %d", i + 1); ASSERT_EQ(data_buf, entry->data.to_string()); entry->Release(); } { braft::LogEntry* entry = seg2->get(0); ASSERT_TRUE(entry == NULL); entry = seg2->get(11); ASSERT_TRUE(entry == NULL); } delete seg2; // truncate and read ASSERT_EQ(0, seg1->truncate(5)); for (int i = 0; i < 5; i++) { braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = i + 6; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "HELLO, WORLD: %d", i + 6); entry->data.append(data_buf); // become open segment again ASSERT_EQ(0, seg1->append(entry)); entry->Release(); } for (int i = 0; i < 10; i++) { braft::LogEntry* entry = seg1->get(i+1); char data_buf[128]; if (i < 5) { snprintf(data_buf, sizeof(data_buf), "hello, world: %d", i + 1); } else { snprintf(data_buf, sizeof(data_buf), "HELLO, WORLD: %d", i + 1); } ASSERT_EQ(entry->id.term, 1); ASSERT_EQ(entry->type, braft::ENTRY_TYPE_DATA); ASSERT_EQ(entry->id.index, i+1); ASSERT_EQ(data_buf, entry->data.to_string()); entry->Release(); } ASSERT_EQ(0, seg1->unlink()); delete configuration_manager; } TEST_F(LogStorageTest, multi_segment_and_segment_logstorage) { ::system("rm -rf data"); braft::SegmentLogStorage* storage = new braft::SegmentLogStorage("./data"); // init ASSERT_EQ(0, storage->init(new braft::ConfigurationManager())); ASSERT_EQ(1, storage->first_log_index()); ASSERT_EQ(0, storage->last_log_index()); // append entry for (int i = 0; i < 100000; i++) { std::vector<braft::LogEntry*> entries; for (int j = 0; j < 5; j++) { int64_t index = 5*i + j + 1; braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = index; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %" PRId64, index); entry->data.append(data_buf); entries.push_back(entry); } ASSERT_EQ(5, storage->append_entries(entries, NULL)); for (size_t j = 0; j < entries.size(); j++) { entries[j]->Release(); } } // read entry for (int i = 0; i < 500000; i++) { int64_t index = i + 1; braft::LogEntry* entry = storage->get_entry(index); ASSERT_EQ(entry->id.term, 1); ASSERT_EQ(entry->type, braft::ENTRY_TYPE_DATA); ASSERT_EQ(entry->id.index, index); char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %" PRId64, index); ASSERT_EQ(data_buf, entry->data.to_string()); entry->Release(); } ASSERT_EQ(storage->first_log_index(), 1); ASSERT_EQ(storage->last_log_index(), 500000); // truncate prefix ASSERT_EQ(0, storage->truncate_prefix(10001)); ASSERT_EQ(storage->first_log_index(), 10001); ASSERT_EQ(storage->last_log_index(), 500000); // boundary truncate prefix { braft::SegmentLogStorage::SegmentMap segments1 = storage->segments(); size_t old_segment_num = segments1.size(); braft::Segment* first_seg = segments1.begin()->second.get(); ASSERT_EQ(0, storage->truncate_prefix(first_seg->last_index())); braft::SegmentLogStorage::SegmentMap segments2 = storage->segments(); ASSERT_EQ(old_segment_num, segments2.size()); ASSERT_EQ(0, storage->truncate_prefix(first_seg->last_index() + 1)); braft::SegmentLogStorage::SegmentMap segments3 = storage->segments(); ASSERT_EQ(old_segment_num - 1, segments3.size()); } ASSERT_EQ(0, storage->truncate_prefix(250001)); ASSERT_EQ(storage->first_log_index(), 250001); ASSERT_EQ(storage->last_log_index(), 500000); for (int i = 250001; i <= 500000; i++) { int64_t index = i; braft::LogEntry* entry = storage->get_entry(index); ASSERT_EQ(entry->id.term, 1); ASSERT_EQ(entry->type, braft::ENTRY_TYPE_DATA); ASSERT_EQ(entry->id.index, index); char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %" PRId64, index); ASSERT_EQ(data_buf, entry->data.to_string()); entry->Release(); } // append for (int i = 100000; i < 200000; i++) { std::vector<braft::LogEntry*> entries; for (int j = 0; j < 5; j++) { int64_t index = 5*i + j + 1; braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = index; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %" PRId64, index); entry->data.append(data_buf); entries.push_back(entry); } ASSERT_EQ(5, storage->append_entries(entries, NULL)); for (size_t j = 0; j < entries.size(); j++) { entries[j]->Release(); } } // truncate suffix ASSERT_EQ(250001, storage->first_log_index()); ASSERT_EQ(1000000, storage->last_log_index()); ASSERT_EQ(0, storage->truncate_suffix(750000)); ASSERT_EQ(250001, storage->first_log_index()); ASSERT_EQ(750000, storage->last_log_index()); // boundary truncate suffix { braft::SegmentLogStorage::SegmentMap segments1 = storage->segments(); braft::Segment* first_seg = segments1.begin()->second.get(); if (segments1.size() > 1) { storage->truncate_suffix(first_seg->last_index() + 1); } braft::SegmentLogStorage::SegmentMap segments2 = storage->segments(); ASSERT_EQ(1ul, segments2.size()); ASSERT_EQ(storage->last_log_index(), first_seg->last_index() + 1); storage->truncate_suffix(first_seg->last_index()); braft::SegmentLogStorage::SegmentMap segments3 = storage->segments(); ASSERT_EQ(1ul, segments3.size()); ASSERT_EQ(storage->last_log_index(), first_seg->last_index()); } // read for (int i = 250001; i <= storage->last_log_index(); i++) { int64_t index = i; braft::LogEntry* entry = storage->get_entry(index); ASSERT_EQ(entry->id.term, 1); ASSERT_EQ(entry->type, braft::ENTRY_TYPE_DATA); ASSERT_EQ(entry->id.index, index); char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %" PRId64, index); ASSERT_EQ(data_buf, entry->data.to_string()); entry->Release(); } delete storage; // re load ::system("rm -rf data/log_meta"); braft::SegmentLogStorage* storage2 = new braft::SegmentLogStorage("./data"); ASSERT_EQ(0, storage2->init(new braft::ConfigurationManager())); ASSERT_EQ(1, storage2->first_log_index()); ASSERT_EQ(0, storage2->last_log_index()); delete storage2; } TEST_F(LogStorageTest, append_close_load_append) { ::system("rm -rf data"); braft::LogStorage* storage = new braft::SegmentLogStorage("./data"); braft::ConfigurationManager* configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); // append entry for (int i = 0; i < 100000; i++) { std::vector<braft::LogEntry*> entries; for (int j = 0; j < 5; j++) { int64_t index = 5*i + j + 1; braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = index; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %" PRId64, index); entry->data.append(data_buf); entries.push_back(entry); } ASSERT_EQ(5, storage->append_entries(entries, NULL)); for (size_t j = 0; j < entries.size(); j++) { delete entries[j]; } } delete storage; delete configuration_manager; // reinit storage = new braft::SegmentLogStorage("./data"); configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); // append entry for (int i = 100000; i < 200000; i++) { std::vector<braft::LogEntry*> entries; for (int j = 0; j < 5; j++) { int64_t index = 5*i + j + 1; braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 2; entry->id.index = index; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %" PRId64, index); entry->data.append(data_buf); entries.push_back(entry); } ASSERT_EQ(5, storage->append_entries(entries, NULL)); for (size_t j = 0; j < entries.size(); j++) { delete entries[j]; } } // check and read ASSERT_EQ(storage->first_log_index(), 1); ASSERT_EQ(storage->last_log_index(), 200000*5); for (int i = 0; i < 200000*5; i++) { int64_t index = i + 1; braft::LogEntry* entry = storage->get_entry(index); if (i < 100000*5) { ASSERT_EQ(entry->id.term, 1); } else { ASSERT_EQ(entry->id.term, 2); } ASSERT_EQ(entry->type, braft::ENTRY_TYPE_DATA); ASSERT_EQ(entry->id.index, index); char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %" PRId64, index); ASSERT_EQ(data_buf, entry->data.to_string()); entry->Release(); } delete storage; delete configuration_manager; } ssize_t file_size(const char* filename) { struct stat st; stat(filename, &st); return st.st_size; } int truncate_uninterrupted(const char* filename, off_t length) { int rc = 0; do { rc = truncate(filename, length); } while (rc == -1 && errno == EINTR); return rc; } TEST_F(LogStorageTest, data_lost) { ::system("rm -rf data"); braft::LogStorage* storage = new braft::SegmentLogStorage("./data"); braft::ConfigurationManager* configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); // append entry for (int i = 0; i < 100000; i++) { std::vector<braft::LogEntry*> entries; for (int j = 0; j < 5; j++) { int64_t index = 5*i + j + 1; braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = index; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %ld", index); entry->data.append(data_buf); entries.push_back(entry); } ASSERT_EQ(5, storage->append_entries(entries, NULL)); for (size_t j = 0; j < entries.size(); j++) { delete entries[j]; } } delete storage; delete configuration_manager; // reinit storage = new braft::SegmentLogStorage("./data"); configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); ASSERT_EQ(storage->first_log_index(), 1); ASSERT_EQ(storage->last_log_index(), 100000*5); delete storage; delete configuration_manager; // last segment lost data butil::DirReaderPosix dir_reader1("./data"); ASSERT_TRUE(dir_reader1.IsValid()); while (dir_reader1.Next()) { int64_t first_index = 0; int match = sscanf(dir_reader1.name(), "log_inprogress_%020ld", &first_index); std::string path; butil::string_appendf(&path, "./data/%s", dir_reader1.name()); if (match == 1) { ASSERT_EQ(truncate_uninterrupted(path.c_str(), file_size(path.c_str()) - 1), 0); } } storage = new braft::SegmentLogStorage("./data"); configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); ASSERT_EQ(storage->first_log_index(), 1); ASSERT_EQ(storage->last_log_index(), 100000*5 - 1); delete storage; delete configuration_manager; // middle segment lost data butil::DirReaderPosix dir_reader2("./data"); ASSERT_TRUE(dir_reader2.IsValid()); while (dir_reader2.Next()) { int64_t first_index = 0; int64_t last_index = 0; int match = sscanf(dir_reader2.name(), "log_%020ld_%020ld", &first_index, &last_index); std::string path; butil::string_appendf(&path, "./data/%s", dir_reader2.name()); if (match == 2) { ASSERT_EQ(truncate_uninterrupted(path.c_str(), file_size(path.c_str()) - 1), 0); } } storage = new braft::SegmentLogStorage("./data"); configuration_manager = new braft::ConfigurationManager; ASSERT_NE(0, storage->init(configuration_manager)); delete storage; delete configuration_manager; } TEST_F(LogStorageTest, full_segment_has_garbage) { ::system("rm -rf data"); braft::LogStorage* storage = new braft::SegmentLogStorage("./data"); braft::ConfigurationManager* configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); // append entry for (int i = 0; i < 100000; i++) { std::vector<braft::LogEntry*> entries; for (int j = 0; j < 5; j++) { int64_t index = 5*i + j + 1; braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = index; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %ld", index); entry->data.append(data_buf); entries.push_back(entry); } ASSERT_EQ(5, storage->append_entries(entries, NULL)); for (size_t j = 0; j < entries.size(); j++) { delete entries[j]; } } delete storage; delete configuration_manager; // generate garbage entries butil::DirReaderPosix dir_reader("./data"); std::string first_segment; std::string second_segment; while (dir_reader.IsValid()) { dir_reader.Next(); int64_t first_index = 0; int64_t last_index = 0; int match = sscanf(dir_reader.name(), "log_%020ld_%020ld", &first_index, &last_index); if (match != 2) { continue; } if (first_segment.empty()) { butil::string_appendf(&first_segment, "./data/%s", dir_reader.name()); } else { butil::string_appendf(&second_segment, "./data/%s", dir_reader.name()); break; } } int fd1 = open(first_segment.c_str(), O_RDWR); int fd2 = open(second_segment.c_str(), O_RDWR); int off1 = 0; int off2 = 0; ASSERT_TRUE(fd1 >= 0); ASSERT_TRUE(fd2 >= 0); struct stat st_buf; ASSERT_EQ(fstat(fd1, &st_buf), 0); off1 = st_buf.st_size; for (;;) { butil::IOPortal buf; ssize_t ret = braft::file_pread(&buf, fd2, off2, 8192); ASSERT_TRUE(ret >= 0); if (ret == 0) { break; } ASSERT_EQ(buf.size(), braft::file_pwrite(buf, fd1, off1)); off1 += buf.size(); off2 += buf.size(); } close(fd1); close(fd2); storage = new braft::SegmentLogStorage("./data"); configuration_manager = new braft::ConfigurationManager; ASSERT_NE(0, storage->init(configuration_manager)); } TEST_F(LogStorageTest, append_read_badcase) { ::system("rm -rf data"); braft::LogStorage* storage = new braft::SegmentLogStorage("./data"); braft::ConfigurationManager* configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); // append entry for (int i = 0; i < 100000; i++) { std::vector<braft::LogEntry*> entries; for (int j = 0; j < 5; j++) { int64_t index = 5*i + j + 1; braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = index; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %" PRId64, index); entry->data.append(data_buf); entries.push_back(entry); } ASSERT_EQ(5, storage->append_entries(entries, NULL)); for (size_t j = 0; j < entries.size(); j++) { delete entries[j]; } } // check and read ASSERT_EQ(storage->first_log_index(), 1); ASSERT_EQ(storage->last_log_index(), 100000*5); delete storage; delete configuration_manager; // make file unwrite butil::FileEnumerator dir1(butil::FilePath("./data"), false, butil::FileEnumerator::FILES | butil::FileEnumerator::DIRECTORIES); for (butil::FilePath sub_path = dir1.Next(); !sub_path.empty(); sub_path = dir1.Next()) { butil::File::Info info; butil::GetFileInfo(sub_path, &info); if (!info.is_directory) { chmod(sub_path.value().c_str(), 0444); } } // reinit failed, because load open no permission storage = new braft::SegmentLogStorage("./data"); configuration_manager = new braft::ConfigurationManager; ASSERT_NE(0, storage->init(configuration_manager)); delete storage; delete configuration_manager; butil::FileEnumerator dir2(butil::FilePath("./data"), false, butil::FileEnumerator::FILES | butil::FileEnumerator::DIRECTORIES); for (butil::FilePath sub_path = dir2.Next(); !sub_path.empty(); sub_path = dir2.Next()) { butil::File::Info info; butil::GetFileInfo(sub_path, &info); if (!info.is_directory) { chmod(sub_path.value().c_str(), 0644); } } // reinit success storage = new braft::SegmentLogStorage("./data"); configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); // make file chaos butil::FileEnumerator dir3(butil::FilePath("./data"), false, butil::FileEnumerator::FILES | butil::FileEnumerator::DIRECTORIES); for (butil::FilePath sub_path = dir3.Next(); !sub_path.empty(); sub_path = dir3.Next()) { butil::File::Info info; butil::GetFileInfo(sub_path, &info); if (!info.is_directory) { chmod(sub_path.value().c_str(), 0644); int fd = ::open(sub_path.value().c_str(), O_RDWR, 0644); int64_t off = rand() % info.size; int64_t len = rand() % (info.size - off); if (len > 4096) { len = 4096; } char data[4096] = {0}; ::pwrite(fd, data, len, off); ::close(fd); } } // read will fail for (int i = 0; i < 100000*5; i++) { int64_t index = i + 1; braft::LogEntry* entry = storage->get_entry(index); if (entry) { entry->Release(); } } delete storage; delete configuration_manager; } TEST_F(LogStorageTest, configuration) { ::system("rm -rf data"); braft::SegmentLogStorage* storage = new braft::SegmentLogStorage("./data"); braft::ConfigurationManager* configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); { braft::LogEntry entry; entry.type = braft::ENTRY_TYPE_NO_OP; entry.id.term = 1; entry.id.index = 1; ASSERT_EQ(0, storage->append_entry(&entry)); } // add peer { braft::LogEntry entry; entry.type = braft::ENTRY_TYPE_CONFIGURATION; entry.id.term = 1; entry.id.index = 2; entry.peers = new std::vector<braft::PeerId>; entry.peers->push_back(braft::PeerId("1.1.1.1:1000:0")); entry.peers->push_back(braft::PeerId("1.1.1.1:2000:0")); entry.peers->push_back(braft::PeerId("1.1.1.1:3000:0")); storage->append_entry(&entry); } // append entry for (int i = 0; i < 100000; i++) { std::vector<braft::LogEntry*> entries; for (int j = 0; j < 5; j++) { int64_t index = 3 + i*5+j; braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = index; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %" PRId64, index); entry->data.append(data_buf); entries.push_back(entry); } ASSERT_EQ(5, storage->append_entries(entries, NULL)); for (size_t j = 0; j < entries.size(); j++) { delete entries[j]; } } // remove peer { int64_t index = 2 + 100000*5 + 1; braft::LogEntry entry; entry.type = braft::ENTRY_TYPE_CONFIGURATION; entry.id.term = 1; entry.id.index = index; entry.peers = new std::vector<braft::PeerId>; entry.peers->push_back(braft::PeerId("1.1.1.1:1000:0")); entry.peers->push_back(braft::PeerId("1.1.1.1:2000:0")); storage->append_entry(&entry); } delete storage; braft::SegmentLogStorage* storage2 = new braft::SegmentLogStorage("./data"); ASSERT_EQ(0, storage2->init(configuration_manager)); braft::ConfigurationEntry pair; configuration_manager->get(2 + 100000*5, &pair); ASSERT_EQ(2, pair.id.index); LOG(INFO) << pair.conf; configuration_manager->get(2 + 100000*5 + 1, &pair); ASSERT_EQ(2+100000*5+1, pair.id.index); LOG(INFO) << pair.conf; storage2->truncate_suffix(400000); configuration_manager->get(400000, &pair); ASSERT_EQ(2, pair.id.index); storage2->truncate_prefix(2); configuration_manager->get(400000, &pair); ASSERT_EQ(2, pair.id.index); delete storage2; } butil::atomic<int> g_first_read_index(0); butil::atomic<int> g_last_read_index(0); bool g_stop = false; void* read_thread_routine(void* arg) { braft::SegmentLogStorage* storage = (braft::SegmentLogStorage*)arg; while (!g_stop) { int a = g_first_read_index.load(butil::memory_order_relaxed); int b = g_last_read_index.load(butil::memory_order_relaxed); EXPECT_LE(a, b); int index = butil::fast_rand_in(a, b); braft::LogEntry* entry = storage->get_entry(index); if (entry != NULL) { std::string expect; butil::string_printf(&expect, "hello_%d", index); EXPECT_EQ(expect, entry->data.to_string()); entry->Release(); } else { EXPECT_LT(index, storage->first_log_index()) << "first_read_index=" << g_first_read_index.load() << " last_read_index=" << g_last_read_index.load() << " a=" << a << " b=" << b; g_stop = true; return NULL; } } return NULL; } void* write_thread_routine(void* arg) { braft::SegmentLogStorage* storage = (braft::SegmentLogStorage*)arg; // Write operation distribution: // - 10% truncate_prefix // - 10% truncate_suffix, // - 30% increase last_read_index (which stands for commitment in the real // world), // - 50% append new entry int next_log_index = storage->last_log_index() + 1; while (!g_stop) { const int r = butil::fast_rand_in(0, 9); if (r < 1) { // truncate_prefix int truncate_index = butil::fast_rand_in( g_first_read_index.load(butil::memory_order_relaxed), g_last_read_index.load(butil::memory_order_relaxed)); EXPECT_EQ(0, storage->truncate_prefix(truncate_index)); g_first_read_index.store(truncate_index, butil::memory_order_relaxed); } else if (r < 2) { // truncate suffix int truncate_index = butil::fast_rand_in( g_last_read_index.load(butil::memory_order_relaxed), next_log_index - 1); EXPECT_EQ(0, storage->truncate_suffix(truncate_index)); next_log_index = truncate_index + 1; } else if (r < 5) { // increase last_read_index which cannot be truncate int next_read_index = butil::fast_rand_in( g_last_read_index.load(butil::memory_order_relaxed), next_log_index - 1); g_last_read_index.store(next_read_index, butil::memory_order_relaxed); } else { // Append entry braft::LogEntry* entry = new braft::LogEntry; entry->type = braft::ENTRY_TYPE_DATA; entry->id.index = next_log_index; std::string data; butil::string_printf(&data, "hello_%d", next_log_index); entry->data.append(data); ++next_log_index; EXPECT_EQ(0, storage->append_entry(entry)); entry->Release(); } } return NULL; } namespace braft { DECLARE_int32(raft_max_segment_size); } TEST_F(LogStorageTest, multi_read_single_modify_thread_safe) { int32_t saved_max_segment_size = braft::FLAGS_raft_max_segment_size; braft::FLAGS_raft_max_segment_size = 1024; system("rm -rf ./data"); braft::SegmentLogStorage* storage = new braft::SegmentLogStorage("./data"); braft::ConfigurationManager* configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); const int N = 10000; for (int i = 1; i <= N; ++i) { braft::LogEntry* entry = new braft::LogEntry; entry->type = braft::ENTRY_TYPE_DATA; entry->id.index = i; std::string data; butil::string_printf(&data, "hello_%d", i); entry->data.append(data); ASSERT_EQ(0, storage->append_entry(entry)); entry->Release(); } ASSERT_EQ(N, storage->last_log_index()); g_stop = false; g_first_read_index.store(1); g_last_read_index.store(N); bthread_t read_thread[8]; for (size_t i = 0; i < ARRAY_SIZE(read_thread); ++i) { ASSERT_EQ(0, bthread_start_urgent(&read_thread[i], NULL, read_thread_routine, storage)); } bthread_t write_thread; ASSERT_EQ(0, bthread_start_urgent(&write_thread, NULL, write_thread_routine, storage)); ::usleep(5 * 1000 * 1000); g_stop = true; for (size_t i = 0; i < ARRAY_SIZE(read_thread); ++i) { bthread_join(read_thread[i], NULL); } bthread_join(write_thread, NULL); delete configuration_manager; delete storage; braft::FLAGS_raft_max_segment_size = saved_max_segment_size; } TEST_F(LogStorageTest, max_segment_size_illegal) { int32_t saved_max_segment_size = braft::FLAGS_raft_max_segment_size; braft::FLAGS_raft_max_segment_size = -1; system("rm -rf ./data"); braft::SegmentLogStorage* storage = new braft::SegmentLogStorage("./data"); braft::ConfigurationManager* configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(-1, storage->init(configuration_manager)); delete configuration_manager; delete storage; braft::FLAGS_raft_max_segment_size = saved_max_segment_size; } TEST_F(LogStorageTest, large_entry) { system("rm -rf ./data"); braft::SegmentLogStorage* storage = new braft::SegmentLogStorage("./data"); braft::ConfigurationManager* configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); braft::LogEntry* entry = new braft::LogEntry; entry->type = braft::ENTRY_TYPE_DATA; entry->id.index = 1; entry->id.term = 1; std::string data; data.resize(512 * 1024 * 1024, 'a'); entry->data.append(data); ASSERT_EQ(0, storage->append_entry(entry)); entry->Release(); entry = storage->get_entry(1); ASSERT_EQ(data, entry->data.to_string()); entry->Release(); ASSERT_EQ(1, storage->_first_log_index); ASSERT_EQ(1, storage->_last_log_index); ASSERT_EQ(0, storage->_segments.size()); scoped_refptr<braft::Segment> segment = storage->open_segment(); ASSERT_EQ(1, storage->_segments.size()); braft::SegmentLogStorage* storage2 = new braft::SegmentLogStorage("./data"); braft::ConfigurationManager* configuration_manager2 = new braft::ConfigurationManager; ASSERT_EQ(0, storage2->init(configuration_manager2)); ASSERT_EQ(1, storage2->_first_log_index); ASSERT_EQ(1, storage2->_last_log_index); ASSERT_EQ(1, storage2->_segments.size()); } TEST_F(LogStorageTest, reboot_with_checksum_type_changed) { system("rm -rf ./data"); braft::SegmentLogStorage* storage = new braft::SegmentLogStorage("./data"); braft::ConfigurationManager* configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); storage->_checksum_type = 0; // murmurhash for (int i = 0; i < 10; i++) { braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = i + 1; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %d", i + 1); entry->data.append(data_buf); ASSERT_EQ(0, storage->append_entry(entry)); entry->Release(); } delete storage; storage = new braft::SegmentLogStorage("./data"); ASSERT_EQ(0, storage->init(configuration_manager)); storage->_checksum_type = 1; // crc32 for (int i = 10; i < 20; i++) { braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = i + 1; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %d", i + 1); entry->data.append(data_buf); ASSERT_EQ(0, storage->append_entry(entry)); entry->Release(); } delete storage; storage = new braft::SegmentLogStorage("./data"); ASSERT_EQ(0, storage->init(configuration_manager)); for (int index = 1; index <= 20; ++index) { braft::LogEntry* entry = storage->get_entry(index); ASSERT_EQ(entry->id.term, 1); ASSERT_EQ(entry->type, braft::ENTRY_TYPE_DATA); ASSERT_EQ(entry->id.index, index); char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %d", index); ASSERT_EQ(data_buf, entry->data.to_string()); entry->Release(); } delete storage; } TEST_F(LogStorageTest, joint_configuration) { system("rm -rf ./data"); braft::ConfigurationManager cm; std::unique_ptr<braft::SegmentLogStorage> log_storage(new braft::SegmentLogStorage("./data")); ASSERT_EQ(0, log_storage->init(&cm)); for (int i = 1; i <= 20; ++i) { scoped_refptr<braft::LogEntry> entry = new braft::LogEntry; entry->id = braft::LogId(i, 1); entry->peers = new std::vector<braft::PeerId>; entry->type = braft::ENTRY_TYPE_CONFIGURATION; for (int j = 0; j < 3; ++j) { entry->peers->push_back("127.0.0.1:" + std::to_string(i + j)); } entry->old_peers = new std::vector<braft::PeerId>; for (int j = 1; j <= 3; ++j) { entry->old_peers->push_back("127.0.0.1:" + std::to_string(i + j)); } ASSERT_EQ(0, log_storage->append_entry(entry)); } for (int i = 1; i <= 20; ++i) { braft::LogEntry* entry = log_storage->get_entry(i); ASSERT_TRUE(entry != NULL); ASSERT_EQ(entry->type, braft::ENTRY_TYPE_CONFIGURATION); ASSERT_TRUE(entry->peers != NULL); ASSERT_TRUE(entry->old_peers != NULL); braft::Configuration conf; for (int j = 0; j < 3; ++j) { conf.add_peer("127.0.0.1:" + std::to_string(i + j)); } braft::Configuration old_conf; for (int j = 1; j <= 3; ++j) { old_conf.add_peer("127.0.0.1:" + std::to_string(i + j)); } ASSERT_TRUE(conf.equals(*entry->peers)) << conf << " xxxx " << braft::Configuration(*entry->peers); ASSERT_TRUE(old_conf.equals(*entry->old_peers)); entry->Release(); } // Restart log_storage.reset(new braft::SegmentLogStorage("./data")); ASSERT_EQ(0, log_storage->init(&cm)); for (int i = 1; i <= 20; ++i) { braft::LogEntry* entry = log_storage->get_entry(i); ASSERT_TRUE(entry != NULL); ASSERT_EQ(entry->type, braft::ENTRY_TYPE_CONFIGURATION); ASSERT_TRUE(entry->peers != NULL); ASSERT_TRUE(entry->old_peers != NULL); braft::Configuration conf; for (int j = 0; j < 3; ++j) { conf.add_peer("127.0.0.1:" + std::to_string(i + j)); } braft::Configuration old_conf; for (int j = 1; j <= 3; ++j) { old_conf.add_peer("127.0.0.1:" + std::to_string(i + j)); } ASSERT_TRUE(conf.equals(*entry->peers)) << conf << " xxxx " << braft::Configuration(*entry->peers); ASSERT_TRUE(old_conf.equals(*entry->old_peers)); entry->Release(); } for (int i = 1; i <= 20; ++i) { braft::LogEntry* entry = log_storage->get_entry(i); ASSERT_TRUE(entry != NULL); ASSERT_EQ(entry->type, braft::ENTRY_TYPE_CONFIGURATION); ASSERT_TRUE(entry->peers != NULL); ASSERT_TRUE(entry->old_peers != NULL); ASSERT_EQ(1, entry->id.term); braft::Configuration conf; for (int j = 0; j < 3; ++j) { conf.add_peer("127.0.0.1:" + std::to_string(i + j)); } braft::Configuration old_conf; for (int j = 1; j <= 3; ++j) { old_conf.add_peer("127.0.0.1:" + std::to_string(i + j)); } ASSERT_TRUE(conf.equals(*entry->peers)); ASSERT_TRUE(old_conf.equals(*entry->old_peers)); entry->Release(); } for (int i = 1; i <= 20; ++i) { braft::ConfigurationEntry entry; cm.get(i, &entry); ASSERT_EQ(braft::LogId(i, 1), entry.id); braft::Configuration conf; for (int j = 0; j < 3; ++j) { conf.add_peer("127.0.0.1:" + std::to_string(i + j)); } braft::Configuration old_conf; for (int j = 1; j <= 3; ++j) { old_conf.add_peer("127.0.0.1:" + std::to_string(i + j)); } ASSERT_TRUE(conf.equals(entry.conf)); ASSERT_TRUE(old_conf.equals(entry.old_conf)); } } TEST_F(LogStorageTest, append_close_load_append_with_io_metric) { ::system("rm -rf data"); braft::IOMetric metric; braft::FLAGS_raft_trace_append_entry_latency = true; braft::LogStorage* storage = new braft::SegmentLogStorage("./data"); braft::ConfigurationManager* configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); // append entry for (int i = 0; i < 100000; i++) { std::vector<braft::LogEntry*> entries; for (int j = 0; j < 5; j++) { int64_t index = 5*i + j + 1; braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 1; entry->id.index = index; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %ld", index); entry->data.append(data_buf); entries.push_back(entry); } ASSERT_EQ(5, storage->append_entries(entries, &metric)); for (size_t j = 0; j < entries.size(); j++) { delete entries[j]; } } ASSERT_NE(0, metric.open_segment_time_us); ASSERT_NE(0, metric.append_entry_time_us); ASSERT_NE(0, metric.sync_segment_time_us); LOG(INFO) << metric; delete storage; delete configuration_manager; // reinit storage = new braft::SegmentLogStorage("./data"); configuration_manager = new braft::ConfigurationManager; ASSERT_EQ(0, storage->init(configuration_manager)); // append entry for (int i = 100000; i < 200000; i++) { std::vector<braft::LogEntry*> entries; for (int j = 0; j < 5; j++) { int64_t index = 5*i + j + 1; braft::LogEntry* entry = new braft::LogEntry(); entry->type = braft::ENTRY_TYPE_DATA; entry->id.term = 2; entry->id.index = index; char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %ld", index); entry->data.append(data_buf); entries.push_back(entry); } ASSERT_EQ(5, storage->append_entries(entries, &metric)); for (size_t j = 0; j < entries.size(); j++) { delete entries[j]; } } // check and read ASSERT_EQ(storage->first_log_index(), 1); ASSERT_EQ(storage->last_log_index(), 200000*5); for (int i = 0; i < 200000*5; i++) { int64_t index = i + 1; braft::LogEntry* entry = storage->get_entry(index); if (i < 100000*5) { ASSERT_EQ(entry->id.term, 1); } else { ASSERT_EQ(entry->id.term, 2); } ASSERT_EQ(entry->type, braft::ENTRY_TYPE_DATA); ASSERT_EQ(entry->id.index, index); char data_buf[128]; snprintf(data_buf, sizeof(data_buf), "hello, world: %ld", index); ASSERT_EQ(data_buf, entry->data.to_string()); entry->Release(); } delete storage; delete configuration_manager; }
34.445483
93
0.589333
[ "vector" ]
135c345011dc3b996e33035b95ac72e9c4ddb740
47,952
cxx
C++
admin/netui/common/src/blt/blt/bltlc.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/netui/common/src/blt/blt/bltlc.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/netui/common/src/blt/blt/bltlc.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/**********************************************************************/ /** Microsoft Windows/NT **/ /** Copyright(c) Microsoft Corp., 1991 **/ /**********************************************************************/ /* bltlc.cxx BLT list control: implementations FILE HISTORY: rustanl 20-Nov-1990 Created beng 11-Feb-1991 Uses lmui.hxx rustanl 22-Feb-1991 Changes due to new LC hierarchy rustanl 19-Mar-1991 Added COMBOBOX::SetMaxLength, and corresponding constructor parameter rustanl 21-Mar-1991 Folded in code review changes from CR on 20-Mar-1991 attended by JimH, GregJ, Hui-LiCh, RustanL. beng 14-May-1991 Exploded blt.hxx into components terryk 25-Jul-1991 Add SetItemData, QuerySelCount and QuerySelItems to LIST_CONTROL class Also add SetTopIndex, ChangeSel rustanl 12-Aug-1991 Hid some single/mult sel differences between the cozy covers of BLT terryk 22-Mar-1992 add STRING_LIST_CONTROL's InsertItem jonn 09-Sep-1993 Moved fns from SET_CONTROL_LISTBOX to LISTBOX */ #include "pchblt.hxx" // Precompiled header // ----- Local macros ----- /* The following macro is used to conveniently specify a LB_ or CB_ * manifest, depending on the value of _fCombo. Note, although * most (not all!) LB_ and CB_ manifests have the same name (apart from * the prefix) and SendMessage semantics, they do not have the same values * at all. An experienced PM programmer may at this point be stunned. */ #define LC_MSG( suffix ) ( IsCombo() ? ( CB_##suffix ) : ( LB_##suffix )) // This file assumes that LB_ERR has the same value as CB_ERR. The file // only uses LB_ERR when checking return codes. If the two values differ, // the code needs to change to use ( IsCombo() ? CB_ERR : LB_ERR ) instead. #if ( LB_ERR != CB_ERR ) #error "This file assumes LB_ERR == CB_ERR." #endif /********************************************************************** NAME: LIST_CONTROL::LIST_CONTROL SYNOPSIS: Constructor for list-control abstract object ENTRY: OWNER_WINDOW * powin - pointer to the owner window CID cid - cid of the listbox BOOL fCombo - flag for combo box HISTORY: rustanl 20-Nov-1990 Created beng 17-May-1991 Added app-window constructor **********************************************************************/ LIST_CONTROL::LIST_CONTROL( OWNER_WINDOW * powin, CID cid, BOOL fCombo ) : CONTROL_WINDOW( powin, cid ), _fCombo( fCombo ) , _iSavedSelection( 0 ), _piSavedMultSel( NULL ) { if ( QueryError() ) return; } LIST_CONTROL::LIST_CONTROL( OWNER_WINDOW * powin, CID cid, BOOL fCombo, XYPOINT xy, XYDIMENSION dxy, ULONG flStyle, const TCHAR * pszClassName ) : CONTROL_WINDOW( powin, cid, xy, dxy, flStyle, pszClassName ), _fCombo( fCombo ) , _iSavedSelection( 0 ), _piSavedMultSel( NULL ) { if ( QueryError() ) return; } LIST_CONTROL::~LIST_CONTROL() { delete _piSavedMultSel; } /******************************************************************* NAME: LIST_CONTROL::IsMultSel SYNOPSIS: Returns whether or not several items in the list control can be selected at one time. RETURNS: FALSE if at most one item can be selected at one time in the list control (i.e., the list control is either a combo box or a single select listbox) TRUE if several items can be selected simultaneously (i.e., the list control is either a extended select listbox or a multiple select listbox) HISTORY: rustanl 12-Aug-1991 Created ********************************************************************/ BOOL LIST_CONTROL::IsMultSel() const { if ( IsCombo()) return FALSE; ULONG ulStyle = QueryStyle(); if ( ( ulStyle & LBS_MULTIPLESEL ) || ( ulStyle & LBS_EXTENDEDSEL )) { return TRUE; } return FALSE; } /********************************************************************** NAME: LIST_CONTROL::AddItemData SYNOPSIS: Add an item to the list box control ENTRY: VOID * pv - pointer to the item to be added EXIT: LB_ERR if an error occurs LB_ERRSPACE - not enough space to add the item Otherwise, it will be index of the item in the listbox HISTORY: rustanl 20-Nov-1990 Created **********************************************************************/ INT LIST_CONTROL::AddItemData( VOID * pv ) { return (INT)Command( LC_MSG( ADDSTRING), 0, (LPARAM)pv ); } /**********************************************************\ NAME: LIST_CONTROL::SetItemData SYNOPSIS: set the data item to new value ENTRY: INT i - index of the item VOID *pv - the new data RETURN: The return value is LB_ERR if an error occurs HISTORY: terryk 25-Jul-1991 Created \**********************************************************/ INT LIST_CONTROL::SetItemData( INT i, VOID * pv ) { return (INT)Command( LC_MSG( SETITEMDATA ), i, (LPARAM)pv ); } /**********************************************************\ NAME: LIST_CONTROL::InsertItemData SYNOPSIS: insert the item data in the given index ENTRY: INT i - index of the item VOID *pv - the new data RETURN: The return value is LB_ERR if an error occurs HISTORY: kevinl 23-Oct-1991 Created jonn 16-Feb-1993 Maintains caret position on WIN32 \**********************************************************/ INT LIST_CONTROL::InsertItemData( INT i, VOID * pv ) { #ifdef WIN32 INT nCaretIndex = 0; BOOL fMultSel = IsMultSel(); if ( fMultSel ) { nCaretIndex = QueryCaretIndex(); } #endif INT nReturn = (INT)Command( LC_MSG( INSERTSTRING ), i, (LPARAM)pv ); // nReturn could be LB_ERR or LB_ERRSPACE #ifdef WIN32 if ( fMultSel && (nReturn <= nCaretIndex) && (nReturn >= 0) ) { SetCaretIndex( nCaretIndex+1 ); } #endif return nReturn; } /********************************************************************** NAME: LIST_CONTROL::SetTopIndex SYNOPSIS: Set the index of the first visible control in list ctrl ENTRY: i - the index NOTES: CODEWORK - this method only works on listboxes. As such, it should move to some intermediate class. HISTORY: terryk 26-Jul-1991 Created ***********************************************************************/ VOID LIST_CONTROL::SetTopIndex( INT i ) { REQUIRE( (INT)Command( LB_SETTOPINDEX, i, 0 ) != LB_ERR ); } /******************************************************************* NAME: LIST_CONTROL::QueryTopIndex SYNOPSIS: Returns the index of the topmost visible line RETURNS: listbox index NOTES: CODEWORK - this method only works on listboxes. As such, it should move to some intermediate class. HISTORY: beng 22-Aug-1991 Created ********************************************************************/ INT LIST_CONTROL::QueryTopIndex() const { return (INT)Command(LB_GETTOPINDEX); } /********************************************************************** NAME: LIST_CONTROL::SetCaretIndex SYNOPSIS: Set the index of the item with the caret, and scroll the item into view. ENTRY: i - the index fPartiallyVisibleOK - if TRUE, the listbox will be scrolled until the item is at least partially visible. If TRUE, the item will be fully visible. HISTORY: jonn 15-Sep-1993 Created ***********************************************************************/ VOID LIST_CONTROL::SetCaretIndex( INT i, BOOL fPartiallyVisibleOK ) { REQUIRE( (INT)Command( LB_SETCARETINDEX, i, fPartiallyVisibleOK ) != LB_ERR ); } /******************************************************************* NAME: LIST_CONTROL::QueryCaretIndex SYNOPSIS: Returns the index of the item with the caret RETURNS: listbox index HISTORY: jonn 15-Sep-1993 Created ********************************************************************/ INT LIST_CONTROL::QueryCaretIndex() const { return (INT)Command( LB_GETCARETINDEX ); } /********************************************************************** NAME: LIST_CONTROL::QueryCount SYNOPSIS: query the total number of items in the list box EXIT: total number of item in the list box HISTORY: rustanl 20-Nov-1990 Created **********************************************************************/ INT LIST_CONTROL::QueryCount() const { return (INT)Command( LC_MSG( GETCOUNT )); } /**********************************************************\ NAME: LIST_CONTROL::QuerySelCount SYNOPSIS: get the number of items selected in the list control RETURN: total number of selected items HISTORY: terryk 25-Jul-1991 Created rustanl 12-Aug-1991 Added support for both single sel listboxes, too. \**********************************************************/ INT LIST_CONTROL::QuerySelCount() const { if ( IsMultSel()) { INT c = (INT)Command( LB_GETSELCOUNT ); UIASSERT( c >= 0 ); return c; } // combo or single sel listbox if ( QueryCurrentItem() < 0 ) return 0; return 1; } /********************************************************************* NAME: LIST_CONTROL::QuerySelItem SYNOPSIS: return an array of integer indecies for the currently selected list control items ENTRY: piSel - Pointer to buffer (array) which will receive the selected items. ciMax - Maximum number of entries that array pointed to by piSel can hold RETURN: An API return code, which is NERR_Success on success. Other often-returned errors may include: ERROR_MORE_DATA - More than ciMax items are selected, but only ciMax indicies were copied into the piSel buffer. HISTORY: terryk 25-JUl-1991 Created rustanl 12-Aug-1991 Added support for single select listboxes, too. **********************************************************************/ APIERR LIST_CONTROL::QuerySelItems( INT * piSel, INT ciMax ) const { UIASSERT( ciMax >= 0 ); UIASSERT( ciMax == 0 || piSel != NULL ); if ( IsMultSel()) { INT c = (INT)Command( LB_GETSELITEMS, ciMax, (LPARAM)piSel ); UIASSERT( c >= 0 ); if ( QuerySelCount() < ciMax ) return ERROR_MORE_DATA; return NERR_Success; } INT iCurr = QueryCurrentItem(); if ( iCurr < 0 ) { // no item is selected return NERR_Success; } if ( ciMax < 1 ) return ERROR_MORE_DATA; piSel[ 0 ] = iCurr; return NERR_Success; } /********************************************************************* NAME: LISTBOX::QueryItemHeight SYNOPSIS: Calculate the height of any entry in the listbox HISTORY: beng 21-May-1992 Created jonn 09-Sep-1993 Moved from SET_CONTROL_LISTBOX to LISTBOX *********************************************************************/ UINT LIST_CONTROL::QueryItemHeight( UINT ilb ) const { LONG nRet = (LONG)Command( LB_GETITEMHEIGHT, ilb ); ASSERT( nRet != LB_ERR ); return nRet; } /********************************************************************* NAME: LISTBOX::IsItemSelected SYNOPSIS: Returns whether a given item is selected HISTORY: beng 21-May-1992 Created jonn 09-Sep-1993 Moved from SET_CONTROL_LISTBOX to LISTBOX *********************************************************************/ BOOL LIST_CONTROL::IsItemSelected( UINT ilb ) const { LONG nRet = (LONG)Command( LB_GETSEL, ilb ); ASSERT(nRet != LB_ERR); return (nRet > 0) ? TRUE : FALSE; // works in error case, too } /********************************************************************** NAME: LIST_CONTROL::SelectItem SYNOPSIS: Select the specified item ENTRY: INT i - index for the selected item BOOL fSelect - TRUE to select the item (default) FALSE to unselect the item EXIT: If fSelect is TRUE and i is a valid index, Item i will be selected. If fSelect is TRUE and i is -1, No item will be selected. If fSelect is FALSE and i is a valid index, Item i will be unselected. NOTES: Passing i as -1 and fSelect as TRUE means to remove the hi-lite bar marking the current selection. A client should try to avoid depending on this, and instead calling RemoveSelection. If fSelect is FALSE, i must specify a valid index. HISTORY: rustanl 20-Nov-1990 Created rustanl 13-Aug-1991 Added fSelect parameter and multiple select support **********************************************************************/ VOID LIST_CONTROL::SelectItem( INT i, BOOL fSelect ) { if ( fSelect ) { if ( IsMultSel()) { REQUIRE( Command( LB_SETSEL, ( i >= 0 ), (ULONG)((LONG)i)) != LB_ERR ); return; } // Although not documented in the Windows SDK, the LB_SETCURSEL (and // CB_SETCURSEL, which eventually maps to LB_SETCURSEL) message // returns wParam if wParam is a valid index or is -1; otherwise, it // returns LB_ERR. (Note, that a return code of -1 can thus mean two // different things, depending on what was passed in.) // // The SDK only says that the message returns LB_ERR on error; it does // not say anything about the return code if no error occurs. // // The REQUIRE statement will fail precisely when the given index // is not a valid index and is not -1. // REQUIRE( (LONG)Command( LC_MSG( SETCURSEL ), (UINT)i ) == (LONG)i ); } else { UIASSERT( 0 <= i && i < QueryCount()); if ( IsMultSel()) { REQUIRE( Command( LB_SETSEL, FALSE, (ULONG)((LONG)i)) != LB_ERR ); return; } if ( QueryCurrentItem() == i ) RemoveSelection(); } } /********************************************************************** NAME: LIST_CONTROL::SelectItems SYNOPSIS: Select the specified items ENTRY: INT * pi - indexes for the selected items INT c - number of items BOOL fSelect - TRUE to select the item (default) FALSE to unselect the item NOTES: Only pass valid indices as parameters. The current selection will not be cleared (for multi-select listboxes). HISTORY: jonn 15-Sep-1993 Created **********************************************************************/ VOID LIST_CONTROL::SelectItems( INT * pi, INT c, BOOL fSelect ) { ASSERT( c == 0 || pi != NULL ); INT i; for ( i = 0; i < c; i++ ) { SelectItem( pi[i], fSelect ); } } /********************************************************************** NAME: LIST_CONTROL::DeleteItem SYNOPSIS: delete the specified item from the listbox ENTRY: INT i - item to be deleted RETURN: The return value is a count of the strings remaining in the list. THe return value is LB_ERR if an error occurs. HISTORY: rustanl 20-Nov-1990 Created jonn 16-Feb-1993 Maintains caret position on WIN32 **********************************************************************/ INT LIST_CONTROL::DeleteItem( INT i ) { // The LC_MSG( DELETESTRING ) message returns the number of items // remaining in the list control on success, and LB_ERR (a negative // value) on failure. #ifdef WIN32 INT nCaretIndex = 0; BOOL fMultSel = IsMultSel(); if ( fMultSel ) { nCaretIndex = QueryCaretIndex(); } #endif INT nReturn = (INT)Command( LC_MSG( DELETESTRING ), (UINT)i ); #ifdef WIN32 if ( fMultSel && (i <= nCaretIndex) && (nReturn != LB_ERR) ) { // move caret position back one if earlier item was deleted // if caret was on first item, then i >= nCaretPosition, so this // will not move position to nCaretPosition < 0 if ( i < nCaretIndex ) { nCaretIndex--; } // move caret position to end of list if it is past end if ( nCaretIndex >= QueryCount() ) { nCaretIndex = QueryCount() - 1; } // only set caret position if item exists if ( (nCaretIndex >= 0) && (nCaretIndex < QueryCount()) ) { SetCaretIndex( nCaretIndex ); } } #endif return nReturn; } /********************************************************************** NAME: LIST_CONTROL::DeleteAllItems SYNOPSIS: delete all the item from the listbox HISTORY: rustanl 20-Nov-1990 Created beng 22-Sep-1991 Correct usage of GetVersion **********************************************************************/ VOID LIST_CONTROL::DeleteAllItems() { Command( LC_MSG( RESETCONTENT )); ULONG ulWindowsVersion = ::GetVersion(); if ( ! _fCombo && LOBYTE( LOWORD(ulWindowsVersion) ) == 3 && // major version no. HIBYTE( LOWORD(ulWindowsVersion) ) < 10 ) // minor version no. { // This function uses a RustanL/ChuckC hack to get around a // Windows 3.00 listbox problem where Windows doesn't get rid of the // scrollbar when a listbox is emptied. The work-around works as // follows: // // First, all items are removed from the listbox (above). At // this time, the scrollbar may still be there. // // Then, one item is added to the listbox. The listbox will at // this time realize that it is not in need of the scrollbar, so // it will remove it, if it was there. // // Finally, the listbox is cleared again, removing the one // item that was inserted. // // This problem has been fixed in Windows 3.10; hence, the version // check above. // VOID * pv; ULONG flStyle = QueryStyle(); if ( ( flStyle & ( LBS_OWNERDRAWFIXED | LBS_OWNERDRAWVARIABLE )) && ! ( flStyle & LBS_HASSTRINGS )) { // The list control is a BLT listbox. We should thus make pv a // pointer to an LBI item. Rather than calling 'new' and the LBI // constructor (which may fail and return a NULL anyway), we // simply set pv to NULL. ShellDlgProc will still be able to // properly delete this item (since C++ always defines delete // on NULL pointers). However, this will generate a WM_DRAWITEM // message. Hence, every CD_Draw routine must check the pointer // for NULL before beginning to draw. pv = NULL; } else { // The list control is a string list control pv = SZ(""); } // Note. The item to be temporarily added to the list control, pv, // is either NULL or points to the empty string, neither one of // which will cause anything to be painted (even though it may // generate a WM_DRAWITEM message). Hence, the user will not // get any flickering as a result of adding this item. AddItemData( pv ); Command( LC_MSG( RESETCONTENT )); } } /********************************************************************** NAME: LIST_CONTROL::QueryCurrentItem SYNOPSIS: get the index of the first currently selected item RETURN: The return value is the index of the first currently selected item. It is a negative value if no item is selected. NOTES: Since LIST_CONTROL::QuerySelItems calls this method, this method needs to be careful if calling QuerySelItems. For this reason, this method calls Command directly with the LB_GETSELITEMS parameter. HISTORY: rustanl 20-Nov-1990 Created rustanl 12-Aug-1991 Added multiple selection support **********************************************************************/ INT LIST_CONTROL::QueryCurrentItem() const { if ( IsMultSel()) { INT iSel; INT cRet = (INT)Command( LB_GETSELITEMS, 1, (LPARAM)&iSel ); UIASSERT( cRet == 0 || cRet == 1 ); if ( cRet == 1 ) return iSel; return -1; } return (INT)Command( LC_MSG( GETCURSEL )); } /******************************************************************* NAME: LIST_CONTROL::SaveValue SYNOPSIS: Saves the state of the list control and unselects the current item EXIT: Unselected listbox NOTES: See LIST_CONTROL header notes for comments on multiselection HISTORY: Johnl 25-Apr-1991 Created JonN 04-Dec-1992 Supports multiple-selection ********************************************************************/ VOID LIST_CONTROL::SaveValue( BOOL fInvisible ) { if ( IsMultSel() ) { delete _piSavedMultSel; _piSavedMultSel = NULL; _iSavedSelection = QuerySelCount(); _piSavedMultSel = new INT[ _iSavedSelection ]; if ( _piSavedMultSel == NULL || QuerySelItems( _piSavedMultSel, _iSavedSelection ) != NERR_Success ) { DBGEOL( "NETUI: LIST_CONTROL::SaveValue(): Could not save selection" ); delete _piSavedMultSel; _piSavedMultSel = NULL; } } else { _iSavedSelection = QueryCurrentItem(); } if ( fInvisible ) RemoveSelection(); } /******************************************************************* NAME: LIST_CONTROL::RestoreValue SYNOPSIS: Restores LIST_CONTROL after SaveValue NOTES: See CONTROL_VALUE for more details. See LIST_CONTROL header notes for comments on multiselection HISTORY: Johnl 25-Apr-1991 Created JonN 04-Dec-1992 Supports multiple-selection ********************************************************************/ VOID LIST_CONTROL::RestoreValue( BOOL fInvisible ) { if ( fInvisible ) { if ( IsMultSel() ) { if ( _piSavedMultSel == NULL ) { DBGEOL( "NETUI: LIST_CONTROL::RestoreValue(): Could not restore selection" ); } else { RemoveSelection(); for ( INT i = 0; i < _iSavedSelection; i++ ) SelectItem( _piSavedMultSel[i] ); } } else { SelectItem( _iSavedSelection ); } } } /******************************************************************* NAME: LIST_CONTROL::QueryEventEffects SYNOPSIS: Returns one of the CVMI_* values. See CONTROL_VALUE for more information. ENTRY: Let the parent group test the lParam to see whether it will change the listbox or not RETURNS: If the selection is changed, it will return CVMI_VALUE_CHANGE CVMI_NO_VALUE_CHANGE otherwise NOTES: This only handles listbox messages, COMBOBOX::QueryEventEffects handles the combobox messages. HISTORY: Johnl 29-Apr-1991 Created beng 31-Jul-1991 Renamed from QMessageInfo beng 04-Oct-1991 Win32 conversion ********************************************************************/ UINT LIST_CONTROL::QueryEventEffects( const CONTROL_EVENT & e ) { // UIASSERT( !IsMultSel()); // not support (yet) switch ( e.QueryCode() ) { case LBN_SELCHANGE: return CVMI_VALUE_CHANGE; case LBN_SETFOCUS: return CVMI_VALUE_CHANGE | CVMI_RESTORE_ON_INACTIVE; default: break; } return CVMI_NO_VALUE_CHANGE; } /********************************************************************** NAME: STRING_LIST_CONTROL::STRING_LIST_CONTROL SYNOPSIS: constructor ENTRY: OWNER_WINDOW * powin - pointer to the owner window CID cid - cid of the string list control BOOL fCombo - flag for combo box HISTORY: rustanl 20-Nov-1990 Created beng 17-May-1991 Added app-window constructor **********************************************************************/ STRING_LIST_CONTROL::STRING_LIST_CONTROL( OWNER_WINDOW * powin, CID cid, BOOL fCombo ) : LIST_CONTROL( powin, cid, fCombo ) { if ( QueryError() ) return; // nothing else to do } STRING_LIST_CONTROL::STRING_LIST_CONTROL( OWNER_WINDOW * powin, CID cid, BOOL fCombo, XYPOINT xy, XYDIMENSION dxy, ULONG flStyle, const TCHAR * pszClassName ) : LIST_CONTROL( powin, cid, fCombo, xy, dxy, flStyle, pszClassName ) { if ( QueryError() ) return; // nothing else to do } /********************************************************************** NAME: STRING_LIST_CONTROL::AddItem SYNOPSIS: Add a string to list box ENTRY: TCHAR * pch - string to be added EXIT: LB_ERR if an error occurs LB_ERRSPACE if not enough space to add the item index of the new added string if no error occurs HISTORY: rustanl 20-Nov-1990 Created **********************************************************************/ INT STRING_LIST_CONTROL::AddItem( const TCHAR * pch ) { return AddItemData( (VOID *)pch ); } /********************************************************************** NAME: STRING_LIST_CONTROL::AddItemIdemp SYNOPSIS: Same as add item, however, it will not add the item to the listbox if the item already existed in the listbox ENTRY: TCHAR * psz - string to be added EXIT: LB_ERR if an error occurs LB_ERRSPACE if not enough space to add the item index of the new added string if no error occurs HISTORY: rustanl 20-Nov-1990 Created **********************************************************************/ INT STRING_LIST_CONTROL::AddItemIdemp( const TCHAR * pch ) { INT i = FindItemExact( pch ); if ( i < 0 ) return AddItem( pch ); return i; } /********************************************************************** NAME: STRING_LIST_CONTROL::InsertItem SYNOPSIS: Insert the item in the specified location ENTRY: INT i - location index TCHAR * psz - string to be added EXIT: LB_ERR if an error occurs LB_ERRSPACE if not enough space to add the item index of the new added string if no error occurs HISTORY: terryk 22-Mar-1992 Created **********************************************************************/ INT STRING_LIST_CONTROL::InsertItem( INT i, const TCHAR * pch ) { return InsertItemData( i, (VOID *) pch ); } /********************************************************************** NAME: STRING_LIST_CONTROL::FindItem SYNOPSIS: find the string from the listbox ENTRY: pchPrefix - point to the prefix string, the string must be null-terminated iLastSearchResult - contains the index of the item before the first item to be searched. When the search reaches the bottom of the listbox, it continues from the top of the listbox back to the item specified by this value. RETURNS: The return value is the index of the matching item or LB_ERR if the search was unsuccessful. NOTES: If the index given is -1, Windows searches the entire listbox from the beginning. HISTORY: rustanl 20-Nov-1990 Created beng 21-Aug-1991 Removed magic LC_NEW_SEARCH value **********************************************************************/ INT STRING_LIST_CONTROL::FindItem( const TCHAR * pchPrefix ) const { return FindItem(pchPrefix, -1); } INT STRING_LIST_CONTROL::FindItem( const TCHAR * pchPrefix, INT iLastSearchResult ) const { return (INT)Command( LC_MSG( FINDSTRING ), (UINT)iLastSearchResult, (LPARAM)pchPrefix ); } /********************************************************************** NAME: STRING_LIST_CONTROL::FindItemExact SYNOPSIS: Returns the index of the precise match ENTRY: psz - pointer to string sought iLastSearchResult - index from which to search RETURNS: the position of the specified string, or -1 if not found. HISTORY: rustanl 20-Nov-1990 Created beng 10-Jun-1991 Unicode mods beng 01-May-1992 API changes **********************************************************************/ INT STRING_LIST_CONTROL::FindItemExact( const TCHAR * psz ) const { return FindItemExact(psz, -1); } INT STRING_LIST_CONTROL::FindItemExact( const TCHAR * psz, INT iLastSearchResult ) const { INT iFirstMatch = FindItem( psz, iLastSearchResult ); if ( iFirstMatch < 0 ) { // Prefix not found. Return failure. // return -1; } INT cchLen = ::strlenf( psz ); INT i = iFirstMatch; do { // We find out whether or not FindItem can find any item matching // the given one before the loop. If it can't find the item, // we don't even enter the loop. Since FindItem has the property // of always returning a non-negative index when given a string // which is indeed a prefix of some item in the list control, // regardless of how many consecutive times FindItem is called, // i should invariably not be negative within this loop. // UIASSERT( i >= 0 ); // Item i has prefix pch, but matches the string pointed to by // pch if and only if it has the same length as pch. // if ( QueryItemLength( i ) == cchLen ) return i; // exact match; return index i = FindItem( psz, i ); } while ( i != iFirstMatch ); return -1; // we circled through all items with prefix pch, // but none match pch exactly } /********************************************************************** NAME: STRING_LIST_CONTROL::QueryItemText SYNOPSIS: Returns the text of a given entry in the listbox ENTRY: pnls - pointer to host NLS_STR i - index into listbox or pb - pointer to BYTE buffer cb - number of BYTES available in buffer i - index into listbox EXIT: RETURNS: 0 if successful NOTES: The <pch, i> version is private to the class. HISTORY: rustanl 20-Nov-1990 Created beng 10-Jun-1991 Changed return type beng 21-Aug-1991 Eliminated LC_CURRENT_ITEM magic number beng 01-May-1992 API changes **********************************************************************/ APIERR STRING_LIST_CONTROL::QueryItemText( NLS_STR * pnls, INT i ) const { if (pnls == NULL) return ERROR_INVALID_PARAMETER; if (i < 0) // no item selected, or else invalid param return ERROR_NEGATIVE_SEEK; INT cbLen = QueryItemSize( i ); if ( cbLen < 0 ) { UIASSERT( FALSE ); // invalid list control index return ERROR_INVALID_TARGET_HANDLE; } BLT_SCRATCH scratch( cbLen ); if (!scratch) return scratch.QueryError(); APIERR err = QueryItemTextAux( (TCHAR*)scratch.QueryPtr(), i ); if (err != NERR_Success) return err; return pnls->CopyFrom((TCHAR *)scratch.QueryPtr()); } APIERR STRING_LIST_CONTROL::QueryItemText( TCHAR * pchBuffer, INT cbBuffer, INT i ) const { if (pchBuffer == NULL) return ERROR_INVALID_PARAMETER; if ( i < 0 ) // no item selected, or else invalid param return ERROR_NEGATIVE_SEEK; if ( cbBuffer < QueryItemSize(i) ) return NERR_BufTooSmall; return QueryItemTextAux(pchBuffer, i); // call through to private member } APIERR STRING_LIST_CONTROL::QueryItemTextAux(TCHAR * pchBuffer, INT i) const { INT nRet = (INT)Command( ( IsCombo() ? CB_GETLBTEXT : LB_GETTEXT ), (WPARAM)i, (LPARAM)pchBuffer ); return (nRet < 0) ? ERROR_INVALID_TARGET_HANDLE : NERR_Success; } /********************************************************************** NAME: STRING_LIST_CONTROL::QueryItemLength SYNOPSIS: Returns the cch (character count) of a given item ENTRY: i - index of item in listbox EXIT: RETURNS: cch if >= 0; error if -1 NOTES: This character count does not include the terminating char. On DBCS systems this will not correspond to the number of glyphs in the string. HISTORY: beng 10-Jun-1991 Created anew beng 21-Aug-1991 Eliminated LC_CURRENT_ITEM magic number beng 30-Apr-1992 API changes **********************************************************************/ INT STRING_LIST_CONTROL::QueryItemLength( INT i ) const { if (i < 0) return -1; // cascade errors // Note that these messages return a length in TCHARs // which does not include the terminating character. // return (INT)Command( ( IsCombo() ? CB_GETLBTEXTLEN : LB_GETTEXTLEN ), (UINT)i ); } /********************************************************************** NAME: STRING_LIST_CONTROL::QueryItemSize SYNOPSIS: Returns the cb (byte count) of a given item, including the terminating character ENTRY: i - index of item in listbox RETURNS: cb if >= 0; -1 if error NOTES: The character count corresponds to the value returned by strlen(). This is not the same as the number of glyphs in the string. HISTORY: rustanl 20-Nov-1990 Initially created beng 10-Jun-1991 Created from old QueryItemLen beng 21-Aug-1991 Eliminated LC_CURRENT_ITEM magic number beng 30-Apr-1992 API changes **********************************************************************/ INT STRING_LIST_CONTROL::QueryItemSize( INT i ) const { INT cchRet = QueryItemLength(i); // get chars. (handle errors) if ( cchRet < 0 ) return -1; return (cchRet + 1) * sizeof(TCHAR); // convert to total bytes } /********************************************************************** NAME: STRING_LISTBOX::STRING_LISTBOX SYNOPSIS: constructor ENTRY: OWNER_WINDOW * powin - pointer to the owner window CID cid - cid of the listbox HISTORY: rustanl 20-Nov-1990 Created DavidHov 21-Jan-1992 Added FONT member support **********************************************************************/ STRING_LISTBOX::STRING_LISTBOX( OWNER_WINDOW * powin, CID cid, enum FontType font ) : STRING_LIST_CONTROL( powin, cid, FALSE ), _fontListBox( font ) { if ( QueryError() ) return; // Note: construction should not fail if font unavailable. if ( ! _fontListBox.QueryError() ) Command( WM_SETFONT, (WPARAM) _fontListBox.QueryHandle(), (LPARAM) FALSE ) ; } /********************************************************************** NAME: STRING_LISTBOX::STRING_LISTBOX SYNOPSIS: constructor for control directly on the face of a window. ENTRY: OWNER_WINDOW * pointer to the owner window CID control id XYPOINT location of control in parent window XYDIMENSION size of control ULONG style control bits TCHAR * class name enum FontType font to be used HISTORY: DavidHov 21-Jan-1992 Created, since FONT member disallowed default construction. **********************************************************************/ STRING_LISTBOX::STRING_LISTBOX( OWNER_WINDOW * powin, CID cid, XYPOINT xy, XYDIMENSION dxy, ULONG flStyle, const TCHAR * pszClassName, enum FontType font ) : STRING_LIST_CONTROL( powin, cid, FALSE, xy, dxy, flStyle, pszClassName ), _fontListBox( font ) { if ( QueryError() ) return; // Note: construction should not fail if font unavailable. if ( ! _fontListBox.QueryError() ) Command( WM_SETFONT, (WPARAM) _fontListBox.QueryHandle(), (LPARAM) FALSE ); } /********************************************************************** NAME: COMBOBOX::COMBOBOX SYNOPSIS: Constructor for combo box control ENTRY: EXIT: HISTORY: rustanl 20-Nov-1990 Created beng 17-May-1991 Added app-window constructor beng 04-Oct-1991 Win32 conversion beng 07-Nov-1991 Error mapping beng 30-Apr-1992 API change; cch instead of cb **********************************************************************/ COMBOBOX::COMBOBOX( OWNER_WINDOW * powin, CID cid, UINT cchMaxLen ) : STRING_LIST_CONTROL( powin, cid, TRUE ) , _nlsSaveValue() { if ( QueryError() ) return; if ( _nlsSaveValue.QueryError() ) { ReportError( _nlsSaveValue.QueryError() ); return; } if ( cchMaxLen > 0 && !SetMaxLength( cchMaxLen )) { // assume low memory (why did SetMaxLength fail?) ReportError( BLT::MapLastError(ERROR_NOT_ENOUGH_MEMORY) ); return; } } COMBOBOX::COMBOBOX( OWNER_WINDOW * powin, CID cid, UINT cchMaxLen, XYPOINT xy, XYDIMENSION dxy, ULONG flStyle, const TCHAR * pszClassName ) : STRING_LIST_CONTROL( powin, cid, TRUE, xy, dxy, flStyle, pszClassName ), _nlsSaveValue() { if ( QueryError() ) return; if ( _nlsSaveValue.QueryError() ) { ReportError( _nlsSaveValue.QueryError() ); return; } if ( cchMaxLen > 0 && !SetMaxLength( cchMaxLen )) { // assume low memory ReportError( BLT::MapLastError(ERROR_NOT_ENOUGH_MEMORY) ); return; } } /******************************************************************* NAME: COMBOBOX::SetMaxLength SYNOPSIS: Sets a limit on the number of bytes that the text string contained in the combo box may be. ENTRY: cchMaxLen - Indicates the new limit, or 0 to indicate "no limit" RETURN: TRUE on success; FALSE otherwise CAVEATS: This method should not be called any combo without an SLE HISTORY: rustanl 19-Mar-1991 Created beng 30-Apr-1992 API changes; cch instead of cb ********************************************************************/ BOOL COMBOBOX::SetMaxLength( UINT cchMaxLen ) { ULONG ul = (ULONG)Command( CB_LIMITTEXT, cchMaxLen ); UIASSERT( (LONG)ul != (LONG)CB_ERR ); // called on combo w/o sle return (ul && ((LONG)ul != (LONG)CB_ERR)); } /******************************************************************* NAME: COMBOBOX::IsDropDown SYNOPSIS: Returns TRUE if the combo has the CBS_DROPDOWN style bit set. IsDropDownList and IsSimple are also defined here. RETURNS: Returns TRUE if the appropriate bit is set. NOTES: HISTORY: Johnl 02-May-1991 Created ********************************************************************/ BOOL COMBOBOX::IsDropDown() const { return ( CBS_DROPDOWN == (QueryStyle() & (CBS_DROPDOWN | CBS_SIMPLE | CBS_DROPDOWNLIST) ) ); } BOOL COMBOBOX::IsDropDownList() const { return ( CBS_DROPDOWNLIST == (QueryStyle() & (CBS_DROPDOWN | CBS_SIMPLE | CBS_DROPDOWNLIST) ) ); } BOOL COMBOBOX::IsSimple() const { return ( CBS_SIMPLE == (QueryStyle() & (CBS_DROPDOWN | CBS_SIMPLE | CBS_DROPDOWNLIST) ) ); } /******************************************************************* NAME: COMBOBOX::SaveValue SYNOPSIS: Saves the state of the list control and unselects the current item EXIT: Unselected listbox NOTES: HISTORY: Johnl 25-Apr-1991 Created ********************************************************************/ VOID COMBOBOX::SaveValue( BOOL fInvisible ) { if ( !IsUserEdittable() ) { STRING_LIST_CONTROL::SaveValue( fInvisible ); return; } if ( _nlsSaveValue.QueryError() == NERR_Success ) QueryText( &_nlsSaveValue ); if ( _nlsSaveValue.QueryError() != NERR_Success ) { DBGEOL("COMBOBOX::SaveValue - Error saving combobox string"); _nlsSaveValue = NULL; } if ( IsSimple() && fInvisible ) RemoveSelection(); if ( fInvisible ) ClearText(); } /******************************************************************* NAME: COMBOBOX::RestoreValue SYNOPSIS: Restores COMBOBOX after SaveValue ENTRY: EXIT: NOTES: See CONTROL_VALUE for more details. HISTORY: Johnl 25-Apr-1991 Created ********************************************************************/ VOID COMBOBOX::RestoreValue( BOOL fInvisible ) { if ( !IsUserEdittable() ) { STRING_LIST_CONTROL::RestoreValue( fInvisible ); return; } if ( _nlsSaveValue.QueryError() == NERR_Success ) { if ( fInvisible ) { SetText( _nlsSaveValue ); } // no, don't SelectString(); } } /******************************************************************* NAME: COMBOBOX::QueryEventEffects SYNOPSIS: Returns one of the CVMI_* values. See CONTROL_VALUE for more information. ENTRY: EXIT: HISTORY: Johnl 29-Apr-1991 Created beng 31-Jul-1991 Renamed from QMessageInfo beng 04-Oct-1991 Win32 conversion ********************************************************************/ UINT COMBOBOX::QueryEventEffects( const CONTROL_EVENT & e ) { switch ( e.QueryCode() ) { case CBN_EDITCHANGE: case CBN_SELCHANGE: return CVMI_VALUE_CHANGE; /* If someone clicks on the SLT of the drop down list... */ case CBN_SETFOCUS: // if ( IsDropDownList() ) return CVMI_VALUE_CHANGE | CVMI_RESTORE_ON_INACTIVE; case CBN_DROPDOWN: return CVMI_VALUE_CHANGE | CVMI_RESTORE_ON_INACTIVE; default: break; } return CVMI_NO_VALUE_CHANGE; } /********************************************************** NAME: COMBOBOX::SelectString SYNOPSIS: Selects the string in the combo box. HISTORY: kevinl 19-Nov-1991 Created/stolen from Gregj **********************************************************/ VOID COMBOBOX::SelectString() { #if defined(WIN32) Command( CB_SETEDITSEL, 0, MAKELPARAM(0,-1) ); #else Command( CB_SETEDITSEL, 0, MAKELONG( 0, 0x7fff )); #endif } /********************************************************** NAME: LIST_CONTROL::RemoveSelection SYNOPSIS: Removes the hi-lite bar from the current selection ENTRY: EXIT: NOTES: HISTORY: beng 21-Aug-1991 Removed to .cxx file **********************************************************/ VOID LIST_CONTROL::RemoveSelection() { SelectItem( -1 ); }
29.636588
94
0.489823
[ "object" ]
13626056460b14203bd988fb138c0ead1002377c
1,781
cpp
C++
edu/sqlite/main.cpp
alexeyz041/toolbox
dbb6efff6eb0bcf56fe5b29a0a98d86b5971ddbc
[ "CC0-1.0" ]
1
2022-02-17T22:23:59.000Z
2022-02-17T22:23:59.000Z
edu/sqlite/main.cpp
alexeyz041/toolbox
dbb6efff6eb0bcf56fe5b29a0a98d86b5971ddbc
[ "CC0-1.0" ]
null
null
null
edu/sqlite/main.cpp
alexeyz041/toolbox
dbb6efff6eb0bcf56fe5b29a0a98d86b5971ddbc
[ "CC0-1.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <iostream> #include <fstream> #include <string> #include <vector> #include <sqlite3.h> void save_file(std::string fnm, std::vector<uint8_t> &d) { size_t start = 0; size_t len = d.size(); if(d.size() < 0x26) { printf("%s size too small %ld\n", fnm.c_str(), d.size()); return; } if(d[0x24] == 0xff && d[0x25] == 0xd8) { start = 0x24; len = (d[0x23] << 24) + (d[0x22] << 16) + (d[0x21] << 8) + d[0x20]; if(start + len > d.size()) { printf("invalid len %ld\n", len); len = d.size() - start; } } std::ofstream outfile; outfile.open(fnm, std::ios::out | std::ios::binary); outfile.write((const char *)&d[start], len); } int main() { sqlite3 *db = nullptr; sqlite3_stmt *statement = nullptr; int result = 0; if(sqlite3_open("0.db3", &db) != SQLITE_OK) { printf("Open database failed\n"); return 0; } const char* sql = "SELECT data FROM messages where topic_id = 7 order by timestamp"; if(sqlite3_prepare_v2(db, sql, strlen(sql), &statement, 0) != SQLITE_OK) { printf("Open database failed\n"); return 0; } for(int i=0; ; i++) { result = sqlite3_step(statement); if(result == SQLITE_ROW) { int size = sqlite3_column_bytes(statement, 0); std::vector<uint8_t> data; data.resize(size); memcpy(data.data(), sqlite3_column_blob(statement, 0), size); char fnm[100] = {0}; snprintf(fnm, sizeof(fnm), "images/img_%04d.jpg", i); save_file(fnm, data); } else { break; } } sqlite3_finalize(statement); sqlite3_close(db); return 0; }
24.736111
88
0.544638
[ "vector" ]
13682f8e3c45302bfbfc8ed6f9be0673920fc339
1,896
cpp
C++
BOJ_solve/18260.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
4
2021-01-27T11:51:30.000Z
2021-01-30T17:02:55.000Z
BOJ_solve/18260.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
null
null
null
BOJ_solve/18260.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
5
2021-01-27T11:46:12.000Z
2021-05-06T05:37:47.000Z
#include <bits/stdc++.h> #define x first #define y second #define pb push_back #define all(v) v.begin(),v.end() #pragma gcc optimize("O3") #pragma gcc optimize("Ofast") #pragma gcc optimize("unroll-loops") using namespace std; const int INF = 1e9; const int TMX = 1 << 18; const long long llINF = 1e16; const long long mod = 1e9+7; const long long hashmod = 100003; const int MAXN = 100000; const int MAXM = 1000000; typedef long long ll; typedef long double ld; typedef pair <int,int> pi; typedef pair <ll,ll> pl; typedef vector <int> vec; typedef vector <pi> vecpi; typedef long long ll; int n,Q,co; int in[100005],out[100005]; ll t[400005]; vec v[100005]; map <int,int> t2[400005]; vec la[400005]; void push(int x,int l,int r) { if(la[x].size()) { for(int i : la[x]) { t[x] -= 1LL*t2[x][i]*i; t2[x][i] = r-l+1; t[x] += 1LL*(r-l+1)*i; if(l^r) la[x*2].pb(i), la[x*2+1].pb(i); } la[x].clear(); } } void update(int x,int l,int r,int rl,int rr,int val) { push(x,l,r); if(rl > r||l > rr) return; if(rl <= l&&r <= rr) { la[x].pb(val); push(x,l,r); return; } int mid = (l + r) >> 1; update(x*2,l,mid,rl,rr,val), update(x*2+1,mid+1,r,rl,rr,val); t[x] = t[x*2]+t[x*2+1]; t2[x][val] = t2[x*2][val]+t2[x*2+1][val]; } ll query(int x,int l,int r,int rl,int rr) { push(x,l,r); if(rl > r||l > rr) return 0; if(rl <= l&&r <= rr) return t[x]; int mid = (l + r) >> 1; return query(x*2,l,mid,rl,rr)+query(x*2+1,mid+1,r,rl,rr); } void dfs(int x,int pr) { in[x] = ++co; for(int i : v[x]) { if(i != pr) dfs(i,x); } out[x] = co; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> Q; for(int i = 1;i < n;i++) { int x,y; cin >> x >> y; v[x].pb(y), v[y].pb(x); } dfs(1,-1); while(Q--) { int op,x,y; cin >> op >> x; if(op & 1) { cin >> y; update(1,1,n,in[x],out[x],y); } else cout << query(1,1,n,in[x],out[x]) << '\n'; } }
21.066667
62
0.564346
[ "vector" ]
136bf62e76a372ae30621ffc1bdd59e8a384bd8c
732
cpp
C++
basic/dp/iterator/iterator.cpp
Marveliu/learn-cpp
e1f121fb1d5d7decc5712817a3f4751f43fea1b8
[ "Apache-2.0" ]
null
null
null
basic/dp/iterator/iterator.cpp
Marveliu/learn-cpp
e1f121fb1d5d7decc5712817a3f4751f43fea1b8
[ "Apache-2.0" ]
null
null
null
basic/dp/iterator/iterator.cpp
Marveliu/learn-cpp
e1f121fb1d5d7decc5712817a3f4751f43fea1b8
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "aggregate.h" #include "iterator.h" using namespace std; Iterator::Iterator() //定义抽象迭代器的构造函数 { } Iterator::~Iterator() //定义抽象迭代器的析构函数 { } //定义具体迭代器类的构造函数,首参数表示对哪个聚合类型数据进行迭代,第二个参数表示从哪里开始迭代 ConcreteIterator::ConcreteIterator(Aggregate *ag, int idx) { m_ag = ag; m_idx = idx; } ConcreteIterator::~ConcreteIterator() //定义具体迭代器的析构函数 { } Object ConcreteIterator::current_item() //定义获取聚合数据中当前对象的函数 { return m_ag->get_item(m_idx); } //定义设置聚合数据首位置的函数 void ConcreteIterator::first() { m_idx = 0; } //定义设置聚合数据中下一个位置的函数 void ConcreteIterator::next() { if (m_idx < m_ag->get_size()) m_idx++; } //定义判断是否迭代完毕的函数 bool ConcreteIterator::is_done() { return (m_idx == m_ag->get_size()); }
17.853659
58
0.709016
[ "object" ]
136e4aaab2103d075ddf2b985663ff8e2e2d9621
14,688
cc
C++
utils/kinect_utils.cc
AkillesAILimited/Sensor-Stream-Pipe
9c8671ad5d5e5fdfd43f4d835fa89c36d4de8a6e
[ "MIT" ]
52
2019-12-05T18:00:46.000Z
2022-03-24T04:21:01.000Z
utils/kinect_utils.cc
AkillesAILimited/Sensor-Stream-Pipe
9c8671ad5d5e5fdfd43f4d835fa89c36d4de8a6e
[ "MIT" ]
7
2020-03-24T22:28:08.000Z
2022-02-25T14:28:02.000Z
utils/kinect_utils.cc
AkillesAILimited/Sensor-Stream-Pipe
9c8671ad5d5e5fdfd43f4d835fa89c36d4de8a6e
[ "MIT" ]
10
2020-04-04T00:08:33.000Z
2022-02-25T01:34:12.000Z
/** * \file kinect_utils.cc @brief Utils for Kinect RT integration */ // Created by amourao on 02/09/19. #include "kinect_utils.h" namespace moetsi::ssp { ExtendedAzureConfig BuildKinectConfigFromYAML(YAML::Node config) { ExtendedAzureConfig extended_azure_config; k4a_device_configuration_t device_config = K4A_DEVICE_CONFIG_INIT_DISABLE_ALL; if (!config["streaming_color_format"].IsDefined()) { spdlog::warn("Missing key: \"streaming_color_format\", Using default: " "K4A_IMAGE_FORMAT_COLOR_MJPG"); device_config.color_format = K4A_IMAGE_FORMAT_COLOR_MJPG; } else { std::string streaming_color_format = config["streaming_color_format"].as<std::string>(); if (streaming_color_format == "K4A_IMAGE_FORMAT_COLOR_BGRA32") { device_config.color_format = K4A_IMAGE_FORMAT_COLOR_BGRA32; } else if (streaming_color_format == "K4A_IMAGE_FORMAT_COLOR_MJPG") { device_config.color_format = K4A_IMAGE_FORMAT_COLOR_MJPG; } else if (streaming_color_format == "K4A_IMAGE_FORMAT_COLOR_YUY2" || streaming_color_format == "K4A_IMAGE_FORMAT_COLOR_NV12") { // device_config.color_format = K4A_IMAGE_FORMAT_COLOR_YUY2; spdlog::error( "\"streaming_color_format\" not supported: {}, Supported values are " "K4A_IMAGE_FORMAT_COLOR_BGRA32 and K4A_IMAGE_FORMAT_COLOR_MJPG", streaming_color_format); throw std::invalid_argument("Not supported: \"streaming_color_format\""); } else { spdlog::error( "Invalid value for \"streaming_color_format\": {}, Supported values " "are K4A_IMAGE_FORMAT_COLOR_BGRA32 and K4A_IMAGE_FORMAT_COLOR_MJPG", streaming_color_format); throw std::invalid_argument( "Invalid value for: \"streaming_color_format\""); } } if (!config["streaming_color_resolution"].IsDefined()) { spdlog::warn("Missing key: \"streaming_color_resolution\", Using default: " "K4A_COLOR_RESOLUTION_720P"); device_config.color_resolution = K4A_COLOR_RESOLUTION_720P; } else { std::string streaming_color_resolution = config["streaming_color_resolution"].as<std::string>(); if (streaming_color_resolution == "K4A_COLOR_RESOLUTION_720P") { device_config.color_resolution = K4A_COLOR_RESOLUTION_720P; } else if (streaming_color_resolution == "K4A_COLOR_RESOLUTION_1080P") { device_config.color_resolution = K4A_COLOR_RESOLUTION_1080P; } else if (streaming_color_resolution == "K4A_COLOR_RESOLUTION_1440P") { device_config.color_resolution = K4A_COLOR_RESOLUTION_1440P; } else if (streaming_color_resolution == "K4A_COLOR_RESOLUTION_1536P") { device_config.color_resolution = K4A_COLOR_RESOLUTION_1536P; } else if (streaming_color_resolution == "K4A_COLOR_RESOLUTION_2160P") { device_config.color_resolution = K4A_COLOR_RESOLUTION_2160P; } else if (streaming_color_resolution == "K4A_COLOR_RESOLUTION_3072P") { device_config.color_resolution = K4A_COLOR_RESOLUTION_3072P; } else if (streaming_color_resolution == "K4A_COLOR_RESOLUTION_OFF") { device_config.color_resolution = K4A_COLOR_RESOLUTION_OFF; } else { spdlog::error("Invalid value for \"streaming_color_resolution\": {}, " "Supported values are K4A_COLOR_RESOLUTION_OFF and " "K4A_COLOR_RESOLUTION_720P, K4A_COLOR_RESOLUTION_1080P, " "K4A_COLOR_RESOLUTION_1440P, K4A_COLOR_RESOLUTION_1536P, " "K4A_COLOR_RESOLUTION_2160P and K4A_COLOR_RESOLUTION_3072P", streaming_color_resolution); throw std::invalid_argument( "Invalid value for: \"streaming_color_resolution\""); } } if (!config["streaming_depth_mode"].IsDefined()) { spdlog::warn("Missing key: \"streaming_depth_mode\", Using default: " "K4A_DEPTH_MODE_NFOV_UNBINNED"); device_config.depth_mode = K4A_DEPTH_MODE_NFOV_UNBINNED; } else { std::string streaming_depth_mode = config["streaming_depth_mode"].as<std::string>(); if (streaming_depth_mode == "K4A_DEPTH_MODE_PASSIVE_IR") { device_config.depth_mode = K4A_DEPTH_MODE_PASSIVE_IR; } else if (streaming_depth_mode == "K4A_DEPTH_MODE_WFOV_2X2BINNED") { device_config.depth_mode = K4A_DEPTH_MODE_WFOV_2X2BINNED; } else if (streaming_depth_mode == "K4A_DEPTH_MODE_WFOV_2X2BINNED") { device_config.depth_mode = K4A_DEPTH_MODE_WFOV_2X2BINNED; } else if (streaming_depth_mode == "K4A_DEPTH_MODE_NFOV_UNBINNED") { device_config.depth_mode = K4A_DEPTH_MODE_NFOV_UNBINNED; } else if (streaming_depth_mode == "K4A_DEPTH_MODE_NFOV_2X2BINNED") { device_config.depth_mode = K4A_DEPTH_MODE_NFOV_2X2BINNED; } else if (streaming_depth_mode == "K4A_DEPTH_MODE_OFF") { device_config.depth_mode = K4A_DEPTH_MODE_OFF; } else { spdlog::error( "Invalid value for \"streaming_depth_mode\": {}, " "Supported values are K4A_DEPTH_MODE_OFF and " "K4A_DEPTH_MODE_NFOV_2X2BINNED, K4A_DEPTH_MODE_NFOV_UNBINNED, " "K4A_DEPTH_MODE_WFOV_2X2BINNED, K4A_DEPTH_MODE_WFOV_UNBINNED, " "K4A_DEPTH_MODE_PASSIVE_IR", streaming_depth_mode); throw std::invalid_argument( "Invalid value for: \"streaming_depth_mode\""); } } if (!config["streaming_rate"].IsDefined()) { spdlog::warn("Missing key: \"streaming_rate\", Using default: " "K4A_FRAMES_PER_SECOND_30"); device_config.camera_fps = K4A_FRAMES_PER_SECOND_30; } else { std::string fps_str = config["streaming_rate"].as<std::string>(); if (fps_str == "K4A_FRAMES_PER_SECOND_5") { device_config.camera_fps = K4A_FRAMES_PER_SECOND_5; } else if (fps_str == "K4A_FRAMES_PER_SECOND_15") { device_config.camera_fps = K4A_FRAMES_PER_SECOND_15; } else if (fps_str == "K4A_FRAMES_PER_SECOND_30") { device_config.camera_fps = K4A_FRAMES_PER_SECOND_30; } else { spdlog::error("Invalid value for \"streaming_rate\": {}, " "Supported values are K4A_FRAMES_PER_SECOND_5, " "K4A_FRAMES_PER_SECOND_15, " "K4A_FRAMES_PER_SECOND_30", fps_str); throw std::invalid_argument("Invalid value for: \"streaming_rate\""); } } if (!config["wired_sync_mode"].IsDefined()) { spdlog::warn("Missing key: \"wired_sync_mode\", Using default: " "K4A_WIRED_SYNC_MODE_STANDALONE"); device_config.wired_sync_mode = K4A_WIRED_SYNC_MODE_STANDALONE; } else { std::string wired_sync_mode = config["wired_sync_mode"].as<std::string>(); if (wired_sync_mode == "K4A_WIRED_SYNC_MODE_MASTER") { device_config.wired_sync_mode = K4A_WIRED_SYNC_MODE_MASTER; } else if (wired_sync_mode == "K4A_WIRED_SYNC_MODE_SUBORDINATE") { device_config.wired_sync_mode = K4A_WIRED_SYNC_MODE_SUBORDINATE; } else if (wired_sync_mode == "K4A_WIRED_SYNC_MODE_STANDALONE") { device_config.wired_sync_mode = K4A_WIRED_SYNC_MODE_STANDALONE; } else { spdlog::error( "Invalid value for \"streaming_rate\": {}, " "Supported values are K4A_WIRED_SYNC_MODE_MASTER, " "K4A_WIRED_SYNC_MODE_SUBORDINATE and K4A_WIRED_SYNC_MODE_STANDALONE", wired_sync_mode); throw std::invalid_argument("Invalid value for: \"wired_sync_mode\""); } } device_config.depth_delay_off_color_usec = 0; if (config["depth_delay_off_color_usec"].IsDefined()) { device_config.depth_delay_off_color_usec = config["depth_delay_off_color_usec"].as<int>(); } else { spdlog::warn("Using default depth_delay_off_color_usec = 0"); } device_config.subordinate_delay_off_master_usec = 0; if (config["subordinate_delay_off_master_usec"].IsDefined()) { device_config.subordinate_delay_off_master_usec = config["subordinate_delay_off_master_usec"].as<int>(); } else { spdlog::warn("Using default subordinate_delay_off_master_usec = 0"); } int absolute_exposure_value = 0; if (config["absoluteExposureValue"].IsDefined()) { absolute_exposure_value = config["absoluteExposureValue"].as<int>(); } else { ; spdlog::warn("Using default absoluteExposureValue = 0"); } bool stream_color_video = true; if (!config["stream_color_video"].IsDefined()) { spdlog::warn("Missing key: \"stream_color_video\", Using default: " "true"); } else { stream_color_video = config["stream_color_video"].as<bool>(); if (!stream_color_video) { device_config.color_resolution = K4A_COLOR_RESOLUTION_OFF; } } bool stream_depth_video = true; if (!config["stream_depth_video"].IsDefined()) { spdlog::warn("Missing key: \"stream_depth_video\", Using default: " "true"); } else { stream_depth_video = config["stream_depth_video"].as<bool>(); if (!stream_depth_video) { device_config.depth_mode = K4A_DEPTH_MODE_PASSIVE_IR; } } bool stream_ir_video = false; if (!config["stream_ir_video"].IsDefined()) { spdlog::warn("Missing key: \"stream_ir_video\", Using default: " "false"); } else { stream_ir_video = config["stream_ir_video"].as<bool>(); } if (!stream_ir_video && !stream_depth_video) { device_config.depth_mode = K4A_DEPTH_MODE_OFF; } extended_azure_config.device_config = device_config; extended_azure_config.stream_color = stream_color_video; extended_azure_config.stream_depth = stream_depth_video; extended_azure_config.stream_ir = stream_ir_video; extended_azure_config.absolute_exposure_value = absolute_exposure_value; return extended_azure_config; } void FrameStructToK4A(std::vector<FrameStruct> &fs, k4a::capture &sensor_capture, std::unordered_map<std::string, std::shared_ptr<IDecoder>> &decoders) { for (auto &f : fs) { std::string decoder_id = f.stream_id + std::to_string(f.sensor_id); if (decoders.find(decoder_id) == decoders.end()) { CodecParamsStruct data = f.codec_data; // if (data.type == 0) { if (data.type == CodecParamsType::CodecParamsTypeAv) { std::shared_ptr<LibAvDecoder> fd = std::shared_ptr<LibAvDecoder>(new LibAvDecoder()); fd->Init(getParams(f)); decoders[decoder_id] = fd; // } else if (data.type == 1) { } else if (data.type == CodecParamsType::CodecParamsTypeNvPipe) { #ifdef SSP_WITH_NVPIPE_SUPPORT std::shared_ptr<NvDecoder> fd = std::shared_ptr<NvDecoder>(new NvDecoder()); fd->Init(data.data); decoders[decoder_id] = fd; #else spdlog::error("SSP compiled without \"nvenc\" reader support. Set to " "SSP_WITH_NVPIPE_SUPPORT=ON when configuring with cmake"); exit(1); #endif //} else if (data.type == 2) { } else if (data.type == CodecParamsType::CodecParamsTypeZDepth) { std::shared_ptr<ZDepthDecoder> fd = std::shared_ptr<ZDepthDecoder>(new ZDepthDecoder()); fd->Init(data.data); decoders[decoder_id] = fd; } } cv::Mat img; // if (f.frame_data_type == 0) { if (f.frame_data_type == FrameDataType::FrameDataTypeImageFrame) { img = cv::imdecode(f.frame, CV_LOAD_IMAGE_UNCHANGED); // } else if (f.frame_data_type == 2) { } else if (f.frame_data_type == FrameDataType::FrameDataTypeRawRGBA) { int rows, cols; memcpy(&cols, &f.frame[0], sizeof(int)); memcpy(&rows, &f.frame[4], sizeof(int)); img = cv::Mat(rows, cols, CV_8UC4, (void *)&f.frame[8], cv::Mat::AUTO_STEP); // } else if (f.frame_data_type == 3) { } else if (f.frame_data_type == FrameDataType::FrameDataTypeGRAY16LE) { int rows, cols; memcpy(&cols, &f.frame[0], sizeof(int)); memcpy(&rows, &f.frame[4], sizeof(int)); img = cv::Mat(rows, cols, CV_16UC1, (void *)&f.frame[8], cv::Mat::AUTO_STEP); // } else if (f.frame_data_type == 1) { } else if (f.frame_data_type == FrameDataType::FrameDataTypeLibavPackets) { std::shared_ptr<IDecoder> decoder; std::string decoder_id = f.stream_id + std::to_string(f.sensor_id); if (decoders.find(decoder_id) == decoders.end()) { CodecParamsStruct data = f.codec_data; // if (data.type == 0) { if (data.type == CodecParamsType::CodecParamsTypeAv) { std::shared_ptr<LibAvDecoder> fd = std::shared_ptr<LibAvDecoder>(new LibAvDecoder()); fd->Init(getParams(f)); decoders[decoder_id] = fd; // } else if (data.type == 1) { } else if (data.type == CodecParamsType::CodecParamsTypeNvPipe) { #ifdef SSP_WITH_NVPIPE_SUPPORT std::shared_ptr<NvDecoder> fd = std::shared_ptr<NvDecoder>(new NvDecoder()); fd->Init(data.data); decoders[decoder_id] = fd; #else spdlog::error("SSP compiled without \"nvenc\" reader support. Set to " "SSP_WITH_NVPIPE_SUPPORT=ON when configuring with cmake"); exit(1); #endif // } else if (data.type == 2) { } else if (data.type == CodecParamsType::CodecParamsTypeZDepth) { std::shared_ptr<ZDepthDecoder> fd = std::shared_ptr<ZDepthDecoder>(new ZDepthDecoder()); fd->Init(data.data); decoders[decoder_id] = fd; } } decoder = decoders[decoder_id]; img = decoder->Decode(f); f.frame.clear(); } // if (f.frame_type == 0) { if (f.frame_type == FrameType::FrameTypeColor) { if (img.channels() == 3) cv::cvtColor(img, img, cv::COLOR_BGR2BGRA); k4a::image color = k4a::image::create(K4A_IMAGE_FORMAT_COLOR_BGRA32, img.cols, img.rows, 4 * img.cols); memcpy(color.get_buffer(), img.datastart, img.total() * img.elemSize()); sensor_capture.set_color_image(color); // } else if (f.frame_type == 1) { } else if (f.frame_type == FrameType::FrameTypeDepth) { k4a::image depth = k4a::image::create(K4A_IMAGE_FORMAT_DEPTH16, img.cols, img.rows, 2 * img.cols); memcpy(depth.get_buffer(), img.datastart, img.total() * img.elemSize()); sensor_capture.set_depth_image(depth); // } else if (f.frame_type == 2) { } else if (f.frame_type == FrameType::FrameTypeIR) { k4a::image ir = k4a::image::create(K4A_IMAGE_FORMAT_IR16, img.cols, img.rows, 2 * img.cols); memcpy(ir.get_buffer(), img.datastart, img.total() * img.elemSize()); sensor_capture.set_ir_image(ir); } } } } // namespace moetsi::ssp
43.844776
98
0.671092
[ "vector" ]
1371d78613eadc14812859b49e18cd1e48c68db5
1,272
cpp
C++
atcoder/arc076e.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
atcoder/arc076e.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
atcoder/arc076e.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // after some drawing, note only both end on board matter. // transform board to a straight line, then each seg must not intersect(can contain). stack maintain. void solve() { int R,C; cin >> R >> C; auto on_board = [&](int x, int y){ return x==0 || x==R || y==0 || y==C; }; auto to_line = [&](int x, int y){ if (y==0) return x; if (x==R) return R+y; if (y==C) return R+C+R-x; assert(x==0); return R+C+R+C-y; }; vector<pair<int, int>> a; int n; cin >> n; for (int _ = 0; _ < n; _++) { int x,y,u,v; cin >> x >> y >> u >> v; if (on_board(x,y) && on_board(u,v)) { int i = to_line(x,y); int j = to_line(u,v); if (i>j) swap(i,j); a.emplace_back(i, _); a.emplace_back(j, _); } } sort(a.begin(), a.end()); vector<int> stk; for (auto& p: a) { if (stk.empty() || stk.back()!=p.second) { stk.emplace_back(p.second); } else { stk.pop_back(); } } cout << (stk.empty()?"YES":"NO"); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); cout << endl; }
24.461538
101
0.466195
[ "vector", "transform" ]
1377e1dc516024908602eeb26bb8976643f389ab
6,443
hpp
C++
include/SSVOpenHexagon/Core/MenuGame.hpp
MultHub/SSVOpenHexagon
bb27b4cd382fd1d2ba042c8da1685e629b57d503
[ "AFL-3.0" ]
null
null
null
include/SSVOpenHexagon/Core/MenuGame.hpp
MultHub/SSVOpenHexagon
bb27b4cd382fd1d2ba042c8da1685e629b57d503
[ "AFL-3.0" ]
null
null
null
include/SSVOpenHexagon/Core/MenuGame.hpp
MultHub/SSVOpenHexagon
bb27b4cd382fd1d2ba042c8da1685e629b57d503
[ "AFL-3.0" ]
null
null
null
// Copyright (c) 2013-2015 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 #ifndef HG_MENUGAME #define HG_MENUGAME #include "SSVOpenHexagon/Global/Common.hpp" #include "SSVOpenHexagon/Data/LevelData.hpp" #include "SSVOpenHexagon/Data/StyleData.hpp" #include "SSVOpenHexagon/Global/Assets.hpp" #include "SSVOpenHexagon/Global/Config.hpp" namespace hg { enum class States { ETUser, ETPass, ETEmail, ETLPNew, ETFriend, SLogging, SMain, SLPSelect, MWlcm, MOpts }; class HexagonGame; class MenuGame { private: HGAssets& assets; sf::Font& imagine = assets.get<sf::Font>( "imagine.ttf"); // G++ bug (cannot initialize with curly braces) float wheelProgress{0.f}; float w, h; std::string lrUser, lrPass, lrEmail; HexagonGame& hexagonGame; ssvs::GameState game; ssvs::GameWindow& window; sses::Manager manager; ssvs::Camera backgroundCamera{ window, {ssvs::zeroVec2f, {Config::getSizeX() * Config::getZoomFactor(), Config::getSizeY() * Config::getZoomFactor()}}}; ssvs::Camera overlayCamera{ window, {{Config::getWidth() / 2.f, Config::getHeight() * Config::getZoomFactor() / 2.f}, {Config::getWidth() * Config::getZoomFactor(), Config::getHeight() * Config::getZoomFactor()}}}; States state{States::MWlcm}; ssvms::Menu optionsMenu, welcomeMenu; std::string scoresMessage; float exitTimer{0}, currentCreditsId{0}; bool mustTakeScreenshot{false}; std::string currentLeaderboard, enteredStr, leaderboardString, friendsString; std::vector<char> enteredChars; std::vector<std::string> creditsIds{"creditsBar2.png", "creditsBar2b.png", "creditsBar2c.png", "creditsBar2d.png", "creditsBar2d.png", "creditsBar2d.png"}; sf::Sprite titleBar{assets.get<sf::Texture>("titleBar.png")}, creditsBar1{assets.get<sf::Texture>("creditsBar1.png")}, creditsBar2{assets.get<sf::Texture>("creditsBar2.png")}, bottomBar{assets.get<sf::Texture>("bottomBar.png")}; std::vector<std::string> levelDataIds; std::vector<float> diffMults; int currentIndex{0}, packIdx{0}, profileIdx{0}, diffMultIdx{0}; const LevelData* levelData; LevelStatus levelStatus; StyleData styleData; sf::Text txtVersion{"", imagine, 40}, txtProf{"", imagine, 21}, txtLName{"", imagine, 65}, txtLDesc{"", imagine, 32}, txtLAuth{"", imagine, 20}, txtLMus{"", imagine, 20}, txtFriends{"", imagine, 21}, txtPacks{"", imagine, 14}; void leftAction(); void rightAction(); void upAction(); void downAction(); void okAction(); float touchDelay{0.f}; void refreshCamera(); void initAssets(); void initMenus(); void initInput(); void update(FT mFT); void draw(); void drawLevelSelection(); void drawEnteringText(); void drawProfileSelection(); void drawOptions(); void drawWelcome(); void drawMenu(const ssvms::Menu& mMenu); inline void render(sf::Drawable& mDrawable) { window.draw(mDrawable); } inline sf::Text& renderTextImpl( const std::string& mStr, sf::Text& mText, const Vec2f& mPosition) { if(mText.getString() != mStr) mText.setString(mStr); mText.setPosition(mPosition); render(mText); return mText; } inline sf::Text& renderTextImpl(const std::string& mStr, sf::Text& mText, const Vec2f& mPosition, unsigned int mSize) { auto originalSize(mText.getCharacterSize()); mText.setCharacterSize(mSize); renderTextImpl(mStr, mText, mPosition); mText.setCharacterSize(originalSize); return mText; } inline const sf::Color& getTextColor() const { return (state != States::SMain || Config::getBlackAndWhite()) ? sf::Color::White : styleData.getMainColor(); } inline sf::Text& renderText( const std::string& mStr, sf::Text& mText, const Vec2f& mPos) { mText.setColor(getTextColor()); return renderTextImpl(mStr, mText, mPos); } inline sf::Text& renderText(const std::string& mStr, sf::Text& mText, const Vec2f& mPos, unsigned int mSize) { mText.setColor(getTextColor()); return renderTextImpl(mStr, mText, mPos, mSize); } inline sf::Text& renderText(const std::string& mStr, sf::Text& mText, const Vec2f& mPos, const sf::Color& mColor) { mText.setColor(mColor); return renderTextImpl(mStr, mText, mPos); } inline sf::Text& renderText(const std::string& mStr, sf::Text& mText, const Vec2f& mPos, const sf::Color& mColor, unsigned int mSize) { mText.setColor(mColor); return renderTextImpl(mStr, mText, mPos, mSize); } void setIndex(int mIdx); void updateLeaderboard(); void updateFriends(); void initLua(Lua::LuaContext& mLua); inline bool isEnteringText() { return state == States::ETUser || state == States::ETPass || state == States::ETEmail || state == States::ETLPNew || state == States::ETFriend; } inline ssvms::Menu* getCurrentMenu() { switch(state) { case States::MWlcm: return &welcomeMenu; case States::MOpts: return &optionsMenu; default: return nullptr; } } inline bool isInMenu() { return getCurrentMenu() != nullptr; } public: MenuGame(HGAssets& mAssets, HexagonGame& mHexagonGame, ssvs::GameWindow& mGameWindow); void init(); inline ssvs::GameState& getGame() { return game; } }; } #endif
34.827027
79
0.566661
[ "render", "vector" ]
137b55090a338cbde5bc7f18f248324a9a03b2f8
8,093
hpp
C++
tiny_dnn/xtensor/xassign.hpp
onearrow/tiny_cnn_learn
121de29b4ed039bd03ab19640f54dd447773c361
[ "BSD-3-Clause" ]
3
2016-12-04T20:44:51.000Z
2020-12-07T22:28:48.000Z
tiny_dnn/xtensor/xassign.hpp
hainu2008/tiny-dnn
df2f5d023d99614be1f11caf21831f49bd8f5929
[ "BSD-3-Clause" ]
9
2016-07-28T20:51:13.000Z
2017-06-21T10:13:06.000Z
tiny_dnn/xtensor/xassign.hpp
hainu2008/tiny-dnn
df2f5d023d99614be1f11caf21831f49bd8f5929
[ "BSD-3-Clause" ]
5
2016-07-28T03:35:56.000Z
2020-02-14T20:56:54.000Z
/*************************************************************************** * Copyright (c) 2016, Johan Mabille, Sylvain Corlay and Wolf Vollprecht * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XASSIGN_HPP #define XASSIGN_HPP #include "xiterator.hpp" #include "xtensor_forward.hpp" #include <algorithm> namespace xt { template <class E> class xexpression; /******************** * Assign functions * ********************/ template <class E1, class E2> void assign_data(xexpression<E1>& e1, const xexpression<E2>& e2, bool trivial); template <class E1, class E2> bool reshape(xexpression<E1>& e1, const xexpression<E2>& e2); template <class E1, class E2> void assign_xexpression(xexpression<E1>& e1, const xexpression<E2>& e2); template <class E1, class E2> void computed_assign(xexpression<E1>& e1, const xexpression<E2>& e2); template <class E1, class E2, class F> void scalar_computed_assign(xexpression<E1>& e1, const E2& e2, F&& f); template <class E1, class E2> void assert_compatible_shape(const xexpression<E1>& e1, const xexpression<E2>& e2); /***************** * data_assigner * *****************/ template <class E1, class E2, layout_type L> class data_assigner { public: using lhs_iterator = typename E1::stepper; using rhs_iterator = typename E2::const_stepper; using shape_type = typename E1::shape_type; using index_type = xindex_type_t<shape_type>; using size_type = typename lhs_iterator::size_type; data_assigner(E1& e1, const E2& e2); void run(); void step(size_type i); void reset(size_type i); void to_end(layout_type); private: E1& m_e1; lhs_iterator m_lhs; rhs_iterator m_rhs; rhs_iterator m_rhs_end; index_type m_index; }; /******************** * trivial_assigner * ********************/ template <bool index_assign> struct trivial_assigner { template <class E1, class E2> static void run(E1& e1, const E2& e2); }; /*********************************** * Assign functions implementation * ***********************************/ namespace detail { template <class E1, class E2> inline bool is_trivial_broadcast(const E1& e1, const E2& e2) { return e2.is_trivial_broadcast(e1.strides()); } template <class D, class E2, class... SL> inline bool is_trivial_broadcast(const xview<D, SL...>&, const E2&) { return false; } } template <class E1, class E2> inline void assign_data(xexpression<E1>& e1, const xexpression<E2>& e2, bool trivial) { E1& de1 = e1.derived_cast(); const E2& de2 = e2.derived_cast(); bool trivial_broadcast = trivial && detail::is_trivial_broadcast(de1, de2); if (trivial_broadcast) { constexpr bool contiguous_layout = E1::contiguous_layout && E2::contiguous_layout; trivial_assigner<contiguous_layout>::run(de1, de2); } else { data_assigner<E1, E2, default_assignable_layout(E1::static_layout)> assigner(de1, de2); assigner.run(); } } template <class E1, class E2> inline bool reshape(xexpression<E1>& e1, const xexpression<E2>& e2) { using shape_type = typename E1::shape_type; using size_type = typename E1::size_type; const E2& de2 = e2.derived_cast(); size_type size = de2.dimension(); shape_type shape = make_sequence<shape_type>(size, size_type(1)); bool trivial_broadcast = de2.broadcast_shape(shape); e1.derived_cast().reshape(shape); return trivial_broadcast; } template <class E1, class E2> inline void assign_xexpression(xexpression<E1>& e1, const xexpression<E2>& e2) { bool trivial_broadcast = reshape(e1, e2); assign_data(e1, e2, trivial_broadcast); } template <class E1, class E2> inline void computed_assign(xexpression<E1>& e1, const xexpression<E2>& e2) { using shape_type = typename E1::shape_type; using size_type = typename E1::size_type; E1& de1 = e1.derived_cast(); const E2& de2 = e2.derived_cast(); size_type dim = de2.dimension(); shape_type shape = make_sequence<shape_type>(dim, size_type(1)); bool trivial_broadcast = de2.broadcast_shape(shape); if (dim > de1.dimension() || shape > de1.shape()) { typename E1::temporary_type tmp(shape); assign_data(tmp, e2, trivial_broadcast); de1.assign_temporary(std::move(tmp)); } else { assign_data(e1, e2, trivial_broadcast); } } template <class E1, class E2, class F> inline void scalar_computed_assign(xexpression<E1>& e1, const E2& e2, F&& f) { E1& d = e1.derived_cast(); std::transform(d.cbegin(), d.cend(), d.begin(), [e2, &f](const auto& v) { return f(v, e2); }); } template <class E1, class E2> inline void assert_compatible_shape(const xexpression<E1>& e1, const xexpression<E2>& e2) { using shape_type = typename E1::shape_type; using size_type = typename E1::size_type; const E1& de1 = e1.derived_cast(); const E2& de2 = e2.derived_cast(); size_type size = de2.dimension(); shape_type shape = make_sequence<shape_type>(size, size_type(1)); de2.broadcast_shape(shape); if (shape.size() > de1.shape().size() || shape > de1.shape()) { throw broadcast_error(shape, de1.shape()); } } /******************************** * data_assigner implementation * ********************************/ template <class E1, class E2, layout_type L> inline data_assigner<E1, E2, L>::data_assigner(E1& e1, const E2& e2) : m_e1(e1), m_lhs(e1.stepper_begin(e1.shape())), m_rhs(e2.stepper_begin(e1.shape())), m_rhs_end(e2.stepper_end(e1.shape(), L)), m_index(make_sequence<index_type>(e1.shape().size(), size_type(0))) { } template <class E1, class E2, layout_type L> inline void data_assigner<E1, E2, L>::run() { while (m_rhs != m_rhs_end) { *m_lhs = *m_rhs; stepper_tools<L>::increment_stepper(*this, m_index, m_e1.shape()); } } template <class E1, class E2, layout_type L> inline void data_assigner<E1, E2, L>::step(size_type i) { m_lhs.step(i); m_rhs.step(i); } template <class E1, class E2, layout_type L> inline void data_assigner<E1, E2, L>::reset(size_type i) { m_lhs.reset(i); m_rhs.reset(i); } template <class E1, class E2, layout_type L> inline void data_assigner<E1, E2, L>::to_end(layout_type l) { m_lhs.to_end(l); m_rhs.to_end(l); } /*********************************** * trivial_assigner implementation * ***********************************/ template <bool index_assign> template <class E1, class E2> inline void trivial_assigner<index_assign>::run(E1& e1, const E2& e2) { using size_type = typename E1::size_type; size_type size = e1.size(); for (size_type i = 0; i < size; ++i) { e1.data_element(i) = e2.data_element(i); } } template <> template <class E1, class E2> inline void trivial_assigner<false>::run(E1& e1, const E2& e2) { std::copy(e2.cbegin(), e2.cend(), e1.begin()); } } #endif
30.655303
99
0.557395
[ "shape", "transform" ]
137fb0a4cf3f823d8f1a04fef1f3bdad1ed4febf
34,293
cc
C++
src/xf.cc
cangyu/Fluent3DMeshReader
f5d8a02b586736e385acce7a50286cc2ad9c7816
[ "MIT" ]
1
2020-09-08T06:49:12.000Z
2020-09-08T06:49:12.000Z
src/xf.cc
cangyu/Fluent3DMeshReader
f5d8a02b586736e385acce7a50286cc2ad9c7816
[ "MIT" ]
null
null
null
src/xf.cc
cangyu/Fluent3DMeshReader
f5d8a02b586736e385acce7a50286cc2ad9c7816
[ "MIT" ]
null
null
null
#include "xf.h" /// Convert a boundary condition string literal to unified form within the scope of this code. /// Outcome will be composed of LOWER case letters and '-' only! static std::string formalize(const std::string& s) { std::string ret(s); std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower); for (auto& e : ret) if (e == '_') e = '-'; return ret; } static void eat(std::istream& in, char c) { char tmp = 0; do { in >> tmp; } while (tmp != c); } static void skip_white(std::istream& in) { char tmp = 0; do { in >> tmp; } while (tmp == ' ' || tmp == '\t' || tmp == '\n'); if (!in.eof()) in.unget(); } namespace XF { bool BC::isValidIdx(int x) { static const std::set<int> candidate_set{ INTERIOR, WALL, PRESSURE_INLET, PRESSURE_OUTLET, SYMMETRY, PERIODIC_SHADOW, PRESSURE_FAR_FIELD, VELOCITY_INLET, PERIODIC, FAN, MASS_FLOW_INLET, INTERFACE, PARENT, OUTFLOW, AXIS }; return candidate_set.find(x) != candidate_set.end(); } bool BC::isValidStr(const std::string& x) { static const std::set<std::string> candidate_set{ "interior", "wall", "pressure-inlet", "inlet-vent", "intake-fan", "pressure-outlet", "exhaust-fan", "outlet-vent", "symmetry", "periodic-shadow", "pressure-far-field", "velocity-inlet", "periodic", "fan", "porous-jump", "radiator", "mass-flow-inlet", "interface", "parent", "outflow", "axis" }; return candidate_set.find(formalize(x)) != candidate_set.end(); } const std::string& BC::idx2str(int x) { static const std::map<int, std::string> mapping_set{ std::pair<int, std::string>(INTERIOR, "interior"), std::pair<int, std::string>(WALL, "wall"), std::pair<int, std::string>(PRESSURE_INLET, "pressure-inlet"), std::pair<int, std::string>(PRESSURE_OUTLET, "pressure-outlet"), std::pair<int, std::string>(SYMMETRY, "symmetry"), std::pair<int, std::string>(PERIODIC_SHADOW, "periodic-shadow"), std::pair<int, std::string>(PRESSURE_FAR_FIELD, "pressure-far-field"), std::pair<int, std::string>(VELOCITY_INLET, "velocity-inlet"), std::pair<int, std::string>(PERIODIC, "periodic"), std::pair<int, std::string>(FAN, "fan"), std::pair<int, std::string>(MASS_FLOW_INLET, "mass-flow-inlet"), std::pair<int, std::string>(INTERFACE, "interface"), std::pair<int, std::string>(PARENT, "parent"), std::pair<int, std::string>(OUTFLOW, "outflow"), std::pair<int, std::string>(AXIS, "axis") }; auto it = mapping_set.find(x); if (it == mapping_set.end()) throw invalid_bc_idx(x); else return it->second; } int BC::str2idx(const std::string& x) { static const std::map<std::string, int> mapping_set{ std::pair<std::string, int>("interior", INTERIOR), std::pair<std::string, int>("wall", WALL), std::pair<std::string, int>("pressure-inlet", PRESSURE_INLET), std::pair<std::string, int>("inlet-vent", INLET_VENT), std::pair<std::string, int>("intake-fan", INTAKE_FAN), std::pair<std::string, int>("pressure-outlet", PRESSURE_OUTLET), std::pair<std::string, int>("exhaust-fan", EXHAUST_FAN), std::pair<std::string, int>("outlet-vent", OUTLET_VENT), std::pair<std::string, int>("symmetry", SYMMETRY), std::pair<std::string, int>("periodic-shadow", PERIODIC_SHADOW), std::pair<std::string, int>("pressure-far-field", PRESSURE_FAR_FIELD), std::pair<std::string, int>("velocity-inlet", VELOCITY_INLET), std::pair<std::string, int>("periodic", PERIODIC), std::pair<std::string, int>("fan", FAN), std::pair<std::string, int>("porous-jump", POROUS_JUMP), std::pair<std::string, int>("radiator", RADIATOR), std::pair<std::string, int>("mass-flow-inlet", MASS_FLOW_INLET), std::pair<std::string, int>("interface", INTERFACE), std::pair<std::string, int>("parent", PARENT), std::pair<std::string, int>("outflow", OUTFLOW), std::pair<std::string, int>("axis", AXIS) }; auto it = mapping_set.find(formalize(x)); if (it == mapping_set.end()) throw invalid_bc_str(x); else return it->second; } RANGE::RANGE(int id, size_t zone, size_t first, size_t last) : SECTION(id), m_zone(zone), m_first(first), m_last(last) { if (first > last) throw std::invalid_argument("Invalid range in constructor."); } RANGE::RANGE(const RANGE& rhs) : SECTION(rhs.identity()), m_zone(rhs.zone()), m_first(rhs.first_index()), m_last(rhs.last_index()) { if (first_index() > last_index()) throw std::invalid_argument("Invalid range in copy-constructor."); } bool NODE::isValidTypeIdx(int x) { return x == VIRTUAL || x == ANY || x == BOUNDARY; } bool NODE::isValidTypeStr(const std::string& x) { static const std::set<std::string> candidate_set{ "virtual", "any", "boundary" }; return candidate_set.find(formalize(x)) != candidate_set.end(); } const std::string& NODE::idx2str(int x) { static const std::map<int, std::string> mapping_set{ std::pair<int, std::string>(VIRTUAL, "virtual"), std::pair<int, std::string>(ANY, "any"), std::pair<int, std::string>(BOUNDARY, "boundary") }; auto it = mapping_set.find(x); if (it == mapping_set.end()) throw invalid_node_type_idx(x); else return it->second; } int NODE::str2idx(const std::string& x) { static const std::map<std::string, int> mapping_set{ std::pair<std::string, int>("virtual", VIRTUAL), std::pair<std::string, int>("any", ANY), std::pair<std::string, int>("boundary", BOUNDARY), }; auto it = mapping_set.find(formalize(x)); if (it == mapping_set.end()) throw invalid_node_type_str(x); else return it->second; } void NODE::repr(std::ostream& out) { out << "(" << std::dec << identity(); out << " (" << std::hex << zone() << " " << first_index() << " " << last_index() << " "; out << std::dec << type() << " " << ND() << ")(" << std::endl; out.precision(12); const size_t N = num(); for (size_t i = 0; i < N; ++i) { const auto& node = at(i); for (int k = 0; k < m_dim; ++k) out << " " << node.at(k); out << std::endl; } out << "))" << std::endl; } bool CELL::isValidTypeIdx(int x) { static const std::set<int> candidate_set{ DEAD, FLUID, SOLID }; return candidate_set.find(x) != candidate_set.end(); } bool CELL::isValidTypeStr(const std::string& x) { static const std::set<std::string> candidate_set{ "dead", "fluid", "solid" }; return candidate_set.find(formalize(x)) != candidate_set.end(); } const std::string& CELL::idx2str_type(int x) { static const std::map<int, std::string> mapping_set{ std::pair<int, std::string>(FLUID, "fluid"), std::pair<int, std::string>(SOLID, "solid"), std::pair<int, std::string>(DEAD, "dead") }; auto it = mapping_set.find(x); if (it == mapping_set.end()) throw invalid_cell_type_idx(x); else return it->second; } int CELL::str2idx_type(const std::string& x) { static const std::map<std::string, int> mapping_set{ std::pair<std::string, int>("fluid", FLUID), std::pair<std::string, int>("solid", SOLID), std::pair<std::string, int>("dead", DEAD), }; auto it = mapping_set.find(x); if (it == mapping_set.end()) throw invalid_cell_type_str(x); else return it->second; } bool CELL::isValidElemIdx(int x) { static const std::set<int> candidate_set{ MIXED, TRIANGULAR, TETRAHEDRAL, QUADRILATERAL, HEXAHEDRAL, PYRAMID, WEDGE, POLYHEDRAL }; return candidate_set.find(x) != candidate_set.end(); } bool CELL::isValidElemStr(const std::string& x) { static const std::set<std::string> candidate_set{ "mixed", "triangular", "tetrahedral", "quadrilateral", "hexahedral", "pyramid", "wedge", "prism", "polyhedral" }; return candidate_set.find(formalize(x)) != candidate_set.end(); } const std::string& CELL::idx2str_elem(int x) { static const std::map<int, std::string> mapping_set{ std::pair<int, std::string>(MIXED, "mixed"), std::pair<int, std::string>(TRIANGULAR, "triangular"), std::pair<int, std::string>(TETRAHEDRAL, "tetrahedral"), std::pair<int, std::string>(QUADRILATERAL, "quadrilateral"), std::pair<int, std::string>(HEXAHEDRAL, "hexahedral"), std::pair<int, std::string>(PYRAMID, "pyramid"), std::pair<int, std::string>(WEDGE, "wedge"), std::pair<int, std::string>(POLYHEDRAL, "polyhedral") }; auto it = mapping_set.find(x); if (it == mapping_set.end()) throw invalid_elem_type_idx(x); else return it->second; } int CELL::str2idx_elem(const std::string& x) { static const std::map<std::string, int> mapping_set{ std::pair<std::string, int>("mixed", MIXED), std::pair<std::string, int>("triangular", TRIANGULAR), std::pair<std::string, int>("tri", TRIANGULAR), std::pair<std::string, int>("tetrahedral", TETRAHEDRAL), std::pair<std::string, int>("tet", TETRAHEDRAL), std::pair<std::string, int>("quadrilateral", QUADRILATERAL), std::pair<std::string, int>("quad", QUADRILATERAL), std::pair<std::string, int>("hexahedral", HEXAHEDRAL), std::pair<std::string, int>("hex", HEXAHEDRAL), std::pair<std::string, int>("pyramid", PYRAMID), std::pair<std::string, int>("wedge", WEDGE), std::pair<std::string, int>("prism", WEDGE), std::pair<std::string, int>("polyhedral", POLYHEDRAL) }; auto it = mapping_set.find(x); if (it == mapping_set.end()) throw invalid_elem_type_str(x); else return it->second; } void CELL::repr(std::ostream& out) { static const size_t NumPerLine = 40; out << "(" << std::dec << identity() << " ("; out << std::hex; out << zone() << " " << first_index() << " " << last_index() << " "; out << m_type << " " << m_elem << ")"; if (m_elem != CELL::MIXED) out << ")" << std::endl; else { out << "("; const size_t N = num(); for (size_t i = 0; i < N; ++i) { if (i % NumPerLine == 0) out << std::endl; out << " " << at(i); } out << std::endl << "))" << std::endl; } } bool FACE::isValidIdx(int x) { static const std::set<int> candidate_set{ MIXED, LINEAR, TRIANGULAR, QUADRILATERAL, POLYGONAL }; return candidate_set.find(x) != candidate_set.end(); } bool FACE::isValidStr(const std::string& x) { static const std::set<std::string> candidate_set{ "mixed", "linear", "triangular", "quadrilateral", "polygonal" }; return candidate_set.find(x) != candidate_set.end(); } const std::string& FACE::idx2str(int x) { static const std::map<int, std::string> mapping_set{ std::pair<int, std::string>(MIXED, "mixed"), std::pair<int, std::string>(LINEAR, "linear"), std::pair<int, std::string>(TRIANGULAR, "triangular"), std::pair<int, std::string>(QUADRILATERAL, "quadrilateral"), std::pair<int, std::string>(POLYGONAL, "polygonal") }; auto it = mapping_set.find(x); if (it == mapping_set.end()) throw invalid_face_type_idx(x); else return it->second; } int FACE::str2idx(const std::string& x) { static const std::map<std::string, int> mapping_set{ std::pair<std::string, int>("mixed", MIXED), std::pair<std::string, int>("linear", LINEAR), std::pair<std::string, int>("line", LINEAR), std::pair<std::string, int>("triangular", TRIANGULAR), std::pair<std::string, int>("tri", TRIANGULAR), std::pair<std::string, int>("quadrilateral", QUADRILATERAL), std::pair<std::string, int>("quad", QUADRILATERAL), std::pair<std::string, int>("polygonal", POLYGONAL) }; auto it = mapping_set.find(x); if (it == mapping_set.end()) throw invalid_face_type_str(x); else return it->second; } void FACE::repr(std::ostream& out) { out << "(" << std::dec << identity() << " ("; out << std::hex; out << zone() << " " << first_index() << " " << last_index() << " "; out << bc_type() << " " << face_type() << ")(" << std::endl; const size_t N = num(); if (m_face == MIXED) { for (size_t i = 0; i < N; ++i) { const auto& loc_connect = at(i); out << " " << loc_connect.n.size(); for (auto e : loc_connect.n) out << " " << e; out << " " << loc_connect.c[0] << " " << loc_connect.c[1] << std::endl; } } else { for (size_t i = 0; i < N; ++i) { const auto& loc_connect = at(i); for (auto e : loc_connect.n) out << " " << e; out << " " << loc_connect.c[0] << " " << loc_connect.c[1] << std::endl; } } out << "))" << std::endl; } bool ZONE::isValidIdx(int x) { const bool ret = ZONE::DEGASSING <= x && x <= ZONE::WRAPPER; return ret; } bool ZONE::isValidStr(const std::string& x) { static const std::set<std::string> candidate_set{ "degassing", "exhaust-fan", "fan", "fluid", "geometry", "inlet-vent", "intake-fan", "interface", "interior", "internal", "mass-flow-inlet", "outflow", "outlet-vent", "parent-face", "porous-jump", "pressure-far-field", "pressure-inlet", "pressure-outlet", "radiator", "solid", "symmetry", "velocity-inlet", "wall", "wrapper" }; return candidate_set.find(formalize(x)) != candidate_set.end(); } const std::string& ZONE::idx2str(int x) { static const std::map<int, std::string> mapping_set{ std::pair<int, std::string>(DEGASSING, "degassing"), std::pair<int, std::string>(EXHAUST_FAN, "exhaust-fan"), std::pair<int, std::string>(FAN, "fan"), std::pair<int, std::string>(FLUID, "fluid"), std::pair<int, std::string>(GEOMETRY, "geometry"), std::pair<int, std::string>(INLET_VENT, "inlet-vent"), std::pair<int, std::string>(INTAKE_FAN, "intake-fan"), std::pair<int, std::string>(INTERFACE, "interface"), std::pair<int, std::string>(INTERIOR, "interior"), std::pair<int, std::string>(INTERNAL, "internal"), std::pair<int, std::string>(MASS_FLOW_INLET, "mass-flow-inlet"), std::pair<int, std::string>(OUTFLOW, "outflow"), std::pair<int, std::string>(OUTLET_VENT, "outlet-vent"), std::pair<int, std::string>(PARENT_FACE, "parent-face"), std::pair<int, std::string>(POROUS_JUMP, "porous-jump"), std::pair<int, std::string>(PRESSURE_FAR_FIELD, "pressure-far-field"), std::pair<int, std::string>(PRESSURE_INLET, "pressure-inlet"), std::pair<int, std::string>(PRESSURE_OUTLET, "pressure-outlet"), std::pair<int, std::string>(RADIATOR, "radiator"), std::pair<int, std::string>(SOLID, "solid"), std::pair<int, std::string>(SYMMETRY, "symmetry"), std::pair<int, std::string>(VELOCITY_INLET, "velocity-inlet"), std::pair<int, std::string>(WALL, "wall"), std::pair<int, std::string>(WRAPPER, "wrapper"), }; auto it = mapping_set.find(x); if (it == mapping_set.end()) throw invalid_zone_type_idx(x); else return it->second; } int ZONE::str2idx(const std::string& x) { static const std::map<std::string, int> mapping_set{ std::pair<std::string, int>("degassing", DEGASSING), std::pair<std::string, int>("exhaust-fan", EXHAUST_FAN), std::pair<std::string, int>("fan", FAN), std::pair<std::string, int>("fluid", FLUID), std::pair<std::string, int>("geometry", GEOMETRY), std::pair<std::string, int>("inlet-vent", INLET_VENT), std::pair<std::string, int>("intake-fan", INTAKE_FAN), std::pair<std::string, int>("interface", INTERFACE), std::pair<std::string, int>("interior", INTERIOR), std::pair<std::string, int>("internal", INTERNAL), std::pair<std::string, int>("mass-flow-inlet", MASS_FLOW_INLET), std::pair<std::string, int>("outflow", OUTFLOW), std::pair<std::string, int>("outlet-vent", OUTLET_VENT), std::pair<std::string, int>("parent-face", PARENT_FACE), std::pair<std::string, int>("porous-jump", POROUS_JUMP), std::pair<std::string, int>("pressure-far-field", PRESSURE_FAR_FIELD), std::pair<std::string, int>("pressure-inlet", PRESSURE_INLET), std::pair<std::string, int>("pressure-outlet", PRESSURE_OUTLET), std::pair<std::string, int>("radiator", RADIATOR), std::pair<std::string, int>("solid", SOLID), std::pair<std::string, int>("symmetry", SYMMETRY), std::pair<std::string, int>("velocity-inlet", VELOCITY_INLET), std::pair<std::string, int>("wall", WALL), std::pair<std::string, int>("wrapper", WRAPPER) }; auto it = mapping_set.find(x); if (it == mapping_set.end()) throw invalid_zone_type_str(x); else return it->second; } ZONE::ZONE(int zone, const std::string& zt, const std::string& name, int id) : SECTION(SECTION::ZONE), m_zoneID(zone), m_zoneType(formalize(zt)), m_zoneName(name), m_domainID(id) { if (!isValidStr(zt)) throw invalid_zone_type_str(zt); } void MESH::readFromFile(const std::string& src, std::ostream& f_out) { // Open grid file std::ifstream fin(src); if (fin.fail()) throw std::runtime_error("Failed to open input mesh file: \"" + src + "\"."); // Clear existing records if any. clear_entry(); // Clear existing size if any. reset_counting(); // Read contents while (!fin.eof()) { skip_white(fin); eat(fin, '('); int ti = -1; fin >> std::dec >> ti; if (ti == SECTION::COMMENT) { eat(fin, '\"'); std::string ts; char tc; while ((tc = fin.get()) != '\"') ts.push_back(tc); eat(fin, ')'); add_entry(new COMMENT(ts)); skip_white(fin); } else if (ti == SECTION::HEADER) { eat(fin, '\"'); std::string ts; char tc; while ((tc = fin.get()) != '\"') ts.push_back(tc); eat(fin, ')'); add_entry(new HEADER(ts)); skip_white(fin); } else if (ti == SECTION::DIMENSION) { int nd = 0; fin >> std::dec >> nd; eat(fin, ')'); add_entry(new DIMENSION(nd)); skip_white(fin); m_dim = nd; m_is3D = (nd == 3); } else if (ti == SECTION::NODE) { eat(fin, '('); int zone; fin >> std::hex >> zone; if (zone == 0) { // If zone-id is 0, indicating total number of nodes in the mesh. int tmp; fin >> std::hex; fin >> tmp; if (tmp != 1) throw std::runtime_error("Invalid \"first-index\" in NODE declaration!"); fin >> m_totalNodeNum; f_out << "Total number of nodes: " << m_totalNodeNum << std::endl; fin >> tmp; if (tmp != 0) throw std::runtime_error("Invalid \"type\" in NODE declaration!"); char ndc = fin.get(); if (ndc != ')') { fin >> tmp; eat(fin, ')'); } eat(fin, ')'); } else { // If zone-id is positive, it indicates the zone to which the nodes belong. int first, last, tp, nd; fin >> std::hex; fin >> first >> last; fin >> tp >> nd; auto e = new NODE(zone, first, last, tp, nd); eat(fin, ')'); eat(fin, '('); f_out << "Reading " << e->num() << " nodes in zone " << zone << " (from " << first << " to " << last << "), whose type is \"" << NODE::idx2str(tp) << "\" ... "; if (nd != dimension()) throw std::runtime_error("Inconsistent with previous DIMENSION declaration!"); if (nd == 3) { for (int i = first; i <= last; ++i) { auto& ce = e->at(i - first); fin >> ce.x() >> ce.y() >> ce.z(); } } else { for (int i = first; i <= last; ++i) { auto& ce = e->at(i - first); fin >> ce.x() >> ce.y(); } } eat(fin, ')'); eat(fin, ')'); f_out << "Done!" << std::endl; add_entry(e); } skip_white(fin); } else if (ti == SECTION::CELL) { eat(fin, '('); int zone; fin >> std::hex >> zone; if (zone == 0) { // If zone-id is 0, indicating total number of cells in the mesh. int tmp; fin >> std::hex; fin >> tmp; if (tmp != 1) throw std::runtime_error("Invalid \"first-index\" in CELL declaration!"); fin >> m_totalCellNum; f_out << "Total number of cells: " << m_totalCellNum << std::endl; fin >> tmp; if (tmp != 0) throw std::runtime_error("Invalid \"type\" in CELL declaration!"); char ndc = fin.get(); if (ndc != ')') { fin >> tmp; eat(fin, ')'); } eat(fin, ')'); } else { // If zone-id is positive, it indicates the zone to which the cells belong. int first, last, tp, elem; fin >> std::hex; fin >> first >> last; fin >> tp >> elem; auto e = new CELL(zone, first, last, tp, elem); eat(fin, ')'); if (elem == 0) { f_out << "Reading " << e->num() << " mixed cells in zone " << zone << " (from " << first << " to " << last << ") ... "; eat(fin, '('); for (int i = first; i <= last; ++i) { fin >> elem; if (CELL::isValidElemIdx(elem)) e->at(i - first) = elem; else throw std::runtime_error("Invalid CELL-ELEM-TYPE: \"" + std::to_string(elem) + "\""); } eat(fin, ')'); f_out << "Done!" << std::endl; } else f_out << e->num() << " " << CELL::idx2str_elem(elem) << " in zone " << zone << " (from " << first << " to " << last << ")" << std::endl; eat(fin, ')'); add_entry(e); } skip_white(fin); } else if (ti == SECTION::FACE) { eat(fin, '('); int zone; fin >> std::hex >> zone; if (zone == 0) { // If zone-id is 0, indicating total number of faces in the mesh. int tmp; fin >> tmp; if (tmp != 1) throw std::runtime_error("Invalid \"first-index\" in FACE declaration!"); fin >> m_totalFaceNum; f_out << "Total number of faces: " << m_totalFaceNum << std::endl; fin >> tmp; char ndc = fin.get(); if (ndc != ')') { fin >> tmp; eat(fin, ')'); } eat(fin, ')'); } else { // If zone-id is positive, it indicates a regular face section and will be // followed by a body containing information about the grid connectivity. size_t first, last; int bc, face; fin >> first >> last; fin >> bc >> face; auto e = new FACE(zone, first, last, bc, face); eat(fin, ')'); eat(fin, '('); f_out << "Reading " << e->num() << " " << FACE::idx2str(face) << " faces in zone " << zone << " (from " << first << " to " << last << "), whose B.C. is \"" << BC::idx2str(bc) << "\" ... "; std::vector<size_t> tmp_n; size_t tmp_c[2]; if (face == FACE::MIXED) { int x = -1; for (size_t i = first; i <= last; ++i) { // Read connectivity record fin >> x; if (x < 2) throw std::invalid_argument("Invalid node num in the mixed face."); tmp_n.resize(x); for (int j = 0; j < x; ++j) fin >> tmp_n[j]; fin >> tmp_c[0] >> tmp_c[1]; // Store current connectivity info e->at(i - first).update_included_node(tmp_n); e->at(i - first).update_adjacent_cell(tmp_c[0], tmp_c[1]); } } else { tmp_n.resize(face); for (size_t i = first; i <= last; ++i) { // Read connectivity record for (int j = 0; j < face; ++j) fin >> tmp_n[j]; fin >> tmp_c[0] >> tmp_c[1]; // Store current connectivity info e->at(i - first).update_included_node(tmp_n); e->at(i - first).update_adjacent_cell(tmp_c[0], tmp_c[1]); } } eat(fin, ')'); eat(fin, ')'); f_out << "Done!" << std::endl; add_entry(e); } skip_white(fin); } else if (ti == SECTION::ZONE || ti == SECTION::ZONE_MESHING) { eat(fin, '('); int zone; fin >> std::dec >> zone; std::string ztp; fin >> ztp; skip_white(fin); std::string z_name; char t0; while ((t0 = fin.get()) != ')') z_name.push_back(t0); eat(fin, '('); eat(fin, ')'); eat(fin, ')'); auto e = new ZONE(zone, ztp, z_name); add_entry(e); skip_white(fin); f_out << "ZONE " << e->zone() << ", named " << R"(")" << e->name() << R"(", )" << "is " << R"(")" << e->type() << R"(")" << std::endl; ++m_totalZoneNum; } else throw std::runtime_error("Unsupported section index: " + std::to_string(ti)); } // Close grid file fin.close(); f_out << "Done!" << std::endl; } void MESH::writeToFile(const std::string& dst) const { if (nCell() == 0) throw std::runtime_error("Invalid num of cells."); if (nFace() == 0) throw std::runtime_error("Invalid num of faces."); if (nNode() == 0) throw std::runtime_error("Invalid num of nodes."); if (m_content.empty()) throw std::runtime_error("Invalid num of contents."); /// Open grid file std::ofstream f_out(dst); if (f_out.fail()) throw std::runtime_error("Failed to open output grid file: " + dst); /// Write until dimension declaration size_t i = 0; while (true) { m_content[i]->repr(f_out); bool flag = dynamic_cast<DIMENSION*>(m_content[i]) != nullptr; ++i; if (flag) break; } /// Declaration of NODE, FACE, CELL f_out << "(" << std::dec << SECTION::NODE << " ("; f_out << std::hex << 0 << " " << 1 << " " << m_totalNodeNum << " "; f_out << std::dec << 0 << " " << (m_is3D ? 3 : 2) << "))" << std::endl; f_out << "(" << std::dec << SECTION::CELL << " ("; f_out << std::hex << 0 << " " << 1 << " " << m_totalCellNum << " "; f_out << std::dec << 0 << " " << 0 << "))" << std::endl; f_out << "(" << std::dec << SECTION::FACE << " ("; f_out << std::hex << 0 << " " << 1 << " " << m_totalFaceNum << " "; f_out << std::dec << 0 << " " << 0 << "))" << std::endl; /// Contents for (; i < m_content.size(); ++i) m_content[i]->repr(f_out); /// Close grid file f_out.close(); } }
36.953664
209
0.430671
[ "mesh", "geometry", "vector", "transform", "solid" ]
1380bcdf8c83d429647bdcf40b3a40164623822e
21,410
cpp
C++
src/team.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
12
2015-03-04T15:07:00.000Z
2019-09-13T16:31:06.000Z
src/team.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
null
null
null
src/team.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
5
2017-04-22T08:16:48.000Z
2020-07-12T03:35:16.000Z
/* $Id: team.cpp 49142 2011-04-09 20:25:18Z mordante $ */ /* Copyright (C) 2003 - 2011 by David White <dave@whitevine.net> Part of the Battle for Wesnoth Project http://www.wesnoth.org/ 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. See the COPYING file for more details. */ /** * @file * Team-management, allies, setup at start of scenario. */ #include "team.hpp" #include "ai/manager.hpp" #include "foreach.hpp" #include "game_events.hpp" #include "gamestatus.hpp" #include "resources.hpp" #include "game_preferences.hpp" #include "whiteboard/side_actions.hpp" static lg::log_domain log_engine("engine"); #define DBG_NG LOG_STREAM(debug, log_engine) #define LOG_NG LOG_STREAM(info, log_engine) #define WRN_NG LOG_STREAM(warn, log_engine) static lg::log_domain log_engine_enemies("engine/enemies"); #define DBG_NGE LOG_STREAM(debug, log_engine_enemies) #define LOG_NGE LOG_STREAM(info, log_engine_enemies) #define WRN_NGE LOG_STREAM(warn, log_engine_enemies) static std::vector<team> *&teams = resources::teams; //static member initialization const int team::default_team_gold = 100; const std::vector<team>& teams_manager::get_teams() { assert(teams); return *teams; } team::team_info::team_info() : name(), gold(0), start_gold(0), gold_add(false), income(0), income_per_village(0), minimum_recruit_price(0), recall_cost(0), can_recruit(), team_name(), user_team_name(), save_id(), current_player(), countdown_time(), action_bonus_count(0), flag(), flag_icon(), description(), scroll_to_leader(true), objectives(), objectives_changed(false), controller(), share_maps(false), share_view(false), disallow_observers(false), allow_player(false), no_leader(true), hidden(true), music(), color(), side(0), persistent(false) { } void team::team_info::read(const config &cfg) { name = cfg["name"].str(); gold = cfg["gold"]; income = cfg["income"]; team_name = cfg["team_name"].str(); user_team_name = cfg["user_team_name"]; save_id = cfg["save_id"].str(); current_player = cfg["current_player"].str(); countdown_time = cfg["countdown_time"].str(); action_bonus_count = cfg["action_bonus_count"]; flag = cfg["flag"].str(); flag_icon = cfg["flag_icon"].str(); description = cfg["id"].str(); scroll_to_leader = cfg["scroll_to_leader"].to_bool(true); objectives = cfg["objectives"]; objectives_changed = cfg["objectives_changed"].to_bool(); disallow_observers = cfg["disallow_observers"].to_bool(); allow_player = cfg["allow_player"].to_bool(true); no_leader = cfg["no_leader"].to_bool(); hidden = cfg["hidden"].to_bool(); music = cfg["music"].str(); side = cfg["side"].to_int(1); if(cfg.has_attribute("color")) { color = cfg["color"].str(); } else { color = cfg["side"].str(); } // If arel starting new scenario overide settings from [ai] tags if (!user_team_name.translatable()) user_team_name = t_string::from_serialized(user_team_name); if(cfg.has_attribute("ai_config")) { ai::manager::add_ai_for_side_from_file(side, cfg["ai_config"], true); } else { ai::manager::add_ai_for_side_from_config(side, cfg, true); } std::vector<std::string> recruits = utils::split(cfg["recruit"]); for(std::vector<std::string>::const_iterator i = recruits.begin(); i != recruits.end(); ++i) { can_recruit.insert(*i); } // at the start of a scenario "start_gold" is not set, we need to take the // value from the gold setting (or fall back to the gold default) if (!cfg["start_gold"].empty()) start_gold = cfg["start_gold"]; else if (!cfg["gold"].empty()) start_gold = gold; else start_gold = default_team_gold; if(team_name.empty()) { team_name = cfg["side"].str(); } if(save_id.empty()) { save_id = description; } if (current_player.empty()) { current_player = save_id; } const std::string temp_rgb_str = cfg["team_rgb"]; std::map<std::string, color_range>::iterator global_rgb = game_config::team_rgb_range.find(cfg["side"]); if(!temp_rgb_str.empty()){ std::vector<Uint32> temp_rgb = string2rgb(temp_rgb_str); team_color_range_[side] = color_range(temp_rgb); }else if(global_rgb != game_config::team_rgb_range.end()){ team_color_range_[side] = global_rgb->second; } income_per_village = cfg["village_gold"].to_int(game_config::village_income); recall_cost = cfg["recall_cost"].to_int(game_config::recall_cost); std::string control = cfg["controller"]; //by default, persistence of a team is set depending on the controller persistent = true; if (control == "human") controller = HUMAN; else if (control == "human_ai") controller = HUMAN_AI; else if (control == "network") controller = NETWORK; else if (control == "network_ai") controller = NETWORK_AI; else if (control == "null") { disallow_observers = cfg["disallow_observers"].to_bool(true); controller = EMPTY; persistent = false; } else { controller = AI; persistent = false; } //override persistence flag if it is explicitly defined in the config persistent = cfg["persistent"].to_bool(persistent); //======================================================== //END OF MESSY CODE // Share_view and share_maps can't both be enabled, // so share_view overrides share_maps. share_view = cfg["share_view"].to_bool(); share_maps = !share_view && cfg["share_maps"].to_bool(true); LOG_NG << "team_info::team_info(...): team_name: " << team_name << ", share_maps: " << share_maps << ", share_view: " << share_view << ".\n"; } char const *team::team_info::controller_string() const { switch(controller) { case AI: return "ai"; case HUMAN: return "human"; case HUMAN_AI: return "human_ai"; case NETWORK: return "network"; case NETWORK_AI: return "network_ai"; case EMPTY: return "null"; default: assert(false); return NULL; } } void team::team_info::write(config& cfg) const { cfg["gold"] = gold; cfg["start_gold"] = start_gold; cfg["gold_add"] = gold_add; cfg["income"] = income; cfg["name"] = name; cfg["team_name"] = team_name; cfg["user_team_name"] = user_team_name; cfg["save_id"] = save_id; cfg["current_player"] = current_player; cfg["flag"] = flag; cfg["flag_icon"] = flag_icon; cfg["id"] = description; cfg["objectives"] = objectives; cfg["objectives_changed"] = objectives_changed; cfg["countdown_time"]= countdown_time; cfg["action_bonus_count"]= action_bonus_count; cfg["village_gold"] = income_per_village; cfg["recall_cost"] = recall_cost; cfg["disallow_observers"] = disallow_observers; cfg["allow_player"] = allow_player; cfg["no_leader"] = no_leader; cfg["hidden"] = hidden; cfg["scroll_to_leader"] = scroll_to_leader; cfg["controller"] = controller_string(); std::stringstream can_recruit_str; for(std::set<std::string>::const_iterator cr = can_recruit.begin(); cr != can_recruit.end(); ++cr) { if(cr != can_recruit.begin()) can_recruit_str << ","; can_recruit_str << *cr; } cfg["recruit"] = can_recruit_str.str(); cfg["share_maps"] = share_maps; cfg["share_view"] = share_view; if(music.empty() == false) cfg["music"] = music; cfg["color"] = color; ///@deprecated 1.9.2 'colour' also written in team cfg["colour"] = color; cfg["persistent"] = persistent; cfg.add_child("ai",ai::manager::to_config(side)); } void team::merge_shroud_map_data(const std::string& shroud_data) { shroud_.merge(shroud_data); } team::team() : savegame_config(), gold_(0), villages_(), shroud_(), fog_(), auto_shroud_updates_(true), info_(), countdown_time_(0), action_bonus_count_(0), recall_list_(), enemies_(), seen_(), ally_shroud_(), ally_fog_(), planned_actions_() { } team::~team() { } void team::build(const config &cfg, const gamemap& map, int gold) { gold_ = gold; info_.read(cfg); fog_.set_enabled(cfg["fog"].to_bool()); shroud_.set_enabled(cfg["shroud"].to_bool()); shroud_.read(cfg["shroud_data"]); LOG_NG << "team::team(...): team_name: " << info_.team_name << ", shroud: " << uses_shroud() << ", fog: " << uses_fog() << ".\n"; // To ensure some minimum starting gold, // gold is the maximum of 'gold' and what is given in the config file gold_ = std::max(gold, info_.gold); if (gold_ != info_.gold) info_.start_gold = gold; // Old code was doing: // info_.start_gold = str_cast(gold) + " (" + info_.start_gold + ")"; // Was it correct? // Load in the villages the side controls at the start foreach (const config &v, cfg.child_range("village")) { map_location loc(v, resources::state_of_game); if (map.is_village(loc)) { villages_.insert(loc); } else { WRN_NG << "[side] " << name() << " [village] points to a non-village location " << loc << "\n"; } } countdown_time_ = cfg["countdown_time"]; action_bonus_count_ = cfg["action_bonus_count"]; planned_actions_.reset(new wb::side_actions()); planned_actions_->set_team_index(info_.side - 1); } void team::write(config& cfg) const { info_.write(cfg); cfg["shroud"] = uses_shroud(); cfg["fog"] = uses_fog(); cfg["gold"] = gold_; // Write village locations for(std::set<map_location>::const_iterator t = villages_.begin(); t != villages_.end(); ++t) { t->write(cfg.add_child("village")); } cfg["shroud_data"] = shroud_.write(); cfg["countdown_time"] = countdown_time_; cfg["action_bonus_count"] = action_bonus_count_; } bool team::get_village(const map_location& loc) { villages_.insert(loc); return game_events::fire("capture",loc); } void team::lose_village(const map_location& loc) { if(owns_village(loc)) { villages_.erase(villages_.find(loc)); } } void team::set_recruits(const std::set<std::string>& recruits) { info_.can_recruit = recruits; info_.minimum_recruit_price = 0; ai::manager::raise_recruit_list_changed(); } void team::add_recruit(const std::string &recruit) { info_.can_recruit.insert(recruit); info_.minimum_recruit_price = 0; ai::manager::raise_recruit_list_changed(); } int team::minimum_recruit_price() const { if(info_.minimum_recruit_price){ return info_.minimum_recruit_price; }else{ int min = 20; foreach(std::string recruit, info_.can_recruit){ const unit_type *ut = unit_types.find(recruit); if(!ut) continue; else{ if(ut->cost() < min) min = ut->cost(); } } info_.minimum_recruit_price = min; } return info_.minimum_recruit_price; } bool team::calculate_enemies(size_t index) const { if(teams == NULL || index >= teams->size()) { return false; } while(enemies_.size() <= index) { enemies_.push_back(calculate_is_enemy(enemies_.size())); } return enemies_.back(); } bool team::calculate_is_enemy(size_t index) const { // We're not enemies of ourselves if(&(*teams)[index] == this) { return false; } // We are friends with anyone who we share a teamname with std::vector<std::string> our_teams = utils::split(info_.team_name), their_teams = utils::split((*teams)[index].info_.team_name); LOG_NGE << "team " << info_.side << " calculates if it has enemy in team "<<index+1 << "; our team_name ["<<info_.team_name<<"], their team_name is ["<<(*teams)[index].info_.team_name<<"]"<< std::endl; for(std::vector<std::string>::const_iterator t = our_teams.begin(); t != our_teams.end(); ++t) { if(std::find(their_teams.begin(), their_teams.end(), *t) != their_teams.end()) { LOG_NGE << "team " << info_.side << " found same team name [" << *t << "] in team "<< index+1 << std::endl; return false; } else { LOG_NGE << "team " << info_.side << " not found same team name [" << *t << "] in team "<< index+1 << std::endl; } } LOG_NGE << "team " << info_.side << " has enemy in team " << index+1 << std::endl; return true; } void team::set_share_maps( bool share_maps ){ // Share_view and share_maps can't both be enabled, // so share_view overrides share_maps. // If you want to change them, be sure to change share_view FIRST info_.share_maps = !info_.share_view && share_maps; } void team::set_share_view( bool share_view ){ info_.share_view = share_view; } void team::change_controller(const std::string& controller) { team::team_info::CONTROLLER cid; if (controller == "human") cid = team::team_info::HUMAN; else if (controller == "human_ai") cid = team::team_info::HUMAN_AI; else if (controller == "network") cid = team::team_info::NETWORK; else if (controller == "network_ai") cid = team::team_info::NETWORK_AI; else if (controller == "null") cid = team::team_info::EMPTY; else cid = team::team_info::AI; info_.controller = cid; } void team::change_team(const std::string &name, const t_string &user_name) { info_.team_name = name; if (!user_name.empty()) { info_.user_team_name = user_name; } else { info_.user_team_name = name; } clear_caches(); } void team::clear_caches(){ // Reset the cache of allies for all teams if(teams != NULL) { for(std::vector<team>::const_iterator i = teams->begin(); i != teams->end(); ++i) { i->enemies_.clear(); i->ally_shroud_.clear(); i->ally_fog_.clear(); } } } void team::set_objectives(const t_string& new_objectives, bool silently) { info_.objectives = new_objectives; if(!silently) info_.objectives_changed = true; } bool team::shrouded(const map_location& loc) const { if(!teams) return shroud_.value(loc.x+1,loc.y+1); return shroud_.shared_value(ally_shroud(*teams),loc.x+1,loc.y+1); } bool team::fogged(const map_location& loc) const { if(shrouded(loc)) return true; if(!teams) return fog_.value(loc.x+1,loc.y+1); return fog_.shared_value(ally_fog(*teams),loc.x+1,loc.y+1); } const std::vector<const team::shroud_map*>& team::ally_shroud(const std::vector<team>& teams) const { if(ally_shroud_.empty()) { for(size_t i = 0; i < teams.size(); ++i) { if(!is_enemy(i + 1) && (&(teams[i]) == this || teams[i].share_view() || teams[i].share_maps())) { ally_shroud_.push_back(&(teams[i].shroud_)); } } } return ally_shroud_; } const std::vector<const team::shroud_map*>& team::ally_fog(const std::vector<team>& teams) const { if(ally_fog_.empty()) { for(size_t i = 0; i < teams.size(); ++i) { if(!is_enemy(i + 1) && (&(teams[i]) == this || teams[i].share_view())) { ally_fog_.push_back(&(teams[i].fog_)); } } } return ally_fog_; } bool team::knows_about_team(size_t index, bool is_multiplayer) const { const team& t = (*teams)[index]; // We know about our own team if(this == &t) return true; // If we aren't using shroud or fog, then we know about everyone if(!uses_shroud() && !uses_fog()) return true; // We don't know about enemies if(is_enemy(index+1)) return false; // We know our allies in multiplayer if (is_multiplayer) return true; // We know about allies we're sharing maps with if(share_maps() && t.uses_shroud()) return true; // We know about allies we're sharing view with if(share_view() && (t.uses_fog() || t.uses_shroud())) return true; return false; } bool team::copy_ally_shroud() { if(!teams || !share_maps()) return false; return shroud_.copy_from(ally_shroud(*teams)); } int team::nteams() { if(teams == NULL) { return 0; } else { return teams->size(); } } bool is_observer() { if(teams == NULL) { return true; } foreach (const team &t, *teams) { if (t.is_human()) return false; } return true; } void validate_side(int side) { if(teams == NULL) { return; } if(side < 1 || side > int(teams->size())) { throw game::game_error("invalid side(" + str_cast(side) + ") found in unit definition"); } } bool team::shroud_map::clear(int x, int y) { if(enabled_ == false || x < 0 || y < 0) return false; if(x >= static_cast<int>(data_.size())) data_.resize(x+1); if(y >= static_cast<int>(data_[x].size())) data_[x].resize(y+1); if(data_[x][y] == false) { data_[x][y] = true; return true; } else { return false; } } void team::shroud_map::place(int x, int y) { if(enabled_ == false || x < 0 || y < 0) return; if (x >= static_cast<int>(data_.size())) { DBG_NG << "Couldn't place shroud on invalid x coordinate: (" << x << ", " << y << ") - max x: " << data_.size() - 1 << "\n"; } else if (y >= static_cast<int>(data_[x].size())) { DBG_NG << "Couldn't place shroud on invalid y coordinate: (" << x << ", " << y << ") - max y: " << data_[x].size() - 1 << "\n"; } else { data_[x][y] = false; } } void team::shroud_map::reset() { if(enabled_ == false) return; for(std::vector<std::vector<bool> >::iterator i = data_.begin(); i != data_.end(); ++i) { std::fill(i->begin(),i->end(),false); } } bool team::shroud_map::value(int x, int y) const { if(enabled_ == false || x < 0 || y < 0) return false; if(x >= static_cast<int>(data_.size())) return true; if(y >= static_cast<int>(data_[x].size())) return true; if(data_[x][y]) return false; else return true; } bool team::shroud_map::shared_value(const std::vector<const shroud_map*>& maps, int x, int y) const { if(enabled_ == false || x < 0 || y < 0) return false; for(std::vector<const shroud_map*>::const_iterator i = maps.begin(); i != maps.end(); ++i) { if((*i)->enabled_ == true && (*i)->value(x,y) == false) return false; } return true; } std::string team::shroud_map::write() const { std::stringstream shroud_str; for(std::vector<std::vector<bool> >::const_iterator sh = data_.begin(); sh != data_.end(); ++sh) { shroud_str << '|'; for(std::vector<bool>::const_iterator i = sh->begin(); i != sh->end(); ++i) { shroud_str << (*i ? '1' : '0'); } shroud_str << '\n'; } return shroud_str.str(); } void team::shroud_map::read(const std::string& str) { data_.clear(); for(std::string::const_iterator sh = str.begin(); sh != str.end(); ++sh) { if(*sh == '|') data_.resize(data_.size()+1); if(data_.empty() == false) { if(*sh == '1') data_.back().push_back(true); else if(*sh == '0') data_.back().push_back(false); } } } void team::shroud_map::merge(const std::string& str) { int x=0, y=0; for(std::string::const_iterator sh = str.begin(); sh != str.end(); ++sh) { if(*sh == '|' && sh != str.begin()) { y=0; x++; } else if(*sh == '1') { clear(x,y); y++; } else if(*sh == '0') { y++; } } } bool team::shroud_map::copy_from(const std::vector<const shroud_map*>& maps) { if(enabled_ == false) return false; bool cleared = false; for(std::vector<const shroud_map*>::const_iterator i = maps.begin(); i != maps.end(); ++i) { if((*i)->enabled_ == false) continue; const std::vector<std::vector<bool> >& v = (*i)->data_; for(size_t x = 0; x != v.size(); ++x) { for(size_t y = 0; y != v[x].size(); ++y) { if(v[x][y]) { cleared |= clear(x,y); } } } } return cleared; } std::map<int, color_range> team::team_color_range_; const color_range team::get_side_color_range(int side){ std::string index = get_side_color_index(side); std::map<std::string, color_range>::iterator gp=game_config::team_rgb_range.find(index); if(gp != game_config::team_rgb_range.end()){ return(gp->second); } return(color_range(0x00FF0000,0x00FFFFFF,0x00000000,0x00FF0000)); } SDL_Color team::get_side_color(int side) { return int_to_color(get_side_color_range(side).mid()); } SDL_Color team::get_minimap_color(int side) { // Note: use mid() instead of rep() unless // high contrast is needed over a map or minimap! return int_to_color(get_side_color_range(side).rep()); } std::string team::get_side_color_index(int side) { size_t index = size_t(side-1); if(teams != NULL && index < teams->size()) { const std::string side_map = (*teams)[index].map_color_to(); if(side_map.size()) { return side_map; } } return str_cast(side); } std::string team::get_side_highlight(int side) { return rgb2highlight(get_side_color_range(side+1).mid()); } void team::log_recruitable(){ LOG_NG << "Adding recruitable units: \n"; for (std::set<std::string>::const_iterator it = info_.can_recruit.begin(); it != info_.can_recruit.end(); ++it) { LOG_NG << *it << std::endl; } LOG_NG << "Added all recruitable units\n"; } config team::to_config() const { config cfg; config& result = cfg.add_child("side"); write(result); return result; } namespace player_teams { int village_owner(const map_location& loc) { if(! teams) { return -1; } for(size_t i = 0; i != teams->size(); ++i) { if((*teams)[i].owns_village(loc)) return i; } return -1; } }
25.733173
203
0.638113
[ "vector" ]